Compare

f90f8afb61beb268ca8092e7f3a826b520d3e8da..72732cbee632b1be22b636813c9be3df55c72bd9

Merge tag 'i2c-fixes-7.3-rc8' of git://git.kernel.org/pub/scm/linux/kernel/git/andi.shyti/linux

Pull i2c fixes from Andi Shyti:
 "Three independent clock management fixes, plus one for a simple
  reset mask blunder in the qcom-cci interrupt handler"

* tag 'i2c-fixes-7.3-rc8' of git://git.kernel.org/pub/scm/linux/kernel/git/andi.shyti/linux:
  i2c: xiic: restore non-managed runtime PM to fix clk WARN flood
  i2c: qcom-cci: Fix HALT_ACK reset request being dropped
  i2c: qcom-geni: Restore the source-clock selection policy
  i2c: viai2c-wmt: Fix clock leak in wmt_i2c_probe()

Linus Torvalds <torvalds@linux-foundation.org> · 2026-10-18 18:16 UTC

Browse files
554 files changed, +12590 −2464
modified .mailmap
@@ -101,6 +101,7 @@ Andy Chiu <andybnac@gmail.com> <andy.chiu@sifive.com>
101 101 Andy Chiu <andybnac@gmail.com> <taochiu@synology.com>
102 102 Andy Shevchenko <andy@kernel.org> <andy@smile.org.ua>
103 103 Andy Shevchenko <andy@kernel.org> <ext-andriy.shevchenko@nokia.com>
104 + Andy Yan <andyshrk@163.com> <andy.yan@rock-chips.com>
104 105 Anilkumar Kolli <quic_akolli@quicinc.com> <akolli@codeaurora.org>
105 106 Anirudh Ghayal <quic_aghayal@quicinc.com> <aghayal@codeaurora.org>
106 107 Antoine Tenart <atenart@kernel.org> <antoine.tenart@bootlin.com>
@@ -461,7 +462,8 @@ Johan Hovold <johan@kernel.org> <jhovold@gmail.com>
461 462 Johan Hovold <johan@kernel.org> <johan@hovoldconsulting.com>
462 463 John Crispin <john@phrozen.org> <blogic@openwrt.org>
463 464 John Fastabend <john.fastabend@gmail.com> <john.r.fastabend@intel.com>
464 - John Garry <john.g.garry@oracle.com> <john.garry@huawei.com>
465 + John Garry <john.garry@linux.dev> <john.garry@huawei.com>
466 + John Garry <john.garry@linux.dev> <john.g.garry@oracle.com>
465 467 John Keeping <john@keeping.me.uk> <john@metanate.com>
466 468 John Moon <john@jmoon.dev> <quic_johmoo@quicinc.com>
467 469 John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>
@@ -486,6 +488,7 @@ Juha Yrjola <juha.yrjola@nokia.com>
486 488 Juha Yrjola <juha.yrjola@solidboot.com>
487 489 Julien Thierry <julien.thierry.kdev@gmail.com> <julien.thierry@arm.com>
488 490 Justin Iurman <justin.iurman@gmail.com> <justin.iurman@uliege.be>
491 + Imre Kaloz <kaloz@kernel.org> <kaloz@openwrt.org>
489 492 Ira Weiny <iweiny@kernel.org> <ira.weiny@intel.com>
490 493 Iskren Chernev <me@iskren.info> <iskren.chernev@gmail.com>
491 494 Kalle Valo <kvalo@kernel.org> <kvalo@codeaurora.org>
modified Documentation/admin-guide/ext4.rst
@@ -172,7 +172,8 @@ When mounting an ext4 filesystem, the following option are accepted:
172 172 data=journal
173 173 All data are committed into the journal prior to being written into the
174 174 main file system. Enabling this mode will disable delayed allocation
175 - and O_DIRECT support.
175 + and O_DIRECT support. This feature is deprecated and support
176 + will be removed in January 2028.
176 177
177 178 data=ordered (*)
178 179 All data are forced directly out to the main file system prior to its
@@ -418,7 +419,8 @@ There are 3 different data modes:
418 419 consistent state. This mode is the slowest except when data needs to be read
419 420 from and written to disk at the same time where it outperforms all others
420 421 modes. Enabling this mode will disable delayed allocation and O_DIRECT
421 - support.
422 + support. The data=journal feature is deprecated and support will be
423 + removed in January 2028.
422 424
423 425 /proc entries
424 426 =============
modified Documentation/devicetree/bindings/spi/snps,dw-apb-ssi.yaml
@@ -77,6 +77,7 @@ properties:
77 77 - mscc,ocelot-spi
78 78 - mscc,jaguar2-spi
79 79 - sophgo,sg2042-spi
80 + - syna,sl2610-spi
80 81 - thead,th1520-spi
81 82 - ultrarisc,dp1000-spi
82 83 - const: snps,dw-apb-ssi
modified Documentation/filesystems/propagate_umount.txt
@@ -32,12 +32,12 @@ of set. They can be reparented to the place where the bottom of
32 32 stack is attached to a mount that will survive. NOTE: doing that
33 33 will violate a constraint on having no more than one mount with
34 34 the same parent/mountpoint pair; however, the caller (umount_tree())
35 - will immediately remedy that - it may keep unmounted element attached
36 - to parent, but only if the parent itself is unmounted. Since all
37 - conflicts created by reparenting have common parent *not* in the
38 - set and one side of the conflict (bottom of the stack of overmounts)
39 - is in the set, it will be resolved. However, we rely upon umount_tree()
40 - doing that pretty much immediately after the call of propagate_umount().
35 + will immediately remedy that - it detaches every element of the set
36 + from its parent. Since all conflicts created by reparenting have
37 + common parent *not* in the set and one side of the conflict (bottom
38 + of the stack of overmounts) is in the set, it will be resolved.
39 + However, we rely upon umount_tree() doing that pretty much immediately
40 + after the call of propagate_umount().
41 41
42 42 Algorithm is based on two statements:
43 43 1) for any set S, there is a maximal non-shifting subset of S
modified Documentation/filesystems/sharedsubtree.rst
@@ -564,8 +564,8 @@ f) Unmount semantics
564 564 where 'A' is a mount mounted on mount 'B' at dentry 'b'.
565 565
566 566 If mount 'B' is shared, then all most-recently-mounted mounts at dentry
567 - 'b' on mounts that receive propagation from mount 'B' and does not have
568 - sub-mounts within them are unmounted.
567 + 'b' on mounts that receive propagation from mount 'B' are unmounted as
568 + well, if every mount below them is also unmounted.
569 569
570 570 Example: Let's say 'B1', 'B2', 'B3' are shared mounts that propagate to
571 571 each other.
@@ -584,10 +584,18 @@ f) Unmount semantics
584 584
585 585 So all 'C1', 'C2' and 'C3' should be unmounted.
586 586
587 - If any of 'C2' or 'C3' has some child mounts, then that mount is not
588 - unmounted, but all other mounts are unmounted. However if 'C1' is told
589 - to be unmounted and 'C1' has some sub-mounts, the umount operation is
590 - failed entirely.
587 + If any of 'C2' or 'C3' has a child mount that cannot be unmounted
588 + then that mount is not unmounted. But all other mounts are unmounted.
589 + A child mount that is itself unmounted by the same unmount
590 + propagation does not keep its parent mounted. However if 'C1' is
591 + supposed to be unmounted and 'C1' has some sub-mounts, the unmount
592 + fails.
593 +
594 + A lazy umount (MNT_DETACH) takes a whole tree. Every mount of the
595 + tree then propagates its unmount from its own parent as described
596 + above, so the mounts that receive propagation lose the corresponding
597 + trees as well. Documentation/filesystems/propagate_umount.txt has the
598 + precise rules, including the ones for locked mounts.
591 599
592 600 g) Clone Namespace
593 601
modified Documentation/networking/strparser.rst
@@ -77,7 +77,7 @@ Functions
77 77
78 78 strp_done is called to release any resources held by the stream
79 79 parser instance. This must be called after the stream processor
80 - has been stopped.
80 + has been stopped. The socket lock must not be held.
81 81
82 82 ::
83 83
modified MAINTAINERS
@@ -3012,7 +3012,7 @@ F: arch/arm/boot/dts/ti/omap/omap3-igep*
3012 3012
3013 3013 ARM/INTEL IXP4XX ARM ARCHITECTURE
3014 3014 M: Linus Walleij <linusw@kernel.org>
3015 - M: Imre Kaloz <kaloz@openwrt.org>
3015 + M: Imre Kaloz <kaloz@kernel.org>
3016 3016 L: linux-arm-kernel@lists.infradead.org (moderated for non-subscribers)
3017 3017 S: Maintained
3018 3018 F: Documentation/devicetree/bindings/arm/intel-ixp4xx.yaml
@@ -8013,6 +8013,7 @@ F: include/uapi/drm/ivpu_accel.h
8013 8013
8014 8014 DRM ACCEL DRIVER FOR ROCKCHIP NPU
8015 8015 M: Tomeu Vizoso <tomeu@tomeuvizoso.net>
8016 + R: Heiko Stuebner <heiko@sntech.de>
8016 8017 L: dri-devel@lists.freedesktop.org
8017 8018 S: Supported
8018 8019 T: git https://gitlab.freedesktop.org/drm/misc/kernel.git
@@ -8170,7 +8171,6 @@ F: drivers/gpu/drm/tiny/hx8357d.c
8170 8171
8171 8172 DRM DRIVER FOR HYPERV SYNTHETIC VIDEO DEVICE
8172 8173 M: Dexuan Cui <decui@microsoft.com>
8173 - M: Long Li <longli@microsoft.com>
8174 8174 M: Saurabh Sengar <ssengar@linux.microsoft.com>
8175 8175 L: linux-hyperv@vger.kernel.org
8176 8176 L: dri-devel@lists.freedesktop.org
@@ -8575,7 +8575,7 @@ F: Documentation/devicetree/bindings/display/panel/synaptics,r63353.yaml
8575 8575 F: drivers/gpu/drm/panel/panel-synaptics-r63353.c
8576 8576
8577 8577 DRM DRIVER FOR SYNOPSYS DESIGNWARE DISPLAYPORT BRIDGE
8578 - M: Andy Yan <andy.yan@rock-chips.com>
8578 + M: Andy Yan <andyshrk@163.com>
8579 8579 S: Maintained
8580 8580 T: git https://gitlab.freedesktop.org/drm/misc/kernel.git
8581 8581 F: Documentation/devicetree/bindings/display/rockchip/rockchip,dw-dp.yaml
@@ -8928,7 +8928,7 @@ F: include/linux/platform_data/shmob_drm.h
8928 8928 DRM DRIVERS FOR ROCKCHIP
8929 8929 M: Sandy Huang <hjc@rock-chips.com>
8930 8930 M: Heiko Stübner <heiko@sntech.de>
8931 - M: Andy Yan <andy.yan@rock-chips.com>
8931 + M: Andy Yan <andyshrk@163.com>
8932 8932 L: dri-devel@lists.freedesktop.org
8933 8933 L: linux-rockchip@lists.infradead.org
8934 8934 S: Maintained
@@ -9861,7 +9861,7 @@ L: linux-ext4@vger.kernel.org
9861 9861 S: Maintained
9862 9862 W: http://ext4.wiki.kernel.org
9863 9863 Q: http://patchwork.ozlabs.org/project/linux-ext4/list/
9864 - T: git git://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git
9864 + T: git git://git.kernel.org/pub/scm/linux/kernel/git/tytso/ext4.git dev
9865 9865 F: Documentation/filesystems/ext4/
9866 9866 F: fs/ext4/
9867 9867 F: include/trace/events/ext4.h
@@ -10102,7 +10102,6 @@ F: tools/testing/selftests/mount_setattr/
10102 10102
10103 10103 FILESYSTEMS [IOMAP]
10104 10104 M: Christian Brauner <brauner@kernel.org>
10105 - R: Darrick J. Wong <djwong@kernel.org>
10106 10105 L: linux-xfs@vger.kernel.org
10107 10106 L: linux-fsdevel@vger.kernel.org
10108 10107 S: Supported
@@ -12161,11 +12160,9 @@ S: Maintained
12161 12160 F: drivers/media/i2c/hi847.c
12162 12161
12163 12162 Hyper-V/Azure CORE AND DRIVERS
12164 - M: "K. Y. Srinivasan" <kys@microsoft.com>
12165 12163 M: Haiyang Zhang <haiyangz@microsoft.com>
12166 12164 M: Wei Liu <wei.liu@kernel.org>
12167 12165 M: Dexuan Cui <decui@microsoft.com>
12168 - M: Long Li <longli@microsoft.com>
12169 12166 L: linux-hyperv@vger.kernel.org
12170 12167 S: Supported
12171 12168 T: git git://git.kernel.org/pub/scm/linux/kernel/git/hyperv/linux.git
@@ -12883,7 +12880,7 @@ S: Maintained
12883 12880 F: drivers/power/supply/ip5xxx_power.c
12884 12881
12885 12882 INNOSILICON HDMI BRIDGE DRIVER
12886 - M: Andy Yan <andy.yan@rock-chips.com>
12883 + M: Andy Yan <andyshrk@163.com>
12887 12884 L: dri-devel@lists.freedesktop.org
12888 12885 S: Maintained
12889 12886 T: git https://gitlab.freedesktop.org/drm/misc/kernel.git
@@ -18818,6 +18815,7 @@ F: drivers/hwmon/nct7363.c
18818 18815
18819 18816 NETCONSOLE
18820 18817 M: Breno Leitao <leitao@debian.org>
18818 + R: Gustavo Luiz Duarte <gustavold@gmail.com>
18821 18819 S: Maintained
18822 18820 F: Documentation/networking/netconsole.rst
18823 18821 F: drivers/net/netconsole.c
modified Makefile
@@ -2,7 +2,7 @@
2 2 VERSION = 7
3 3 PATCHLEVEL = 3
4 4 SUBLEVEL = 0
5 - EXTRAVERSION = -rc6
5 + EXTRAVERSION = -rc7
6 6 NAME = Baby Opossum Posse
7 7
8 8 # *DOCUMENTATION*
modified arch/arm/boot/dts/ti/omap/dra7xx-clocks.dtsi
@@ -1376,8 +1376,8 @@
1376 1376 clocks = <&apll_pcie_ck>;
1377 1377 #clock-cells = <0>;
1378 1378 reg = <0x021c>;
1379 + ti,dividers = <2>, <1>;
1379 1380 ti,bit-shift = <8>;
1380 - ti,max-div = <2>;
1381 1381 };
1382 1382
1383 1383 apll_pcie_clkvcoldo: clock-apll-pcie-clkvcoldo {
modified arch/arm/configs/sama5_defconfig
@@ -69,8 +69,8 @@ CONFIG_BLK_DEV_SD=y
69 69 # CONFIG_BLK_DEV_BSG is not set
70 70 # CONFIG_SCSI_LOWLEVEL is not set
71 71 CONFIG_NETDEVICES=y
72 - CONFIG_NET_DSA_MICROCHIP_KSZ9477=m
73 - CONFIG_NET_DSA_MICROCHIP_KSZ9477_SPI=m
72 + CONFIG_NET_DSA_MICROCHIP_KSZ_COMMON=m
73 + CONFIG_NET_DSA_MICROCHIP_KSZ_SPI=m
74 74 # CONFIG_NET_VENDOR_BROADCOM is not set
75 75 CONFIG_MACB=y
76 76 # CONFIG_NET_VENDOR_CIRRUS is not set
modified arch/arm64/boot/dts/freescale/fsl-lx216x.dtsi
@@ -1602,7 +1602,7 @@
1602 1602 };
1603 1603
1604 1604 dspi2_miso_mosi_pins: iic5-spi3-pins {
1605 - pinctrl-single,bits = <0x3 (0x2 << 9) (0x7 << 9)>;
1605 + pinctrl-single,bits = <0x0 (0x3 << 9) (0x7 << 9)>;
1606 1606 };
1607 1607
1608 1608 i2c5_pins: iic6-i2c-pins {
@@ -1622,7 +1622,7 @@
1622 1622 };
1623 1623
1624 1624 gpio1_31_28_pins: xspi1-data74-gpio-pins {
1625 - pinctrl-single,bits = <0x0 0x1 (0x7 << 15)>;
1625 + pinctrl-single,bits = <0x0 (0x1 << 15) (0x7 << 15)>;
1626 1626 };
1627 1627
1628 1628 fspi_data30_pins: xspi1-data30-pins {
@@ -1630,7 +1630,7 @@
1630 1630 };
1631 1631
1632 1632 gpio1_27_24_pins: xspi1-data30-gpio-pins {
1633 - pinctrl-single,bits = <0x0 0x1 (0x7 << 18)>;
1633 + pinctrl-single,bits = <0x0 (0x1 << 18) (0x7 << 18)>;
1634 1634 };
1635 1635
1636 1636 fspi_dqs_sck_cs10_pins: xspi1-base-pins {
@@ -1638,7 +1638,7 @@
1638 1638 };
1639 1639
1640 1640 gpio1_23_20_pins: xspi1-base-gpio-pins {
1641 - pinctrl-single,bits = <0x0 0x1 (0x7 << 21)>;
1641 + pinctrl-single,bits = <0x0 (0x1 << 21) (0x7 << 21)>;
1642 1642 };
1643 1643
1644 1644 esdhc0_cmd_data30_clk_vsel_pins: sdhc1-base-sdhc-vsel-pins {
@@ -1687,12 +1687,19 @@
1687 1687 };
1688 1688
1689 1689 /* RCWSR14 */
1690 + /*
1691 + * IIC1_PMUX is a single bit at RCWSR14[10], but bit-per-mux
1692 + * uses the mask for the field to clear before applying the
1693 + * value.
1694 + * So bits 11 and 12, which are reserved, are written as 0
1695 + * on every mux switch, it is harmless.
1696 + */
1690 1697 i2c0_pins: iic1-i2c-pins {
1691 - pinctrl-single,bits = <0x8 0x0 (0x1 << 10)>;
1698 + pinctrl-single,bits = <0x8 0x0 (0x7 << 10)>;
1692 1699 };
1693 1700
1694 1701 gpio0_3_2_pins: iic1-gpio-pins {
1695 - pinctrl-single,bits = <0x8 (0x1 << 10) (0x1 << 10)>;
1702 + pinctrl-single,bits = <0x8 (0x1 << 10) (0x7 << 10)>;
1696 1703 };
1697 1704 };
1698 1705
modified arch/arm64/boot/dts/freescale/imx8mp-var-dart-sonata.dts
@@ -511,6 +511,7 @@
511 511 pinctrl-2 = <&pinctrl_usdhc2_200mhz>, <&pinctrl_usdhc2_gpio>;
512 512 cd-gpios = <&gpio2 12 GPIO_ACTIVE_LOW>;
513 513 vmmc-supply = <&reg_usdhc2_vmmc>;
514 + vqmmc-supply = <&ldo5>;
514 515 bus-width = <4>;
515 516 status = "okay";
516 517 };
modified arch/arm64/boot/dts/nvidia/tegra264-p4071-0000+p3834.dtsi
@@ -9,4 +9,17 @@
9 9 chosen {
10 10 stdout-path = "serial0:115200n8";
11 11 };
12 +
13 + bus@0 {
14 + pwm@c6a0000 {
15 + status = "okay";
16 + };
17 + };
18 +
19 + fan: pwm-fan {
20 + compatible = "pwm-fan";
21 + cooling-levels = <77 102 140 192 255>;
22 + pwms = <&pwm4 0 40000>;
23 + #cooling-cells = <2>;
24 + };
12 25 };
modified arch/arm64/boot/dts/nvidia/tegra264.dtsi
@@ -3356,6 +3356,18 @@
3356 3356 status = "disabled";
3357 3357 };
3358 3358
3359 + pwm4: pwm@c6a0000 {
3360 + compatible = "nvidia,tegra264-pwm";
3361 + reg = <0x0 0xc6a0000 0x0 0x10000>;
3362 + status = "disabled";
3363 +
3364 + clocks = <&bpmp TEGRA264_CLK_PWM4>;
3365 + resets = <&bpmp TEGRA264_RESET_PWM4>;
3366 + reset-names = "pwm";
3367 +
3368 + #pwm-cells = <2>;
3369 + };
3370 +
3359 3371 pinmux_aon: pinmux@c7a2000 {
3360 3372 compatible = "nvidia,tegra264-pinmux-aon";
3361 3373 reg = <0x0 0x0c7a2000 0x0 0x2000>;
@@ -3537,11 +3549,11 @@
3537 3549
3538 3550 pci@c000000 {
3539 3551 compatible = "nvidia,tegra264-pcie";
3540 - reg = <0xd0 0xb0000000 0x0 0x10000000>,
3541 - <0x00 0x0c000000 0x0 0x00004000>,
3552 + reg = <0x00 0x0c000000 0x0 0x00004000>,
3542 3553 <0x00 0x0c004000 0x0 0x00001000>,
3543 - <0x00 0x0c005000 0x0 0x00001000>;
3544 - reg-names = "ecam", "xal", "xtl", "xtl-pri";
3554 + <0x00 0x0c005000 0x0 0x00001000>,
3555 + <0xd0 0xb0000000 0x0 0x10000000>;
3556 + reg-names = "xal", "xtl", "xtl-pri", "ecam";
3545 3557 #address-cells = <3>;
3546 3558 #size-cells = <2>;
3547 3559 device_type = "pci";
@@ -3565,6 +3577,16 @@
3565 3577
3566 3578 nvidia,bpmp = <&bpmp 0>;
3567 3579 status = "disabled";
3580 +
3581 + pcie@0 {
3582 + device_type = "pci";
3583 + compatible = "pciclass,0604";
3584 + reg = <0x0 0x0 0x0 0x0 0x0>;
3585 + bus-range = <0x01 0xff>;
3586 + #address-cells = <3>;
3587 + #size-cells = <2>;
3588 + ranges;
3589 + };
3568 3590 };
3569 3591
3570 3592 pinmux_main: pinmux@c281000 {
@@ -3661,6 +3683,66 @@
3661 3683 status = "disabled";
3662 3684 };
3663 3685
3686 + pwm2: pwm@c5e0000 {
3687 + compatible = "nvidia,tegra264-pwm";
3688 + reg = <0x0 0xc5e0000 0x0 0x10000>;
3689 + status = "disabled";
3690 +
3691 + clocks = <&bpmp TEGRA264_CLK_PWM2>;
3692 + resets = <&bpmp TEGRA264_RESET_PWM2>;
3693 + reset-names = "pwm";
3694 +
3695 + #pwm-cells = <2>;
3696 + };
3697 +
3698 + pwm3: pwm@c5f0000 {
3699 + compatible = "nvidia,tegra264-pwm";
3700 + reg = <0x0 0xc5f0000 0x0 0x10000>;
3701 + status = "disabled";
3702 +
3703 + clocks = <&bpmp TEGRA264_CLK_PWM3>;
3704 + resets = <&bpmp TEGRA264_RESET_PWM3>;
3705 + reset-names = "pwm";
3706 +
3707 + #pwm-cells = <2>;
3708 + };
3709 +
3710 + pwm5: pwm@c600000 {
3711 + compatible = "nvidia,tegra264-pwm";
3712 + reg = <0x0 0xc600000 0x0 0x10000>;
3713 + status = "disabled";
3714 +
3715 + clocks = <&bpmp TEGRA264_CLK_PWM5>;
3716 + resets = <&bpmp TEGRA264_RESET_PWM5>;
3717 + reset-names = "pwm";
3718 +
3719 + #pwm-cells = <2>;
3720 + };
3721 +
3722 + pwm9: pwm@c610000 {
3723 + compatible = "nvidia,tegra264-pwm";
3724 + reg = <0x0 0xc610000 0x0 0x10000>;
3725 + status = "disabled";
3726 +
3727 + clocks = <&bpmp TEGRA264_CLK_PWM9>;
3728 + resets = <&bpmp TEGRA264_RESET_PWM9>;
3729 + reset-names = "pwm";
3730 +
3731 + #pwm-cells = <2>;
3732 + };
3733 +
3734 + pwm10: pwm@c620000 {
3735 + compatible = "nvidia,tegra264-pwm";
3736 + reg = <0x0 0xc620000 0x0 0x10000>;
3737 + status = "disabled";
3738 +
3739 + clocks = <&bpmp TEGRA264_CLK_PWM10>;
3740 + resets = <&bpmp TEGRA264_RESET_PWM10>;
3741 + reset-names = "pwm";
3742 +
3743 + #pwm-cells = <2>;
3744 + };
3745 +
3664 3746 i2c0: i2c@c630000 {
3665 3747 compatible = "nvidia,tegra264-i2c";
3666 3748 reg = <0x00 0x0c630000 0x0 0x10000>;
@@ -3990,12 +4072,12 @@
3990 4072
3991 4073 pci@8400000 {
3992 4074 compatible = "nvidia,tegra264-pcie";
3993 - reg = <0xa8 0xb0000000 0x0 0x10000000>,
3994 - <0x00 0x08400000 0x0 0x00004000>,
4075 + reg = <0x00 0x08400000 0x0 0x00004000>,
3995 4076 <0x00 0x08404000 0x0 0x00001000>,
3996 4077 <0x00 0x08405000 0x0 0x00001000>,
3997 - <0x00 0x08410000 0x0 0x00010000>;
3998 - reg-names = "ecam", "xal", "xtl", "xtl-pri", "xpl";
4078 + <0x00 0x08410000 0x0 0x00010000>,
4079 + <0xa8 0xb0000000 0x0 0x10000000>;
4080 + reg-names = "xal", "xtl", "xtl-pri", "xpl", "ecam";
3999 4081 #address-cells = <3>;
4000 4082 #size-cells = <2>;
4001 4083 device_type = "pci";
@@ -4018,16 +4100,26 @@
4018 4100
4019 4101 nvidia,bpmp = <&bpmp 1>;
4020 4102 status = "disabled";
4103 +
4104 + pcie@0 {
4105 + device_type = "pci";
4106 + compatible = "pciclass,0604";
4107 + reg = <0x0 0x0 0x0 0x0 0x0>;
4108 + bus-range = <0x01 0xff>;
4109 + #address-cells = <3>;
4110 + #size-cells = <2>;
4111 + ranges;
4112 + };
4021 4113 };
4022 4114
4023 4115 pci@8420000 {
4024 4116 compatible = "nvidia,tegra264-pcie";
4025 - reg = <0xb0 0xb0000000 0x0 0x10000000>,
4026 - <0x00 0x08420000 0x0 0x00004000>,
4117 + reg = <0x00 0x08420000 0x0 0x00004000>,
4027 4118 <0x00 0x08424000 0x0 0x00001000>,
4028 4119 <0x00 0x08425000 0x0 0x00001000>,
4029 - <0x00 0x08430000 0x0 0x00010000>;
4030 - reg-names = "ecam", "xal", "xtl", "xtl-pri", "xpl";
4120 + <0x00 0x08430000 0x0 0x00010000>,
4121 + <0xb0 0xb0000000 0x0 0x10000000>;
4122 + reg-names = "xal", "xtl", "xtl-pri", "xpl", "ecam";
4031 4123 #address-cells = <3>;
4032 4124 #size-cells = <2>;
4033 4125 device_type = "pci";
@@ -4050,16 +4142,26 @@
4050 4142
4051 4143 nvidia,bpmp = <&bpmp 2>;
4052 4144 status = "disabled";
4145 +
4146 + pcie@0 {
4147 + device_type = "pci";
4148 + compatible = "pciclass,0604";
4149 + reg = <0x0 0x0 0x0 0x0 0x0>;
4150 + bus-range = <0x01 0xff>;
4151 + #address-cells = <3>;
4152 + #size-cells = <2>;
4153 + ranges;
4154 + };
4053 4155 };
4054 4156
4055 4157 pci@8440000 {
4056 4158 compatible = "nvidia,tegra264-pcie";
4057 - reg = <0xb8 0xb0000000 0x0 0x10000000>,
4058 - <0x00 0x08440000 0x0 0x00004000>,
4159 + reg = <0x00 0x08440000 0x0 0x00004000>,
4059 4160 <0x00 0x08444000 0x0 0x00001000>,
4060 4161 <0x00 0x08445000 0x0 0x00001000>,
4061 - <0x00 0x08450000 0x0 0x00010000>;
4062 - reg-names = "ecam", "xal", "xtl", "xtl-pri", "xpl";
4162 + <0x00 0x08450000 0x0 0x00010000>,
4163 + <0xb8 0xb0000000 0x0 0x10000000>;
4164 + reg-names = "xal", "xtl", "xtl-pri", "xpl", "ecam";
4063 4165 #address-cells = <3>;
4064 4166 #size-cells = <2>;
4065 4167 device_type = "pci";
@@ -4082,16 +4184,26 @@
4082 4184
4083 4185 nvidia,bpmp = <&bpmp 3>;
4084 4186 status = "disabled";
4187 +
4188 + pcie@0 {
4189 + device_type = "pci";
4190 + compatible = "pciclass,0604";
4191 + reg = <0x0 0x0 0x0 0x0 0x0>;
4192 + bus-range = <0x01 0xff>;
4193 + #address-cells = <3>;
4194 + #size-cells = <2>;
4195 + ranges;
4196 + };
4085 4197 };
4086 4198
4087 4199 pci@8460000 {
4088 4200 compatible = "nvidia,tegra264-pcie";
4089 - reg = <0xc0 0xb0000000 0x0 0x10000000>,
4090 - <0x00 0x08460000 0x0 0x00004000>,
4201 + reg = <0x00 0x08460000 0x0 0x00004000>,
4091 4202 <0x00 0x08464000 0x0 0x00001000>,
4092 4203 <0x00 0x08465000 0x0 0x00001000>,
4093 - <0x00 0x08470000 0x0 0x00010000>;
4094 - reg-names = "ecam", "xal", "xtl", "xtl-pri", "xpl";
4204 + <0x00 0x08470000 0x0 0x00010000>,
4205 + <0xc0 0xb0000000 0x0 0x10000000>;
4206 + reg-names = "xal", "xtl", "xtl-pri", "xpl", "ecam";
4095 4207 #address-cells = <3>;
4096 4208 #size-cells = <2>;
4097 4209 device_type = "pci";
@@ -4114,16 +4226,26 @@
4114 4226
4115 4227 nvidia,bpmp = <&bpmp 4>;
4116 4228 status = "disabled";
4229 +
4230 + pcie@0 {
4231 + device_type = "pci";
4232 + compatible = "pciclass,0604";
4233 + reg = <0x0 0x0 0x0 0x0 0x0>;
4234 + bus-range = <0x01 0xff>;
4235 + #address-cells = <3>;
4236 + #size-cells = <2>;
4237 + ranges;
4238 + };
4117 4239 };
4118 4240
4119 4241 pci@8480000 {
4120 4242 compatible = "nvidia,tegra264-pcie";
4121 - reg = <0xc8 0xb0000000 0x0 0x10000000>,
4122 - <0x00 0x08480000 0x0 0x00004000>,
4243 + reg = <0x00 0x08480000 0x0 0x00004000>,
4123 4244 <0x00 0x08484000 0x0 0x00001000>,
4124 4245 <0x00 0x08485000 0x0 0x00001000>,
4125 - <0x00 0x08490000 0x0 0x00010000>;
4126 - reg-names = "ecam", "xal", "xtl", "xtl-pri", "xpl";
4246 + <0x00 0x08490000 0x0 0x00010000>,
4247 + <0xc8 0xb0000000 0x0 0x10000000>;
4248 + reg-names = "xal", "xtl", "xtl-pri", "xpl", "ecam";
4127 4249 #address-cells = <3>;
4128 4250 #size-cells = <2>;
4129 4251 device_type = "pci";
@@ -4146,6 +4268,16 @@
4146 4268
4147 4269 nvidia,bpmp = <&bpmp 5>;
4148 4270 status = "disabled";
4271 +
4272 + pcie@0 {
4273 + device_type = "pci";
4274 + compatible = "pciclass,0604";
4275 + reg = <0x0 0x0 0x0 0x0 0x0>;
4276 + bus-range = <0x01 0xff>;
4277 + #address-cells = <3>;
4278 + #size-cells = <2>;
4279 + ranges;
4280 + };
4149 4281 };
4150 4282 };
4151 4283
modified arch/arm64/boot/dts/qcom/x1-microsoft-denali.dtsi
@@ -863,11 +863,11 @@
863 863 };
864 864
865 865 &lpass_vamacro {
866 - pinctrl-0 = <&dmic01_default>, <&dmic23_default>;
866 + pinctrl-0 = <&dmic01_default>;
867 867 pinctrl-names = "default";
868 868
869 869 vdd-micb-supply = <&vreg_l1b_1p8>;
870 - qcom,dmic-sample-rate = <4800000>;
870 + qcom,dmic-sample-rate = <2400000>;
871 871 };
872 872
873 873 &mdss {
modified arch/arm64/include/asm/el2_setup.h
@@ -421,8 +421,9 @@
421 421 mov x2, xzr
422 422 mrs x1, id_aa64dfr0_el1
423 423 ubfx x1, x1, #ID_AA64DFR0_EL1_PMUVer_SHIFT, #4
424 - cmp x1, #ID_AA64DFR0_EL1_PMUVer_V3P9
425 - b.lt .Lskip_pmuv3p9_\@
424 + cmp x1, #ID_AA64DFR0_EL1_PMUVer_IMP_DEF
425 + ccmp x1, #ID_AA64DFR0_EL1_PMUVer_V3P9, #8, ne
426 + b.lt .Lskip_pmuv3p9_\@ // Skip if < PMUv3p9 or IMP_DEF
426 427
427 428 orr x0, x0, #HDFGRTR2_EL2_nPMICNTR_EL0
428 429 orr x0, x0, #HDFGRTR2_EL2_nPMICFILTR_EL0
modified arch/arm64/kernel/Makefile
@@ -25,6 +25,9 @@ KASAN_SANITIZE_stacktrace.o := n
25 25 KCOV_INSTRUMENT_entry-common.o := n
26 26 KCOV_INSTRUMENT_idle.o := n
27 27
28 + # Softirq stack switching can run outside interrupt context.
29 + KCOV_INSTRUMENT_irq.o := n
30 +
28 31 # Object file lists.
29 32 obj-y := debug-monitors.o entry.o irq.o fpsimd.o \
30 33 entry-common.o process.o ptrace.o \
modified arch/nios2/include/asm/checksum.h
@@ -27,7 +27,7 @@ static inline __sum16 csum_fold(__wsum sum)
27 27 "add %0, %0, r8\n"
28 28 "nor %0, %0, %0\n"
29 29 : "=r" (sum)
30 - : "r" (sum << 16), "0" (sum)
30 + : "r" ((__force u32)sum << 16), "0" (sum)
31 31 : "r8");
32 32 return (__force __sum16) sum;
33 33 }
modified arch/riscv/Kconfig
@@ -453,9 +453,10 @@ config SMP
453 453 config NR_CPUS
454 454 int "Maximum number of CPUs (2-512)"
455 455 depends on SMP
456 - range 2 512 if !RISCV_SBI_V01
457 - range 2 32 if RISCV_SBI_V01 && 32BIT
456 + range 2 512 if !RISCV_SBI_V01 && 64BIT
457 + range 2 128 if !RISCV_SBI_V01 && 32BIT
458 458 range 2 64 if RISCV_SBI_V01 && 64BIT
459 + range 2 32 if RISCV_SBI_V01 && 32BIT
459 460 default "32" if 32BIT
460 461 default "64" if RISCV_SBI_V01 && 64BIT
461 462 default "256" if !RISCV_SBI_V01 && 64BIT
modified arch/riscv/Kconfig.errata
@@ -46,7 +46,7 @@ config ERRATA_MIPS_P8700_PAUSE_OPCODE
46 46
47 47 config ERRATA_SIFIVE
48 48 bool "SiFive errata"
49 - depends on RISCV_ALTERNATIVE
49 + depends on RISCV_ALTERNATIVE && 64BIT
50 50 help
51 51 All SiFive errata Kconfig depend on this Kconfig. Disabling
52 52 this Kconfig will disable all SiFive errata. Please say "Y"
@@ -96,6 +96,20 @@ config ERRATA_STARFIVE_JH7100
96 96 Say "Y" if you want to support the BeagleV Starlight and/or
97 97 StarFive VisionFive V1 boards.
98 98
99 + config ERRATA_SIFIVE_MAL_9092
100 + bool "Apply SiFive HLV/HLVX/HSV fence errata"
101 + depends on ERRATA_SIFIVE && 64BIT
102 + default y
103 + help
104 + This will apply the SiFive MAL-9092 errata to add fence.rw
105 + instructions around all HLV/HLVX/HSV instructions.
106 +
107 + Note: HSTATUS.HU is cleared during KVM initialization. If future
108 + changes enable HSTATUS.HU to allow hypervisor instructions in
109 + U-mode, additional errata handling may be required.
110 +
111 + If you don't know what to do here, say "Y".
112 +
99 113 config ERRATA_THEAD
100 114 bool "T-HEAD errata"
101 115 depends on RISCV_ALTERNATIVE
@@ -146,6 +160,7 @@ config ERRATA_THEAD_PMU
146 160 config ERRATA_THEAD_GHOSTWRITE
147 161 bool "Apply T-Head Ghostwrite errata"
148 162 depends on ERRATA_THEAD && RISCV_ISA_XTHEADVECTOR
163 + select RISCV_ALTERNATIVE_EARLY
149 164 default y
150 165 help
151 166 The T-Head C9xx cores have a vulnerability in the xtheadvector
modified arch/riscv/Kconfig.socs
@@ -34,6 +34,7 @@ config ARCH_RENESAS
34 34 config ARCH_SIFIVE
35 35 bool "SiFive SoCs"
36 36 select ERRATA_SIFIVE
37 + depends on 64BIT
37 38 help
38 39 This enables support for SiFive SoC platform hardware.
39 40
modified arch/riscv/boot/dts/microchip/mpfs-beaglev-fire.dts
@@ -90,10 +90,6 @@
90 90 };
91 91
92 92 &gpio0 {
93 - interrupts = <13>, <14>, <15>, <16>,
94 - <17>, <18>, <19>, <20>,
95 - <21>, <22>, <23>, <24>,
96 - <25>, <26>;
97 93 ngpios = <14>;
98 94 gpio-line-names = "", "", "", "", "", "", "",
99 95 "", "", "", "", "", "SD_CARD_CS", "USER_BUTTON";
@@ -101,12 +97,6 @@
101 97 };
102 98
103 99 &gpio1 {
104 - interrupts = <27>, <28>, <29>, <30>,
105 - <31>, <32>, <33>, <34>,
106 - <35>, <36>, <37>, <38>,
107 - <39>, <40>, <41>, <42>,
108 - <43>, <44>, <45>, <46>,
109 - <47>, <48>, <49>, <50>;
110 100 ngpios = <24>;
111 101 gpio-line-names = "", "", "", "", "", "", "", "", "", "",
112 102 "", "", "", "", "", "", "", "", "", "",
@@ -115,14 +105,6 @@
115 105 };
116 106
117 107 &gpio2 {
118 - interrupts = <53>, <53>, <53>, <53>,
119 - <53>, <53>, <53>, <53>,
120 - <53>, <53>, <53>, <53>,
121 - <53>, <53>, <53>, <53>,
122 - <53>, <53>, <53>, <53>,
123 - <53>, <53>, <53>, <53>,
124 - <53>, <53>, <53>, <53>,
125 - <53>, <53>, <53>, <53>;
126 108 ngpios = <32>;
127 109 gpio-line-names = "P8_PIN3_USER_LED_0", "P8_PIN4_USER_LED_1", "P8_PIN5_USER_LED_2",
128 110 "P8_PIN6_USER_LED_3", "P8_PIN7_USER_LED_4", "P8_PIN8_USER_LED_5",
modified arch/riscv/errata/sifive/errata.c
@@ -51,6 +51,22 @@ static bool errata_cip_1200_check_func(unsigned long arch_id, unsigned long imp
51 51 return true;
52 52 }
53 53
54 + static bool errata_mal_9092_check_func(unsigned long arch_id, unsigned long impid)
55 + {
56 + /*
57 + * Affected cores:
58 + * Architecture ID: 0x8000000000000109
59 + * Implementation ID: 0x19251031, 0x19251217, 0x19260320
60 + */
61 +
62 + if (arch_id != 0x8000000000000109)
63 + return false;
64 + if (impid != 0x19251031 && impid != 0x19251217 && impid != 0x19260320)
65 + return false;
66 +
67 + return true;
68 + }
69 +
54 70 static struct errata_info_t errata_list[ERRATA_SIFIVE_NUMBER] = {
55 71 {
56 72 .name = "cip-453",
@@ -60,6 +76,10 @@ static struct errata_info_t errata_list[ERRATA_SIFIVE_NUMBER] = {
60 76 .name = "cip-1200",
61 77 .check_func = errata_cip_1200_check_func
62 78 },
79 + {
80 + .name = "mal-9092",
81 + .check_func = errata_mal_9092_check_func
82 + },
63 83 };
64 84
65 85 static u32 __init_or_module sifive_errata_probe(unsigned long archid,
modified arch/riscv/include/asm/cpufeature.h
@@ -40,6 +40,8 @@ extern u32 thead_vlenb_of;
40 40
41 41 void __init riscv_user_isa_enable(void);
42 42
43 + void riscv_clear_hypervisor_csr(void);
44 +
43 45 #define _RISCV_ISA_EXT_DATA(_name, _id, _subset_exts, _subset_exts_size, _validate) { \
44 46 .name = #_name, \
45 47 .property = #_name, \
modified arch/riscv/include/asm/errata_list_vendors.h
@@ -11,7 +11,8 @@
11 11 #ifdef CONFIG_ERRATA_SIFIVE
12 12 #define ERRATA_SIFIVE_CIP_453 0
13 13 #define ERRATA_SIFIVE_CIP_1200 1
14 - #define ERRATA_SIFIVE_NUMBER 2
14 + #define ERRATA_SIFIVE_MAL_9092 2
15 + #define ERRATA_SIFIVE_NUMBER 3
15 16 #endif
16 17
17 18 #ifdef CONFIG_ERRATA_THEAD
modified arch/riscv/include/asm/futex.h
@@ -40,6 +40,7 @@ arch_futex_atomic_op_inuser(int op, int oparg, int *oval, u32 __user *uaddr)
40 40
41 41 if (!access_ok(uaddr, sizeof(u32)))
42 42 return -EFAULT;
43 + uaddr = untagged_addr(uaddr);
43 44
44 45 switch (op) {
45 46 case FUTEX_OP_SET:
@@ -82,6 +83,7 @@ futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr,
82 83
83 84 if (!access_ok(uaddr, sizeof(u32)))
84 85 return -EFAULT;
86 + uaddr = untagged_addr(uaddr);
85 87
86 88 __enable_user_access();
87 89 __asm__ __volatile__ (
modified arch/riscv/include/asm/insn-def.h
@@ -192,18 +192,28 @@
192 192 INSN_R(OPCODE_SYSTEM, FUNC3(0), FUNC7(49), \
193 193 __RD(0), RS1(gaddr), RS2(vmid))
194 194
195 + #define ALT_SIFIVE_MAL_9092_FENCE \
196 + ALTERNATIVE("nop", "fence rw, rw", SIFIVE_VENDOR_ID, \
197 + ERRATA_SIFIVE_MAL_9092, CONFIG_ERRATA_SIFIVE_MAL_9092)
198 +
195 199 #define HLVX_HU(dest, addr) \
200 + ALT_SIFIVE_MAL_9092_FENCE "\n" \
196 201 INSN_R(OPCODE_SYSTEM, FUNC3(4), FUNC7(50), \
197 - RD(dest), RS1(addr), __RS2(3))
202 + RD(dest), RS1(addr), __RS2(3)) "\n" \
203 + ALT_SIFIVE_MAL_9092_FENCE
198 204
199 205 #define HLV_W(dest, addr) \
206 + ALT_SIFIVE_MAL_9092_FENCE "\n" \
200 207 INSN_R(OPCODE_SYSTEM, FUNC3(4), FUNC7(52), \
201 - RD(dest), RS1(addr), __RS2(0))
208 + RD(dest), RS1(addr), __RS2(0)) "\n" \
209 + ALT_SIFIVE_MAL_9092_FENCE
202 210
203 211 #ifdef CONFIG_64BIT
204 212 #define HLV_D(dest, addr) \
213 + ALT_SIFIVE_MAL_9092_FENCE "\n" \
205 214 INSN_R(OPCODE_SYSTEM, FUNC3(4), FUNC7(54), \
206 - RD(dest), RS1(addr), __RS2(0))
215 + RD(dest), RS1(addr), __RS2(0)) "\n" \
216 + ALT_SIFIVE_MAL_9092_FENCE
207 217 #else
208 218 #define HLV_D(dest, addr) \
209 219 __ASM_STR(.error "hlv.d requires 64-bit support")
modified arch/riscv/include/asm/scs.h
@@ -4,6 +4,7 @@
4 4
5 5 #ifdef __ASSEMBLER__
6 6 #include <asm/asm-offsets.h>
7 + #include <asm/csr.h>
7 8
8 9 #ifdef CONFIG_SHADOW_CALL_STACK
9 10
@@ -22,9 +23,17 @@
22 23 REG_L gp, TASK_TI_SCS_SP(tp)
23 24 .endm
24 25
25 - /* Load task_scs_sp(current) to gp, but only if tp has changed. */
26 - .macro scs_load_current_if_task_changed prev
27 - beq \prev, tp, _skip_scs
26 + /*
27 + * Load task_scs_sp(current) to gp, but only when the trap came from U-mode.
28 + * The source privilege level is taken from the saved sstatus.SPP bit (written
29 + * by hardware on trap entry), not by comparing tp. tp is a user-writable
30 + * register, so gating the shadow call stack reload on it let a user task that
31 + * set tp == &current skip the reload and run the kernel with an attacker
32 + * controlled gp (the shadow call stack pointer).
33 + */
34 + .macro scs_load_current_if_from_user status, tmp
35 + andi \tmp, \status, SR_SPP
36 + bnez \tmp, _skip_scs
28 37 scs_load_current
29 38 _skip_scs:
30 39 .endm
@@ -42,7 +51,7 @@ _skip_scs:
42 51 .endm
43 52 .macro scs_load_current
44 53 .endm
45 - .macro scs_load_current_if_task_changed prev
54 + .macro scs_load_current_if_from_user status, tmp
46 55 .endm
47 56 .macro scs_save_current
48 57 .endm
modified arch/riscv/include/asm/vector.h
@@ -137,8 +137,8 @@ static __always_inline void __vstate_csr_save(struct __riscv_v_ext_state *dest)
137 137 "csrr %0, " __stringify(CSR_VSTART) "\n\t"
138 138 "csrr %1, " __stringify(CSR_VTYPE) "\n\t"
139 139 "csrr %2, " __stringify(CSR_VL) "\n\t"
140 - : "=r" (dest->vstart), "=r" (dest->vtype), "=r" (dest->vl),
141 - "=r" (dest->vcsr) : :);
140 + : "=r" (dest->vstart), "=r" (dest->vtype), "=r" (dest->vl)
141 + : :);
142 142
143 143 if (has_xtheadvector()) {
144 144 unsigned long status;
@@ -230,7 +230,7 @@ static inline void __riscv_v_vstate_save(struct __riscv_v_ext_state *save_to,
230 230 "add %1, %1, %0\n\t"
231 231 "vse8.v v24, (%1)\n\t"
232 232 ".option pop\n\t"
233 - : "=&r" (vl) : "r" (datap) : "memory");
233 + : "=&r" (vl), "+r" (datap) : : "memory");
234 234 }
235 235 riscv_v_disable();
236 236 }
@@ -266,7 +266,7 @@ static inline void __riscv_v_vstate_restore(struct __riscv_v_ext_state *restore_
266 266 "add %1, %1, %0\n\t"
267 267 "vle8.v v24, (%1)\n\t"
268 268 ".option pop\n\t"
269 - : "=&r" (vl) : "r" (datap) : "memory");
269 + : "=&r" (vl), "+r" (datap) : : "memory");
270 270 }
271 271 __vstate_csr_restore(restore_from);
272 272 riscv_v_disable();
modified arch/riscv/include/uapi/asm/vendor/mips.h
@@ -1,3 +1,5 @@
1 1 /* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
2 2
3 - #define RISCV_HWPROBE_VENDOR_EXT_XMIPSEXECTL BIT(0)
3 + #include <linux/const.h>
4 +
5 + #define RISCV_HWPROBE_VENDOR_EXT_XMIPSEXECTL _BITULL(0)
modified arch/riscv/kernel/cpufeature.c
@@ -1233,6 +1233,18 @@ void __init riscv_user_isa_enable(void)
1233 1233 pr_warn("Zicbop disabled as it is unavailable on some harts\n");
1234 1234 }
1235 1235
1236 + void riscv_clear_hypervisor_csr(void)
1237 + {
1238 + if (!riscv_has_extension_unlikely(RISCV_ISA_EXT_H))
1239 + return;
1240 +
1241 + /*
1242 + * Clear HSTATUS.HU to restrict hypervisor instructions to HS-mode.
1243 + * This prevents user-mode from executing HLV/HSV instructions.
1244 + */
1245 + csr_clear(CSR_HSTATUS, HSTATUS_HU);
1246 + }
1247 +
1236 1248 #ifdef CONFIG_RISCV_ALTERNATIVE
1237 1249 /*
1238 1250 * Alternative patch sites consider 48 bits when determining when to patch
modified arch/riscv/kernel/entry.S
@@ -208,7 +208,7 @@ SYM_CODE_START(handle_exception)
208 208 load_global_pointer
209 209
210 210 /* Load the kernel shadow call stack pointer if coming from userspace */
211 - scs_load_current_if_task_changed s5
211 + scs_load_current_if_from_user s1, s5
212 212
213 213 #ifdef CONFIG_RISCV_ISA_V_PREEMPTIVE
214 214 move a0, sp
modified arch/riscv/kernel/patch.c
@@ -48,7 +48,7 @@ static __always_inline void *patch_map(void *addr, const unsigned int fixmap)
48 48 if (!IS_ENABLED(CONFIG_STRICT_KERNEL_RWX))
49 49 return addr;
50 50 phys = __pa_symbol(addr);
51 - } else if (IS_ENABLED(CONFIG_STRICT_MODULE_RWX)) {
51 + } else if (IS_ENABLED(CONFIG_EXECMEM)) {
52 52 struct page *page = vmalloc_to_page(addr);
53 53
54 54 BUG_ON(!page);
modified arch/riscv/kernel/ptrace.c
@@ -230,6 +230,7 @@ static int riscv_vr_set(struct task_struct *target,
230 230 return -ENODATA;
231 231
232 232 /* Copy rest of the vstate except datap */
233 + memset(&ptrace_vstate, 0, sizeof(ptrace_vstate));
233 234 ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &ptrace_vstate, 0,
234 235 sizeof(struct __riscv_v_regset_state));
235 236 if (unlikely(ret))
@@ -299,6 +300,9 @@ static int riscv_cfi_get(struct task_struct *target,
299 300 struct user_cfi_state user_cfi;
300 301 struct pt_regs *regs;
301 302
303 + if (!is_user_lpad_enabled() && !is_user_shstk_enabled())
304 + return -EINVAL;
305 +
302 306 memset(&user_cfi, 0, sizeof(user_cfi));
303 307 regs = task_pt_regs(target);
304 308
@@ -337,8 +341,12 @@ static int riscv_cfi_set(struct task_struct *target,
337 341 struct user_cfi_state user_cfi;
338 342 struct pt_regs *regs;
339 343
344 + if (!is_user_lpad_enabled() && !is_user_shstk_enabled())
345 + return -EINVAL;
346 +
340 347 regs = task_pt_regs(target);
341 348
349 + memset(&user_cfi, 0, sizeof(user_cfi));
342 350 ret = user_regset_copyin(&pos, &count, &kbuf, &ubuf, &user_cfi, 0, -1);
343 351 if (ret)
344 352 return ret;
modified arch/riscv/kernel/setup.c
@@ -366,6 +366,8 @@ void __init setup_arch(char **cmdline_p)
366 366
367 367 if (!IS_ENABLED(CONFIG_RISCV_ISA_ZBB) || !riscv_isa_extension_available(NULL, ZBB))
368 368 static_branch_disable(&efficient_ffs_key);
369 +
370 + riscv_clear_hypervisor_csr();
369 371 }
370 372
371 373 bool arch_cpu_is_hotpluggable(int cpu)
modified arch/riscv/kernel/smpboot.c
@@ -244,6 +244,8 @@ asmlinkage __visible void smp_callin(void)
244 244
245 245 numa_add_cpu(curr_cpuid);
246 246
247 + riscv_clear_hypervisor_csr();
248 +
247 249 pr_debug("CPU%u: Booted secondary hartid %lu\n", curr_cpuid,
248 250 cpuid_to_hartid_map(curr_cpuid));
249 251
modified arch/riscv/kernel/suspend.c
@@ -43,6 +43,8 @@ void suspend_save_csrs(struct suspend_context *context)
43 43
44 44 void suspend_restore_csrs(struct suspend_context *context)
45 45 {
46 + riscv_clear_hypervisor_csr();
47 +
46 48 csr_write(CSR_SCRATCH, 0);
47 49 if (riscv_has_extension_unlikely(RISCV_ISA_EXT_XLINUXENVCFG))
48 50 csr_write(CSR_ENVCFG, context->envcfg);
modified arch/riscv/lib/strnlen.S
@@ -87,9 +87,25 @@ strnlen_zbb:
87 87 * Aligned boundary. Use the address of the last valid byte
88 88 * (s + count - 1) to avoid loading a word past the count
89 89 * boundary in the loop below. count == 0 is handled above.
90 + *
91 + * Saturate the boundary when s + count would wrap around (very
92 + * large counts, e.g. SIZE_MAX passed by FORTIFY strcat/strlcat
93 + * with a destination whose size is unknown at compile time).
94 + * Without this, the wrapped boundary lands before s and the
95 + * pre-loop guard below always exits, returning a truncated
96 + * length.
97 + *
98 + * Clamping the increment to ~s (== SIZE_MAX - s) keeps the
99 + * computation branchless and wrap-free:
100 + *
101 + * s + min(count - 1, ~s) == saturating_add(s, count - 1)
102 + *
103 + * Saturating makes the scan equivalent to strlen().
90 104 */
91 - add t4, a0, a1
92 - addi t4, t4, -1
105 + addi t4, a1, -1 /* count - 1 */
106 + not t1, a0 /* SIZE_MAX - s */
107 + minu t4, t4, t1 /* clamp, so s + t4 can never wrap */
108 + add t4, a0, t4 /* saturated s + count - 1 */
93 109 andi t4, t4, -SZREG
94 110
95 111 /* Get the first word. */
modified arch/riscv/mm/extable.c
@@ -68,8 +68,8 @@ ex_handler_load_unaligned_zeropad(const struct exception_table_entry *ex,
68 68
69 69 addr = regs_get_gpr(regs, reg_addr * sizeof(unsigned long));
70 70
71 - offset = addr & 0x7UL;
72 - addr &= ~0x7UL;
71 + offset = addr & (sizeof(data) - 1);
72 + addr &= ~(sizeof(data) - 1);
73 73
74 74 data = *(unsigned long *)addr >> (offset * 8);
75 75
modified arch/um/drivers/vector_transports.c
@@ -209,6 +209,7 @@ static int raw_verify_header(
209 209 if ((vheader->flags & VIRTIO_NET_HDR_F_DATA_VALID) > 0)
210 210 return 1;
211 211
212 + skb_set_network_header(skb, ETH_HLEN);
212 213 virtio_net_hdr_to_skb(skb, vheader, virtio_legacy_is_little_endian());
213 214 return 0;
214 215 }
modified arch/x86/events/intel/uncore_snbep.c
@@ -474,6 +474,9 @@
474 474 /* DMR */
475 475 #define DMR_IMH1_HIOP_MMIO_BASE 0x1ffff6ae7000
476 476 #define DMR_HIOP_MMIO_SIZE 0x8000
477 + #define DMR_CXLCM_PMON_CTL_INVERT BIT(21)
478 + #define DMR_CXLCM_PMON_RAW_EVENT_MASK (GENERIC_PMON_RAW_EVENT_MASK | \
479 + DMR_CXLCM_PMON_CTL_INVERT)
477 480 #define DMR_CXLCM_EVENT_MASK_EXT 0xf
478 481 #define DMR_HAMVF_EVENT_MASK_EXT 0xffffffff
479 482 #define DMR_PCIE4_EVENT_MASK_EXT 0xffffff
@@ -6696,7 +6699,7 @@ static struct event_constraint dmr_uncore_cxlcm_constraints[] = {
6696 6699
6697 6700 static struct intel_uncore_type dmr_uncore_cxlcm = {
6698 6701 .name = "cxlcm",
6699 - .event_mask = GENERIC_PMON_RAW_EVENT_MASK,
6702 + .event_mask = DMR_CXLCM_PMON_RAW_EVENT_MASK,
6700 6703 .event_mask_ext = DMR_CXLCM_EVENT_MASK_EXT,
6701 6704 .constraints = dmr_uncore_cxlcm_constraints,
6702 6705 .format_group = &dmr_cxlcm_uncore_format_group,
modified arch/x86/hyperv/hv_init.c
@@ -426,7 +426,7 @@ static void __init hv_stimer_setup_percpu_clockev(void)
426 426 int ret;
427 427
428 428 /*
429 - * Continue afters errors in setting up stimer clockevents
429 + * Continue after errors in setting up stimer clockevents
430 430 * as we can run with the LAPIC timer as a fallback.
431 431 */
432 432 ret = hv_stimer_alloc(false);
@@ -434,7 +434,7 @@ static void __init hv_stimer_setup_percpu_clockev(void)
434 434 pr_warn("stimer setup failed with error %d\n", ret);
435 435
436 436 /*
437 - * Still register the LAPIC timer to allows users
437 + * Still register the LAPIC timer to allow users
438 438 * to switch to LAPIC timer via /sys, if they want to.
439 439 */
440 440 if (old_setup_percpu_clockev)
@@ -727,7 +727,8 @@ int hv_apicid_to_vp_index(u32 apic_id)
727 727 input->partition_id = HV_PARTITION_ID_SELF;
728 728 input->apic_ids[0] = apic_id;
729 729
730 - output = *this_cpu_ptr(hyperv_pcpu_output_arg);
730 + /* Treat input as having 2 APIC IDs so output is 64-bit aligned */
731 + output = (void *)input + struct_size(input, apic_ids, 2);
731 732
732 733 control = HV_HYPERCALL_REP_COMP_1 | HVCALL_GET_VP_INDEX_FROM_APIC_ID;
733 734 status = hv_do_hypercall(control, input, output);
modified arch/x86/include/asm/cpufeatures.h
@@ -477,6 +477,8 @@
477 477 #define X86_FEATURE_NO_NESTED_DATA_BP (20*32+ 0) /* No Nested Data Breakpoints */
478 478 #define X86_FEATURE_WRMSR_XX_BASE_NS (20*32+ 1) /* WRMSR to {FS,GS,KERNEL_GS}_BASE is non-serializing */
479 479 #define X86_FEATURE_LFENCE_RDTSC (20*32+ 2) /* LFENCE always serializing / synchronizes RDTSC */
480 +
481 + #define X86_FEATURE_TLBSYNC_SFW_NO (20*32+ 4) /* TLBI Erratum #1718 fixed in microcode */
480 482 #define X86_FEATURE_VERW_CLEAR (20*32+ 5) /* The memory form of VERW mitigates TSA */
481 483 #define X86_FEATURE_NULL_SEL_CLR_BASE (20*32+ 6) /* Null Selector Clears Base */
482 484
@@ -587,4 +589,5 @@
587 589 #define X86_BUG_TSA X86_BUG( 1*32+ 9) /* "tsa" CPU is affected by Transient Scheduler Attacks */
588 590 #define X86_BUG_VMSCAPE X86_BUG( 1*32+10) /* "vmscape" CPU is affected by VMSCAPE attacks from guests */
589 591 #define X86_BUG_SEAMRET_INVD_VMCS X86_BUG( 1*32+11) /* "seamret_invd_vmcs" SEAMRET from P-SEAMLDR clears the current VMCS */
592 + #define X86_BUG_TLBI X86_BUG( 1*32+12) /* "tlbi" AMD TLBI Erratum #1718 */
590 593 #endif /* _ASM_X86_CPUFEATURES_H */
modified arch/x86/include/asm/insn.h
@@ -321,7 +321,7 @@ static inline int insn_offset_immediate(struct insn *insn)
321 321 * are repeated, it cannot be used for looping over the prefixes.
322 322 */
323 323 #define for_each_insn_prefix(insn, prefix) \
324 - for (int idx = 0; idx < ARRAY_SIZE(insn->prefixes.bytes) && (prefix = insn->prefixes.bytes[idx]) != 0; idx++)
324 + for (int __i = 0; __i < ARRAY_SIZE(insn->prefixes.bytes) && (prefix = insn->prefixes.bytes[__i]) != 0; __i++)
325 325
326 326 #define POP_SS_OPCODE 0x1f
327 327 #define MOV_SREG_OPCODE 0x8e
modified arch/x86/include/asm/tlb.h
@@ -110,6 +110,12 @@ static inline void __tlbsync(void)
110 110
111 111 /* TLBSYNC: supported in binutils >= 0.36. */
112 112 asm volatile(".byte 0x0f, 0x01, 0xff" ::: "memory");
113 +
114 + if (!static_cpu_has_bug(X86_BUG_TLBI))
115 + return;
116 +
117 + /* TLBSYNC: supported in binutils >= 0.36. */
118 + asm volatile(".byte 0x0f, 0x01, 0xff" ::: "memory");
113 119 }
114 120 #else
115 121 /* Some compilers (I'm looking at you clang!) simply can't do DCE */
modified arch/x86/kernel/alternative.c
@@ -1455,7 +1455,8 @@ asm( ".pushsection .rodata \n"
1455 1455 "fineibt_paranoid_start: \n"
1456 1456 " mov $0x12345678, %eax \n"
1457 1457 " cmpl -11(%r11), %eax \n"
1458 - " cs lea -0x10(%r11), %r11 \n"
1458 + " .byte 0x2e \n"
1459 + " lea -0x10(%r11), %r11 \n"
1459 1460 "#fineibt_caller_size: \n"
1460 1461 " jne fineibt_paranoid_start+0xd \n"
1461 1462 "fineibt_paranoid_ind: \n"
modified arch/x86/kernel/cfi.c
@@ -10,11 +10,11 @@
10 10 #include <asm/insn-eval.h>
11 11
12 12 /*
13 - * Returns the target address and the expected type when regs->ip points
13 + * Returns the target address and the expected type when addr points
14 14 * to a compiler-generated CFI trap.
15 15 */
16 - static bool decode_cfi_insn(struct pt_regs *regs, unsigned long *target,
17 - u32 *type)
16 + static bool decode_cfi_insn(struct pt_regs *regs, unsigned long addr,
17 + unsigned long *target, u32 *type)
18 18 {
19 19 char buffer[MAX_INSN_SIZE];
20 20 struct insn insn;
@@ -29,13 +29,13 @@ static bool decode_cfi_insn(struct pt_regs *regs, unsigned long *target,
29 29 *   movl -<id>, %r10d ; 6 bytes
30 30 * addl -<pos>(%reg), %r10d; 4 bytes
31 31 * je .Ltmp1 ; 2 bytes
32 - * ud2 ; <- regs->ip
32 + * ud2 ; <- addr
33 33 * .Ltmp1:
34 34 *
35 35 * We can decode the expected type and the target address from the
36 36 * movl/addl instructions.
37 37 */
38 - if (copy_from_kernel_nofault(buffer, (void *)regs->ip - 12, MAX_INSN_SIZE))
38 + if (copy_from_kernel_nofault(buffer, (void *)addr - 12, MAX_INSN_SIZE))
39 39 return false;
40 40 if (insn_decode_kernel(&insn, &buffer[offset]))
41 41 return false;
@@ -44,7 +44,7 @@ static bool decode_cfi_insn(struct pt_regs *regs, unsigned long *target,
44 44
45 45 *type = -(u32)insn.immediate.value;
46 46
47 - if (copy_from_kernel_nofault(buffer, (void *)regs->ip - 6, MAX_INSN_SIZE))
47 + if (copy_from_kernel_nofault(buffer, (void *)addr - 6, MAX_INSN_SIZE))
48 48 return false;
49 49 if (insn_decode_kernel(&insn, &buffer[offset]))
50 50 return false;
@@ -82,7 +82,7 @@ enum bug_trap_type handle_cfi_failure(struct pt_regs *regs)
82 82 return BUG_TRAP_TYPE_NONE;
83 83 }
84 84
85 - if (!decode_cfi_insn(regs, &target, &type))
85 + if (!decode_cfi_insn(regs, addr, &target, &type))
86 86 return report_cfi_failure_noaddr(regs, addr);
87 87
88 88 break;
modified arch/x86/kernel/cpu/amd.c
@@ -1049,6 +1049,10 @@ static void init_amd_zen5(struct cpuinfo_x86 *c)
1049 1049 msr_clear_bit(MSR_AMD64_CPUID_FN_7, 18);
1050 1050 pr_emerg_once("RDSEED32 is broken. Disabling the corresponding CPUID bit.\n");
1051 1051 }
1052 +
1053 + if (cpu_has(c, X86_FEATURE_INVLPGB) &&
1054 + !cpu_has(c, X86_FEATURE_TLBSYNC_SFW_NO))
1055 + set_cpu_bug(c, X86_BUG_TLBI);
1052 1056 }
1053 1057
1054 1058 static void init_amd(struct cpuinfo_x86 *c)
modified arch/x86/kernel/kvm.c
@@ -265,11 +265,39 @@ noinstr u32 kvm_read_and_reset_apf_flags(void)
265 265 }
266 266 EXPORT_SYMBOL_FOR_KVM(kvm_read_and_reset_apf_flags);
267 267
268 + static __always_inline bool kvm_apf_reason_pending(void)
269 + {
270 + return __this_cpu_read(async_pf_enabled) &&
271 + __this_cpu_read(apf_reason.flags);
272 + }
273 +
268 274 noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token)
269 275 {
270 - u32 flags = kvm_read_and_reset_apf_flags();
271 276 irqentry_state_t state;
277 + u32 flags;
278 +
279 + if (!kvm_apf_reason_pending())
280 + return false;
281 +
282 + /*
283 + * The guest does not enable KVM_ASYNC_PF_SEND_ALWAYS, so the host
284 + * delivers async #PF only to user mode (or as a #PF VM-exit, which KVM
285 + * reads itself). A #PF from kernel mode can still arrive between that
286 + * delivery and the read of the reason flags, inside an NMI that
287 + * interrupted it, for instance perf reading user memory for a call
288 + * chain. Such a fault is not async, so leave the async PF flags
289 + * untouched for the outer handler. Outside NMI context, on the other
290 + * hand, async PF flags on a kernel-mode fault mean the host is broken.
291 + */
292 + if (!user_mode(regs)) {
293 + if (likely(in_nmi()))
294 + return false;
295 + state = irqentry_enter(regs);
296 + instrumentation_begin();
297 + panic("Host injected async #PF in kernel mode\n");
298 + }
272 299
300 + flags = kvm_read_and_reset_apf_flags();
273 301 if (!flags)
274 302 return false;
275 303
@@ -285,8 +313,6 @@ noinstr bool __kvm_handle_async_pf(struct pt_regs *regs, u32 token)
285 313 panic("Host injected async #PF in interrupt disabled region\n");
286 314
287 315 if (flags & KVM_PV_REASON_PAGE_NOT_PRESENT) {
288 - if (unlikely(!(user_mode(regs))))
289 - panic("Host injected async #PF in kernel mode\n");
290 316 /* Page is swapped out by the host. */
291 317 kvm_async_pf_task_wait_schedule(token);
292 318 } else {
modified arch/x86/kvm/mmu.h
@@ -275,8 +275,18 @@ static inline u8 permission_fault(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w,
275 275 unsigned pte_access, unsigned pte_pkey,
276 276 u64 access)
277 277 {
278 - /* strip nested paging fault error codes */
279 - unsigned int pfec = access;
278 + /*
279 + * Of the error codes that do not contribute to the index in
280 + * fmt->permissions, PK and SS are not supported by shadow paging
281 + * and also not provided to EPT violations, but SS *is* included
282 + * in the NPT exit code. RSVD faults are handled elsewhere.
283 + */
284 + unsigned int pfec = access & ~PFERR_SS_MASK;
285 + if (WARN_ON_ONCE(pfec & ~(PFERR_PRESENT_MASK | PFERR_WRITE_MASK |
286 + PFERR_USER_MASK | PFERR_FETCH_MASK)))
287 + pfec &= (PFERR_PRESENT_MASK | PFERR_WRITE_MASK |
288 + PFERR_USER_MASK | PFERR_FETCH_MASK);
289 +
280 290 unsigned long rflags = kvm_x86_call(get_rflags)(vcpu);
281 291
282 292 /*
@@ -301,8 +311,6 @@ static inline u8 permission_fault(struct kvm_vcpu *vcpu, struct kvm_pagewalk *w,
301 311 kvm_mmu_refresh_passthrough_bits(vcpu, w);
302 312
303 313 fault = (fmt->permissions[index] >> pte_access) & 1;
304 -
305 - WARN_ON_ONCE(pfec & (PFERR_PK_MASK | PFERR_SS_MASK | PFERR_RSVD_MASK));
306 314 if (unlikely(fmt->pkru_mask)) {
307 315 u32 pkru_bits, offset;
308 316
modified arch/x86/kvm/mmu/paging_tmpl.h
@@ -328,7 +328,6 @@ static int FNAME(walk_addr_generic)(struct guest_walker *walker,
328 328 int offset;
329 329 u64 walk_nx_mask = 0;
330 330 const int write_fault = access & PFERR_WRITE_MASK;
331 - const int user_fault = access & PFERR_USER_MASK;
332 331 const int fetch_fault = access & PFERR_FETCH_MASK;
333 332 /*
334 333 * Note! Track the error_code that's common to legacy shadow paging
@@ -486,7 +485,7 @@ retry_walk:
486 485 return 1;
487 486
488 487 error:
489 - errcode |= write_fault | user_fault;
488 + errcode |= access & (PFERR_WRITE_MASK | PFERR_USER_MASK | PFERR_SS_MASK);
490 489 if (fetch_fault && has_pferr_fetch(w))
491 490 errcode |= PFERR_FETCH_MASK;
492 491
modified arch/x86/kvm/svm/avic.c
@@ -395,6 +395,11 @@ static phys_addr_t avic_get_backing_page_address(struct vcpu_svm *svm)
395 395 return __sme_set(__pa(svm->vcpu.arch.apic->regs));
396 396 }
397 397
398 + static bool avic_is_addressable_vcpu(struct kvm_vcpu *vcpu)
399 + {
400 + return vcpu->vcpu_id <= __avic_get_max_physical_id(vcpu->kvm, NULL);
401 + }
402 +
398 403 void avic_init_vmcb(struct vcpu_svm *svm, struct vmcb *vmcb)
399 404 {
400 405 struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
@@ -412,7 +417,6 @@ void avic_init_vmcb(struct vcpu_svm *svm, struct vmcb *vmcb)
412 417
413 418 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
414 419 {
415 - u32 max_id = x2avic_enabled ? x2avic_max_physical_id : AVIC_MAX_PHYSICAL_ID;
416 420 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
417 421 struct vcpu_svm *svm = to_svm(vcpu);
418 422 u32 id = vcpu->vcpu_id;
@@ -425,7 +429,7 @@ static int avic_init_backing_page(struct kvm_vcpu *vcpu)
425 429 * avic_vcpu_load() expects to be called if and only if the vCPU has
426 430 * fully initialized AVIC.
427 431 */
428 - if (id > max_id) {
432 + if (!avic_is_addressable_vcpu(vcpu)) {
429 433 kvm_set_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_TOO_BIG);
430 434 vcpu->arch.apic->apicv_active = false;
431 435 return 0;
@@ -885,6 +889,14 @@ int avic_init_vcpu(struct vcpu_svm *svm)
885 889 return ret;
886 890 }
887 891
892 + void avic_vcpu_free(struct kvm_vcpu *vcpu)
893 + {
894 + struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
895 +
896 + if (kvm_svm->avic_physical_id_table && avic_is_addressable_vcpu(vcpu))
897 + WRITE_ONCE(kvm_svm->avic_physical_id_table[vcpu->vcpu_id], 0);
898 + }
899 +
888 900 void avic_apicv_post_state_restore(struct kvm_vcpu *vcpu)
889 901 {
890 902 avic_handle_dfr_update(vcpu);
@@ -1045,8 +1057,7 @@ static void __avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu,
1045 1057 if (WARN_ON(h_physical_id & ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
1046 1058 return;
1047 1059
1048 - if (WARN_ON_ONCE(vcpu->vcpu_id * sizeof(entry) >=
1049 - PAGE_SIZE << avic_get_physical_id_table_order(vcpu->kvm)))
1060 + if (WARN_ON_ONCE(!avic_is_addressable_vcpu(vcpu)))
1050 1061 return;
1051 1062
1052 1063 /*
@@ -1108,8 +1119,7 @@ static void __avic_vcpu_put(struct kvm_vcpu *vcpu, enum avic_vcpu_action action)
1108 1119
1109 1120 lockdep_assert_preemption_disabled();
1110 1121
1111 - if (WARN_ON_ONCE(vcpu->vcpu_id * sizeof(entry) >=
1112 - PAGE_SIZE << avic_get_physical_id_table_order(vcpu->kvm)))
1122 + if (WARN_ON_ONCE(!avic_is_addressable_vcpu(vcpu)))
1113 1123 return;
1114 1124
1115 1125 /*
modified arch/x86/kvm/svm/sev.c
@@ -2421,7 +2421,7 @@ static int sev_gmem_post_populate(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
2421 2421 void *dst_vaddr = kmap_local_pfn(pfn);
2422 2422
2423 2423 memcpy(src_vaddr, dst_vaddr, PAGE_SIZE);
2424 - set_page_dirty(src_page);
2424 + set_page_dirty_lock(src_page);
2425 2425
2426 2426 kunmap_local(dst_vaddr);
2427 2427 kunmap_local(src_vaddr);
modified arch/x86/kvm/svm/svm.c
@@ -1328,7 +1328,7 @@ static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1328 1328 svm->msrpm = svm_vcpu_alloc_msrpm();
1329 1329 if (!svm->msrpm) {
1330 1330 err = -ENOMEM;
1331 - goto error_free_sev;
1331 + goto error_free_avic;
1332 1332 }
1333 1333
1334 1334 svm->x2avic_msrs_intercepted = true;
@@ -1342,6 +1342,8 @@ static int svm_vcpu_create(struct kvm_vcpu *vcpu)
1342 1342
1343 1343 return 0;
1344 1344
1345 + error_free_avic:
1346 + avic_vcpu_free(vcpu);
1345 1347 error_free_sev:
1346 1348 sev_free_vcpu(vcpu);
1347 1349 error_free_vmcb_page:
@@ -1356,6 +1358,8 @@ static void svm_vcpu_free(struct kvm_vcpu *vcpu)
1356 1358
1357 1359 WARN_ON_ONCE(!list_empty(&svm->ir_list));
1358 1360
1361 + avic_vcpu_free(vcpu);
1362 +
1359 1363 svm_leave_nested(vcpu);
1360 1364 svm_free_nested(svm);
1361 1365
modified arch/x86/kvm/svm/svm.h
@@ -955,6 +955,7 @@ void avic_init_vmcb(struct vcpu_svm *svm, struct vmcb *vmcb);
955 955 int avic_incomplete_ipi_interception(struct kvm_vcpu *vcpu);
956 956 int avic_unaccelerated_access_interception(struct kvm_vcpu *vcpu);
957 957 int avic_init_vcpu(struct vcpu_svm *svm);
958 + void avic_vcpu_free(struct kvm_vcpu *vcpu);
958 959 void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu);
959 960 void avic_vcpu_put(struct kvm_vcpu *vcpu);
960 961 void avic_apicv_post_state_restore(struct kvm_vcpu *vcpu);
modified arch/x86/kvm/vmx/nested.c
@@ -3770,8 +3770,10 @@ vmentry_fail_vmexit_guest_mode:
3770 3770 vmentry_fail_vmexit:
3771 3771 vmx_switch_vmcs(vcpu, &vmx->vmcs01);
3772 3772
3773 - if (!from_vmentry)
3773 + if (!from_vmentry) {
3774 + nested_ept_uninit_mmu_context(vcpu);
3774 3775 return NVMX_VMENTRY_VMEXIT;
3776 + }
3775 3777
3776 3778 nested_put_vmcs12_pages(vcpu);
3777 3779
modified arch/x86/kvm/x86.h
@@ -250,7 +250,7 @@ static inline bool is_noncanonical_invlpg_address(u64 la, struct kvm_vcpu *vcpu)
250 250 static inline void vcpu_cache_mmio_info(struct kvm_vcpu *vcpu,
251 251 gva_t gva, gfn_t gfn, unsigned access)
252 252 {
253 - u64 gen = kvm_memslots(vcpu->kvm)->generation;
253 + u64 gen = kvm_vcpu_memslots(vcpu)->generation;
254 254
255 255 if (unlikely(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS))
256 256 return;
@@ -267,7 +267,7 @@ static inline void vcpu_cache_mmio_info(struct kvm_vcpu *vcpu,
267 267
268 268 static inline bool vcpu_match_mmio_gen(struct kvm_vcpu *vcpu)
269 269 {
270 - return vcpu->arch.mmio_gen == kvm_memslots(vcpu->kvm)->generation;
270 + return vcpu->arch.mmio_gen == kvm_vcpu_memslots(vcpu)->generation;
271 271 }
272 272
273 273 /*
modified drivers/accel/amdxdna/Kconfig
@@ -6,6 +6,7 @@ config DRM_ACCEL_AMDXDNA
6 6 depends on DRM_ACCEL
7 7 depends on PCI && HAS_IOMEM
8 8 depends on X86_64
9 + depends on AMD_PMF || !AMD_PMF
9 10 select DRM_SCHED
10 11 select DRM_GEM_SHMEM_HELPER
11 12 select FW_LOADER
modified drivers/accel/rocket/rocket_device.c
@@ -31,6 +31,8 @@ struct rocket_device *rocket_device_init(struct platform_device *pdev,
31 31 if (of_device_is_available(core_node))
32 32 num_cores++;
33 33
34 + rdev->max_cores = num_cores;
35 +
34 36 rdev->cores = devm_kcalloc(dev, num_cores, sizeof(*rdev->cores), GFP_KERNEL);
35 37 if (!rdev->cores)
36 38 return ERR_PTR(-ENOMEM);
modified drivers/accel/rocket/rocket_device.h
@@ -19,6 +19,7 @@ struct rocket_device {
19 19
20 20 struct rocket_core *cores;
21 21 unsigned int num_cores;
22 + unsigned int max_cores;
22 23 };
23 24
24 25 struct rocket_device *rocket_device_init(struct platform_device *pdev,
modified drivers/accel/rocket/rocket_drv.c
@@ -165,8 +165,11 @@ static int rocket_probe(struct platform_device *pdev)
165 165 /* First core probing, initialize DRM device. */
166 166 rdev = rocket_device_init(drm_dev, &rocket_drm_driver);
167 167 if (IS_ERR(rdev)) {
168 + int err = PTR_ERR(rdev);
169 +
168 170 dev_err(&pdev->dev, "failed to initialize rocket device\n");
169 - return PTR_ERR(rdev);
171 + rdev = NULL;
172 + return err;
170 173 }
171 174 }
172 175
@@ -223,7 +226,7 @@ static int find_core_for_dev(struct device *dev)
223 226 {
224 227 struct rocket_device *rdev = dev_get_drvdata(dev);
225 228
226 - for (unsigned int core = 0; core < rdev->num_cores; core++) {
229 + for (unsigned int core = 0; core < rdev->max_cores; core++) {
227 230 if (dev == rdev->cores[core].dev)
228 231 return core;
229 232 }
modified drivers/accel/rocket/rocket_job.c
@@ -283,7 +283,7 @@ static struct rocket_core *sched_to_core(struct rocket_device *rdev,
283 283 {
284 284 unsigned int core;
285 285
286 - for (core = 0; core < rdev->num_cores; core++) {
286 + for (core = 0; core < rdev->max_cores; core++) {
287 287 if (&rdev->cores[core].sched == sched)
288 288 return &rdev->cores[core];
289 289 }
modified drivers/accessibility/braille/braille_console.c
@@ -62,14 +62,50 @@ static void braille_write(u16 *buf)
62 62 {
63 63 static u16 lastwrite[WIDTH];
64 64 unsigned char data[1 + 1 + 2*WIDTH + 2 + 1], csum = 0, *c;
65 + struct nbcon_write_context wctxt = { };
66 + unsigned long flags;
65 67 u16 out;
66 68 int i;
67 69
68 70 if (!braille_co)
69 71 return;
70 72
73 + /*
74 + * Braille console is not registered in console_list. Instead, it
75 + * is integrated with VT and shows what appears on the graphical
76 + * console under console_lock(). From this POV it is a legacy
77 + * console. But it calls serial console driver which might be
78 + * converted to the NBCON API. It is similar to
79 + * nbcon_legacy_emit_next_record() except that we should try
80 + * harder to get the lock. Otherwise, the Braille device won't show
81 + * everything what is displayed on the terminal.
82 + *
83 + * In short, simulate the original locking using NBCON API.
84 + */
85 + if (braille_co->flags & CON_NBCON) {
86 + if (panic_on_this_cpu()) {
87 + /*
88 + * This should be good enough in practice. Most/all
89 + * serial console drivers have the atomic callback.
90 + */
91 + if (!braille_co->write_atomic)
92 + return;
93 +
94 + local_irq_save(flags);
95 + /* NBCON API strictly requires the ownership. */
96 + if (!nbcon_braille_try_acquire(braille_co, &wctxt)) {
97 + local_irq_restore(flags);
98 + return;
99 + }
100 + } else {
101 + braille_co->device_lock(braille_co, &flags);
102 + while (!nbcon_braille_try_acquire(braille_co, &wctxt))
103 + cpu_relax();
104 + }
105 + }
106 +
71 107 if (!memcmp(lastwrite, buf, WIDTH * sizeof(*buf)))
72 - return;
108 + goto unlock_nbcon;
73 109 memcpy(lastwrite, buf, WIDTH * sizeof(*buf));
74 110
75 111 #define SOH 1
@@ -102,7 +138,24 @@ static void braille_write(u16 *buf)
102 138 *c++ = csum;
103 139 *c++ = ETX;
104 140
105 - braille_co->write(braille_co, data, c - data);
141 + if (braille_co->flags & CON_NBCON) {
142 + nbcon_write_context_set_buf(&wctxt, (char *)data, c - data);
143 + if (panic_on_this_cpu())
144 + braille_co->write_atomic(braille_co, &wctxt);
145 + else
146 + braille_co->write_thread(braille_co, &wctxt);
147 + } else {
148 + braille_co->write(braille_co, data, c - data);
149 + }
150 +
151 + unlock_nbcon:
152 + if (braille_co->flags & CON_NBCON) {
153 + nbcon_braille_release(&wctxt);
154 + if (panic_on_this_cpu())
155 + local_irq_restore(flags);
156 + else
157 + braille_co->device_unlock(braille_co, flags);
158 + }
106 159 }
107 160
108 161 /* Follow the VC cursor*/
modified drivers/ata/libata-scsi.c
@@ -3059,10 +3059,15 @@ static void atapi_qc_complete(struct ata_queued_cmd *qc)
3059 3059 if (qc->cdb[0] == ALLOW_MEDIUM_REMOVAL && qc->dev->sdev)
3060 3060 qc->dev->sdev->locked = 0;
3061 3061
3062 - if (cmd->result)
3063 - ata_scsi_qc_done(qc, false, 0);
3064 - else
3065 - ata_scsi_qc_done(qc, true, SAM_STAT_CHECK_CONDITION);
3062 + /*
3063 + * Report CHECK CONDITION unless the command was terminated
3064 + * with a host byte set. Only set the status byte, so that the
3065 + * SCSI midlayer internal byte, which scsi_check_sense() may
3066 + * have set from the sense data, is preserved.
3067 + */
3068 + if (get_host_byte(cmd) == DID_OK)
3069 + set_status_byte(cmd, SAM_STAT_CHECK_CONDITION);
3070 + ata_scsi_qc_done(qc, false, 0);
3066 3071 goto schedule_deferred;
3067 3072 }
3068 3073
modified drivers/block/zloop.c
@@ -800,6 +800,27 @@ static void zloop_cmd_workfn(struct work_struct *work)
800 800 current->flags = orig_flags;
801 801 }
802 802
803 + static void zloop_fill_zero_rq(struct request *rq, unsigned int zero_from)
804 + {
805 + struct req_iterator iter;
806 + struct bio_vec bv;
807 + unsigned int pos = 0;
808 + unsigned int end, off;
809 +
810 + rq_for_each_segment(bv, rq, iter) {
811 + end = pos + bv.bv_len;
812 + if (end > zero_from) {
813 + if (pos < zero_from)
814 + off = zero_from - pos;
815 + else
816 + off = 0;
817 + memzero_page(bv.bv_page, bv.bv_offset + off,
818 + bv.bv_len - off);
819 + }
820 + pos = end;
821 + }
822 + }
823 +
803 824 static void zloop_complete_rq(struct request *rq)
804 825 {
805 826 struct zloop_cmd *cmd = blk_mq_rq_to_pdu(rq);
@@ -814,13 +835,9 @@ static void zloop_complete_rq(struct request *rq)
814 835 pr_err("Zone %u: failed read sector %llu, %llu sectors\n",
815 836 zone_no, cmd->sector, cmd->nr_sectors);
816 837
817 - if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq)) {
818 - /* short read */
819 - struct bio *bio;
820 -
821 - __rq_for_each_bio(bio, rq)
822 - zero_fill_bio(bio);
823 - }
838 + /* Short read. Zero out the unread tail beyond cmd->ret. */
839 + if (cmd->ret >= 0 && cmd->ret != blk_rq_bytes(rq))
840 + zloop_fill_zero_rq(rq, cmd->ret);
824 841 break;
825 842 case REQ_OP_WRITE:
826 843 case REQ_OP_ZONE_APPEND:
modified drivers/bluetooth/btintel_pcie.c
@@ -401,7 +401,7 @@ static int btintel_pcie_send_sync(struct btintel_pcie_data *data,
401 401
402 402 tfd_index = data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM];
403 403
404 - if (tfd_index > txq->count)
404 + if (tfd_index >= txq->count)
405 405 return -ERANGE;
406 406
407 407 if (skb->len > BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN) {
@@ -1777,7 +1777,7 @@ static irqreturn_t btintel_pcie_irq_msix_handler(int irq, void *dev_id)
1777 1777 static int btintel_pcie_setup_irq(struct btintel_pcie_data *data)
1778 1778 {
1779 1779 int err;
1780 - int num_irqs, i;
1780 + int num_irqs, i, j;
1781 1781
1782 1782 for (i = 0; i < BTINTEL_PCIE_MSIX_VEC_MAX; i++)
1783 1783 data->msix_entries[i].entry = i;
@@ -1806,6 +1806,10 @@ static int btintel_pcie_setup_irq(struct btintel_pcie_data *data)
1806 1806 KBUILD_MODNAME,
1807 1807 msix_entry);
1808 1808 if (err) {
1809 + for (j = 0; j < i; j++)
1810 + devm_free_irq(&data->pdev->dev,
1811 + data->msix_entries[j].vector,
1812 + &data->msix_entries[j]);
1809 1813 pci_free_irq_vectors(data->pdev);
1810 1814 data->alloc_vecs = 0;
1811 1815 return err;
@@ -1877,6 +1881,13 @@ static int btintel_pcie_config_pcie(struct pci_dev *pdev,
1877 1881 if (IS_ERR(data->base_addr))
1878 1882 return PTR_ERR(data->base_addr);
1879 1883
1884 + /* Do shared hardware reset to ensure a clean start before
1885 + * configuring interrupts.
1886 + */
1887 + err = btintel_pcie_reset_bt(data);
1888 + if (err)
1889 + return err;
1890 +
1880 1891 err = btintel_pcie_setup_irq(data);
1881 1892 if (err)
1882 1893 return err;
@@ -3138,7 +3149,7 @@ static void btintel_pcie_remove(struct pci_dev *pdev)
3138 3149 struct msix_entry *msix_entry;
3139 3150
3140 3151 msix_entry = &data->msix_entries[i];
3141 - free_irq(msix_entry->vector, msix_entry);
3152 + devm_free_irq(&pdev->dev, msix_entry->vector, msix_entry);
3142 3153 }
3143 3154
3144 3155 pci_free_irq_vectors(pdev);
modified drivers/char/mem.c
@@ -503,7 +503,7 @@ static int mmap_zero_prepare(struct vm_area_desc *desc)
503 503 #ifndef CONFIG_MMU
504 504 return -ENOSYS;
505 505 #endif
506 - if (vma_desc_test(desc, VMA_SHARED_BIT))
506 + if (vma_desc_test(desc, VMA_MAYSHARE_BIT))
507 507 return shmem_zero_setup_desc(desc);
508 508
509 509 /*
modified drivers/clk/qcom/gcc-eliza.c
@@ -3010,8 +3010,6 @@ static const u32 gcc_eliza_critical_cbcrs[] = {
3010 3010 0x26034, /* GCC_CAMERA_XO_CLK */
3011 3011 0x27004, /* GCC_DISP_AHB_CLK */
3012 3012 0x71004, /* GCC_GPU_CFG_AHB_CLK */
3013 - 0x52010, /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3014 - 0x52010, /* GCC_PCIE_RSCC_XO_CLK */
3015 3013 0x32004, /* GCC_VIDEO_AHB_CLK */
3016 3014 0x32038, /* GCC_VIDEO_XO_CLK */
3017 3015 };
@@ -3045,6 +3043,10 @@ static const struct regmap_config gcc_eliza_regmap_config = {
3045 3043
3046 3044 static void clk_eliza_regs_configure(struct device *dev, struct regmap *regmap)
3047 3045 {
3046 + /* Keep clocks always enabled */
3047 + regmap_update_bits(regmap, 0x52010, BIT(20), BIT(20)); /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3048 + regmap_update_bits(regmap, 0x52010, BIT(21), BIT(21)); /* GCC_PCIE_RSCC_XO_CLK */
3049 +
3048 3050 /* FORCE_MEM_CORE_ON for ufs phy ice core and gcc ufs phy axi clocks */
3049 3051 qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_ice_core_clk, true);
3050 3052 qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_axi_clk, true);
modified drivers/clk/qcom/gcc-hawi.c
@@ -3692,8 +3692,6 @@ static const u32 gcc_hawi_critical_cbcrs[] = {
3692 3692 0x67084, /* GCC_PCIE_1_RSC_CORE_CLK */
3693 3693 0x43014, /* GCC_PCIE_LINK_XO_CLK */
3694 3694 0x6b088, /* GCC_PCIE_RSC_CORE_CLK */
3695 - 0x52010, /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3696 - 0x52010, /* GCC_PCIE_RSCC_XO_CLK */
3697 3695 0x32004, /* GCC_VIDEO_AHB_CLK */
3698 3696 0x32028, /* GCC_VIDEO_XO_CLK */
3699 3697 };
@@ -3763,6 +3761,10 @@ static const struct regmap_config gcc_hawi_regmap_config = {
3763 3761
3764 3762 static void clk_hawi_regs_configure(struct device *dev, struct regmap *regmap)
3765 3763 {
3764 + /* Keep clocks always enabled */
3765 + regmap_update_bits(regmap, 0x52010, BIT(20), BIT(20)); /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3766 + regmap_update_bits(regmap, 0x52010, BIT(21), BIT(21)); /* GCC_PCIE_RSCC_XO_CLK */
3767 +
3766 3768 /* FORCE_MEM_CORE_ON for ufs phy ice core clocks */
3767 3769 qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_ice_core_clk, true);
3768 3770 }
modified drivers/clk/qcom/gcc-kaanapali.c
@@ -3464,8 +3464,6 @@ static const u32 gcc_kaanapali_critical_cbcrs[] = {
3464 3464 0x9f004, /* GCC_EVA_AHB_CLK */
3465 3465 0x9f024, /* GCC_EVA_XO_CLK */
3466 3466 0x71004, /* GCC_GPU_CFG_AHB_CLK */
3467 - 0x52010, /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3468 - 0x52010, /* GCC_PCIE_RSCC_XO_CLK */
3469 3467 0x32004, /* GCC_VIDEO_AHB_CLK */
3470 3468 0x32040, /* GCC_VIDEO_XO_CLK */
3471 3469 };
@@ -3480,6 +3478,10 @@ static const struct regmap_config gcc_kaanapali_regmap_config = {
3480 3478
3481 3479 static void clk_kaanapali_regs_configure(struct device *dev, struct regmap *regmap)
3482 3480 {
3481 + /* Keep clocks always enabled */
3482 + regmap_update_bits(regmap, 0x52010, BIT(20), BIT(20)); /* GCC_PCIE_RSCC_CFG_AHB_CLK */
3483 + regmap_update_bits(regmap, 0x52010, BIT(21), BIT(21)); /* GCC_PCIE_RSCC_XO_CLK */
3484 +
3483 3485 /* FORCE_MEM_CORE_ON for ufs phy ice core clocks */
3484 3486 qcom_branch_set_force_mem_core(regmap, gcc_ufs_phy_ice_core_clk, true);
3485 3487 }
modified drivers/clk/qcom/gpucc-glymur.c
@@ -510,7 +510,7 @@ static struct gdsc gpu_cc_cx_gdsc = {
510 510 .name = "gpu_cc_cx_gdsc",
511 511 },
512 512 .pwrsts = PWRSTS_OFF_ON,
513 - .flags = POLL_CFG_GDSCR | RETAIN_FF_ENABLE,
513 + .flags = RETAIN_FF_ENABLE | VOTABLE,
514 514 };
515 515
516 516 static struct clk_regmap *gpu_cc_glymur_clocks[] = {
modified drivers/clk/qcom/gpucc-kaanapali.c
@@ -380,7 +380,7 @@ static struct gdsc gpu_cc_cx_gdsc = {
380 380 .name = "gpu_cc_cx_gdsc",
381 381 },
382 382 .pwrsts = PWRSTS_OFF_ON,
383 - .flags = POLL_CFG_GDSCR | RETAIN_FF_ENABLE,
383 + .flags = RETAIN_FF_ENABLE | VOTABLE,
384 384 };
385 385
386 386 static struct clk_regmap *gpu_cc_kaanapali_clocks[] = {
modified drivers/dma-buf/Kconfig
@@ -43,7 +43,7 @@ config UDMABUF
43 43 config DMABUF_DEBUG
44 44 bool "DMA-BUF debug checks"
45 45 depends on DMA_SHARED_BUFFER
46 - default y if DEBUG_KERNEL
46 + default y if DEBUG
47 47 help
48 48 This option enables additional checks for DMA-BUF importers and
49 49 exporters. Specifically it validates that importers do not peek at the
modified drivers/edac/amd64_edac.c
@@ -2796,13 +2796,13 @@ static inline void decode_bus_error(int node_id, struct mce *m)
2796 2796 * the instance_id. For example, instance_id=0xYXXXXX where Y is the channel
2797 2797 * number.
2798 2798 *
2799 - * For DRAM ECC errors, the Chip Select number is given in bits [2:0] of
2799 + * For DRAM ECC errors, the Chip Select number is given in bits [1:0] of
2800 2800 * the MCA_SYND[ErrorInformation] field.
2801 2801 */
2802 2802 static void umc_get_err_info(struct mce *m, struct err_info *err)
2803 2803 {
2804 2804 err->channel = (m->ipid & GENMASK(31, 0)) >> 20;
2805 - err->csrow = m->synd & 0x7;
2805 + err->csrow = m->synd & 0x3;
2806 2806 }
2807 2807
2808 2808 static void decode_umc_error(int node_id, struct mce *m)
modified drivers/firewire/core-transaction.c
@@ -89,8 +89,12 @@ void fw_cancel_pending_transactions(struct fw_card *card)
89 89 break; \
90 90 } \
91 91 } \
92 - if (t && try_cancel_split_timeout(t)) \
93 - remove_transaction_entry(card, t); \
92 + if (t) { \
93 + if (try_cancel_split_timeout(t)) \
94 + remove_transaction_entry(card, t); \
95 + else \
96 + t = NULL; \
97 + } \
94 98 t; \
95 99 })
96 100
modified drivers/gpio/gpio-exar.c
@@ -199,6 +199,7 @@ static int gpio_exar_probe(struct platform_device *pdev)
199 199 index = ida_alloc(&ida_index, GFP_KERNEL);
200 200 if (index < 0)
201 201 return index;
202 + exar_gpio->index = index;
202 203
203 204 ret = devm_add_action_or_reset(dev, exar_devm_ida_free, exar_gpio);
204 205 if (ret)
@@ -214,7 +215,6 @@ static int gpio_exar_probe(struct platform_device *pdev)
214 215 exar_gpio->gpio_chip.set = exar_set_value;
215 216 exar_gpio->gpio_chip.base = -1;
216 217 exar_gpio->gpio_chip.ngpio = ngpios;
217 - exar_gpio->index = index;
218 218 exar_gpio->first_pin = first_pin;
219 219
220 220 ret = devm_gpiochip_add_data(dev, &exar_gpio->gpio_chip, exar_gpio);
modified drivers/gpio/gpio-mpsse.c
@@ -10,6 +10,7 @@
10 10 #include <linux/cleanup.h>
11 11 #include <linux/gpio/driver.h>
12 12 #include <linux/mutex.h>
13 + #include <linux/rcupdate.h>
13 14 #include <linux/spinlock.h>
14 15 #include <linux/usb.h>
15 16
@@ -24,6 +25,7 @@ struct mpsse_priv {
24 25 raw_spinlock_t irq_spin; /* protects worker list */
25 26 atomic_t irq_type[16]; /* pin -> edge detection type */
26 27 atomic_t irq_enabled;
28 + atomic_t dying; /* no new workers after disconnect */
27 29 int id;
28 30
29 31 u8 gpio_outputs[2]; /* Output states for GPIOs [L, H] */
@@ -46,6 +48,7 @@ struct mpsse_worker {
46 48 atomic_t cancelled;
47 49 struct list_head list; /* linked list */
48 50 struct list_head destroy; /* teardown linked list */
51 + struct rcu_head rcu; /* deferred free for dying path */
49 52 };
50 53
51 54 struct bulk_desc {
@@ -525,10 +528,24 @@ static void gpio_mpsse_irq_enable(struct irq_data *irqd)
525 528 worker->priv = priv;
526 529 INIT_LIST_HEAD(&worker->list);
527 530 INIT_WORK(&worker->work, gpio_mpsse_poll);
528 - schedule_work(&worker->work);
529 531
530 - scoped_guard(raw_spinlock_irqsave, &priv->irq_spin)
532 + scoped_guard(raw_spinlock_irqsave, &priv->irq_spin) {
533 + if (atomic_read(&priv->dying)) {
534 + /*
535 + * Cannot kfree() here: this callback
536 + * runs with the IRQ descriptor's raw
537 + * spinlock held and kfree() may sleep
538 + * on PREEMPT_RT. The worker is not
539 + * yet published, so the deferred free
540 + * is unobservable.
541 + */
542 + kfree_rcu(worker, rcu);
543 + return;
544 + }
545 +
531 546 list_add(&worker->list, &priv->workers);
547 + schedule_work(&worker->work);
548 + }
532 549 }
533 550 }
534 551
@@ -704,6 +721,9 @@ static void gpio_mpsse_disconnect(struct usb_interface *intf)
704 721 {
705 722 struct mpsse_priv *priv = usb_get_intfdata(intf);
706 723
724 + scoped_guard(raw_spinlock_irqsave, &priv->irq_spin)
725 + atomic_set(&priv->dying, 1);
726 +
707 727 /*
708 728 * Lock prevents double-free of worker from here and the teardown
709 729 * step at the beginning of gpio_mpsse_poll
modified drivers/gpio/gpio-mxc.c
@@ -7,6 +7,7 @@
7 7 // Authors: Daniel Mack, Juergen Beisert.
8 8 // Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved.
9 9
10 + #include <linux/bitops.h>
10 11 #include <linux/cleanup.h>
11 12 #include <linux/clk.h>
12 13 #include <linux/err.h>
@@ -68,11 +69,11 @@ struct mxc_gpio_port {
68 69 struct irq_domain *domain;
69 70 struct gpio_generic_chip gen_gc;
70 71 struct device *dev;
71 - u32 both_edges;
72 + unsigned long both_edges;
72 73 struct mxc_gpio_reg_saved gpio_saved_reg;
73 74 bool power_off;
74 - u32 wakeup_pads;
75 75 bool is_pad_wakeup;
76 + unsigned long wakeup_pads;
76 77 u32 pad_type[32];
77 78 const struct mxc_gpio_hwdata *hwdata;
78 79 };
@@ -168,7 +169,7 @@ static int gpio_set_irq_type(struct irq_data *d, u32 type)
168 169 int edge;
169 170 void __iomem *reg = port->base;
170 171
171 - port->both_edges &= ~(1 << gpio_idx);
172 + clear_bit(gpio_idx, &port->both_edges);
172 173 switch (type) {
173 174 case IRQ_TYPE_EDGE_RISING:
174 175 edge = GPIO_INT_RISE_EDGE;
@@ -188,7 +189,7 @@ static int gpio_set_irq_type(struct irq_data *d, u32 type)
188 189 edge = GPIO_INT_HIGH_LEV;
189 190 pr_debug("mxc: set GPIO %d to high trigger\n", gpio_idx);
190 191 }
191 - port->both_edges |= 1 << gpio_idx;
192 + set_bit(gpio_idx, &port->both_edges);
192 193 }
193 194 break;
194 195 case IRQ_TYPE_LEVEL_LOW:
@@ -259,7 +260,7 @@ static void mxc_gpio_irq_handler(struct mxc_gpio_port *port, u32 irq_stat)
259 260 while (irq_stat != 0) {
260 261 int irqoffset = fls(irq_stat) - 1;
261 262
262 - if (port->both_edges & (1 << irqoffset))
263 + if (test_bit(irqoffset, &port->both_edges))
263 264 mxc_flip_edge(port, irqoffset);
264 265
265 266 generic_handle_domain_irq(port->domain, irqoffset);
@@ -330,16 +331,18 @@ static int gpio_set_wake_irq(struct irq_data *d, u32 enable)
330 331 ret = enable_irq_wake(port->irq_high);
331 332 else
332 333 ret = enable_irq_wake(port->irq);
333 - port->wakeup_pads |= BIT(gpio_idx);
334 334 } else {
335 335 if (port->irq_high && (gpio_idx >= 16))
336 336 ret = disable_irq_wake(port->irq_high);
337 337 else
338 338 ret = disable_irq_wake(port->irq);
339 - port->wakeup_pads &= ~BIT(gpio_idx);
340 339 }
340 + if (ret)
341 + return ret;
341 342
342 - return ret;
343 + assign_bit(gpio_idx, &port->wakeup_pads, enable);
344 +
345 + return 0;
343 346 }
344 347
345 348 static int mxc_gpio_init_gc(struct mxc_gpio_port *port, int irq_base)
@@ -474,8 +477,6 @@ static int mxc_gpio_probe(struct platform_device *pdev)
474 477 } else
475 478 port->mx_irq_handler = mx3_gpio_irq_handler;
476 479
477 - mxc_update_irq_chained_handler(port, true);
478 -
479 480 config.dev = &pdev->dev;
480 481 config.sz = 4;
481 482 config.dat = port->base + GPIO_PSR;
@@ -499,10 +500,6 @@ static int mxc_gpio_probe(struct platform_device *pdev)
499 500 else /* silence boot time warning */
500 501 port->gen_gc.gc.base = -1;
501 502
502 - err = devm_gpiochip_add_data(&pdev->dev, &port->gen_gc.gc, port);
503 - if (err)
504 - goto out_bgio;
505 -
506 503 irq_base = devm_irq_alloc_descs(&pdev->dev, -1, 0, 32, numa_node_id());
507 504 if (irq_base < 0) {
508 505 err = irq_base;
@@ -523,8 +520,19 @@ static int mxc_gpio_probe(struct platform_device *pdev)
523 520 if (err < 0)
524 521 goto out_irqdomain_remove;
525 522
523 + /*
524 + * Register the GPIO chip last: devm_gpiochip_add_data() makes the
525 + * chip visible to consumers immediately, so the IRQ domain and
526 + * generic irq chip must be ready before any to_irq() call.
527 + */
528 + err = devm_gpiochip_add_data(&pdev->dev, &port->gen_gc.gc, port);
529 + if (err)
530 + goto out_irqdomain_remove;
531 +
526 532 list_add_tail(&port->node, &mxc_gpio_ports);
527 533
534 + mxc_update_irq_chained_handler(port, true);
535 +
528 536 platform_set_drvdata(pdev, port);
529 537 pm_runtime_put_autosuspend(&pdev->dev);
530 538
modified drivers/gpio/gpio-nct6694.c
@@ -444,7 +444,7 @@ static int nct6694_gpio_probe(struct platform_device *pdev)
444 444 data->gpio.set_config = nct6694_set_config;
445 445 data->gpio.init_valid_mask = nct6694_init_valid_mask;
446 446 data->gpio.base = -1;
447 - data->gpio.can_sleep = false;
447 + data->gpio.can_sleep = true;
448 448 data->gpio.owner = THIS_MODULE;
449 449 data->gpio.ngpio = NCT6694_NR_GPIO;
450 450
modified drivers/gpio/gpio-xilinx.c
@@ -271,14 +271,7 @@ static void xgpio_save_regs(struct xgpio_instance *chip)
271 271
272 272 static int xgpio_request(struct gpio_chip *chip, unsigned int offset)
273 273 {
274 - int ret;
275 -
276 - ret = pm_runtime_get_sync(chip->parent);
277 - /*
278 - * If the device is already active pm_runtime_get() will return 1 on
279 - * success, but gpio_request still needs to return 0.
280 - */
281 - return ret < 0 ? ret : 0;
274 + return pm_runtime_resume_and_get(chip->parent);
282 275 }
283 276
284 277 static void xgpio_free(struct gpio_chip *chip, unsigned int offset)
modified drivers/gpio/gpiolib-kunit.c
@@ -28,6 +28,8 @@
28 28
29 29 #define GPIO_TEST_PROVIDER_NGPIO 4
30 30
31 + KUNIT_DEFINE_ACTION_WRAPPER(gpio_device_put_wrapper, gpio_device_put, struct gpio_device *);
32 +
31 33 /*
32 34 * The test provider tracks per-line direction and value so that lines can be
33 35 * driven as both inputs and outputs - this is needed to exercise input as well
@@ -770,6 +772,7 @@ static void gpio_hog_assert(struct kunit *test, unsigned int offset,
770 772 struct property_entry properties[2];
771 773 struct platform_device *pdev;
772 774 struct fwnode_handle *fwnode;
775 + struct gpio_device *gdev;
773 776 struct gpio_desc *desc;
774 777 bool bound = true;
775 778 int ret;
@@ -789,10 +792,12 @@ static void gpio_hog_assert(struct kunit *test, unsigned int offset,
789 792 wait_for_device_probe();
790 793
791 794 /* The hog must have configured the line with the expected direction. */
792 - struct gpio_device *gdev __free(gpio_device_put) =
793 - gpio_device_find_by_label(GPIO_CONSUMER_NAME);
795 + gdev = gpio_device_find_by_label(GPIO_CONSUMER_NAME);
794 796 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, gdev);
795 797
798 + ret = kunit_add_action_or_reset(test, gpio_device_put_wrapper, gdev);
799 + KUNIT_ASSERT_EQ(test, ret, 0);
800 +
796 801 desc = gpio_device_get_desc(gdev, offset);
797 802 KUNIT_ASSERT_NOT_ERR_OR_NULL(test, desc);
798 803
modified drivers/gpio/gpiolib-shared.c
@@ -449,10 +449,14 @@ static bool gpio_shared_dev_is_reset_gpio(struct device *consumer,
449 449 int gpio_shared_add_proxy_lookup(struct device *consumer, struct fwnode_handle *fwnode,
450 450 const char *con_id, unsigned long lflags)
451 451 {
452 - const char *dev_id = dev_name(consumer);
453 - struct gpiod_lookup_table *lookup;
454 452 struct gpio_shared_entry *entry;
455 453 struct gpio_shared_ref *ref;
454 + const char *dev_id;
455 +
456 + if (!consumer)
457 + return -EOPNOTSUPP;
458 +
459 + dev_id = dev_name(consumer);
456 460
457 461 list_for_each_entry(entry, &gpio_shared_list, list) {
458 462 list_for_each_entry(ref, &entry->refs, list) {
@@ -480,18 +484,22 @@ int gpio_shared_add_proxy_lookup(struct device *consumer, struct fwnode_handle *
480 484 if (!key)
481 485 return -ENOMEM;
482 486
483 - lookup = kzalloc_flex(*lookup, table, 2);
487 + struct gpiod_lookup_table *lookup __free(kfree) =
488 + kzalloc_flex(*lookup, table, 2);
484 489 if (!lookup)
485 490 return -ENOMEM;
486 491
487 492 pr_debug("Adding machine lookup entry for a shared GPIO for consumer %s, with key '%s' and con_id '%s'\n",
488 493 dev_id, key, ref->con_id ?: "none");
489 494
490 - lookup->dev_id = dev_id;
495 + lookup->dev_id = kstrdup(dev_id, GFP_KERNEL);
496 + if (!lookup->dev_id)
497 + return -ENOMEM;
498 +
491 499 lookup->table[0] = GPIO_LOOKUP(no_free_ptr(key), 0,
492 500 ref->con_id, lflags);
493 501
494 - ref->lookup = lookup;
502 + ref->lookup = no_free_ptr(lookup);
495 503 gpiod_add_lookup_table(ref->lookup);
496 504
497 505 return 0;
@@ -611,6 +619,7 @@ void gpio_device_teardown_shared(struct gpio_device *gdev)
611 619 if (ref->lookup) {
612 620 gpiod_remove_lookup_table(ref->lookup);
613 621 kfree(ref->lookup->table[0].key);
622 + kfree(ref->lookup->dev_id);
614 623 kfree(ref->lookup);
615 624 ref->lookup = NULL;
616 625 }
modified drivers/gpio/gpiolib.c
@@ -3954,16 +3954,17 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep,
3954 3954 } while ((i < array_size) &&
3955 3955 gpio_device_chip_cmp(desc_array[i]->gdev, guard.gc));
3956 3956 /* push collected bits to outputs */
3957 - if (count != 0) {
3957 + ret = 0;
3958 + if (count != 0)
3958 3959 ret = gpiochip_set_multiple(guard.gc, mask, bits);
3959 - if (ret)
3960 - return ret;
3961 - }
3962 3960
3963 3961 if (mask != fastpath_mask)
3964 3962 bitmap_free(mask);
3965 3963 if (bits != fastpath_bits)
3966 3964 bitmap_free(bits);
3965 +
3966 + if (ret)
3967 + return ret;
3967 3968 }
3968 3969 return 0;
3969 3970 }
modified drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c
@@ -598,14 +598,18 @@ int amdgpu_amdkfd_get_dmabuf_info(struct amdgpu_device *adev, int dma_buf_fd,
598 598 /* first get metadata_size by buffer = NULL */
599 599 r = amdgpu_bo_get_metadata(bo, NULL, 0,
600 600 metadata_size, NULL);
601 + if (r)
602 + goto out_put;
601 603
602 604 /* user buf_size is bigger than bo metadata_size
603 605 * allocate a buf at kernel space and copy */
604 606 if (*metadata_size <= buffer_size) {
605 607 *metadata_buffer = kzalloc(*metadata_size, GFP_KERNEL);
606 608
607 - if (!*metadata_buffer)
608 - return -ENOMEM;
609 + if (!*metadata_buffer) {
610 + r = -ENOMEM;
611 + goto out_put;
612 + }
609 613
610 614 r = amdgpu_bo_get_metadata(bo, *metadata_buffer, *metadata_size,
611 615 NULL, &metadata_flags);
modified drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c
@@ -1431,6 +1431,7 @@ static void amdgpu_cs_parser_fini(struct amdgpu_cs_parser *parser)
1431 1431 int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
1432 1432 {
1433 1433 struct amdgpu_device *adev = drm_to_adev(dev);
1434 + struct amdgpu_bo_list_entry *e;
1434 1435 struct amdgpu_cs_parser parser;
1435 1436 int r;
1436 1437
@@ -1465,25 +1466,31 @@ int amdgpu_cs_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
1465 1466
1466 1467 r = amdgpu_cs_patch_jobs(&parser);
1467 1468 if (r)
1468 - goto error_fini;
1469 + goto error_free_user_pages;
1469 1470
1470 1471 r = amdgpu_cs_vm_handling(&parser);
1471 1472 if (r)
1472 - goto error_fini;
1473 + goto error_free_user_pages;
1473 1474
1474 1475 r = amdgpu_cs_sync_rings(&parser);
1475 1476 if (r)
1476 - goto error_fini;
1477 + goto error_free_user_pages;
1477 1478
1478 1479 trace_amdgpu_cs_ibs(&parser);
1479 1480
1480 1481 r = amdgpu_cs_submit(&parser, data);
1481 1482 if (r)
1482 - goto error_fini;
1483 + goto error_free_user_pages;
1483 1484
1484 1485 amdgpu_cs_parser_fini(&parser);
1485 1486 return 0;
1486 1487
1488 + error_free_user_pages:
1489 + /* amdgpu_cs_submit() only drops the ranges once it got that far. */
1490 + amdgpu_bo_list_for_each_userptr_entry(e, parser.bo_list) {
1491 + amdgpu_hmm_range_free(e->range);
1492 + e->range = NULL;
1493 + }
1487 1494 error_fini:
1488 1495 amdgpu_cs_parser_fini(&parser);
1489 1496 return r;
modified drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c
@@ -121,6 +121,20 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f,
121 121
122 122 *pos &= (1UL << 22) - 1;
123 123
124 + if (size > PAGE_SIZE)
125 + return -EINVAL;
126 +
127 + /*
128 + * Access the user buffer only while none of the locks below are held:
129 + * a fault takes mmap_lock, and grbm_idx_mutex and srbm_mutex nest
130 + * inside it.
131 + */
132 + u32 *data __free(kfree) = kmalloc(size, GFP_KERNEL);
133 + if (!data)
134 + return -ENOMEM;
135 + if (!read && copy_from_user(data, buf, size))
136 + return -EFAULT;
137 +
124 138 r = pm_runtime_get_sync(adev_to_drm(adev)->dev);
125 139 if (r < 0) {
126 140 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
@@ -152,28 +166,16 @@ static int amdgpu_debugfs_process_reg_op(bool read, struct file *f,
152 166 mutex_lock(&adev->pm.mutex);
153 167
154 168 while (size) {
155 - uint32_t value;
156 -
157 - if (read) {
158 - value = RREG32(*pos >> 2);
159 - r = put_user(value, (uint32_t *)buf);
160 - } else {
161 - r = get_user(value, (uint32_t *)buf);
162 - if (!r)
163 - amdgpu_mm_wreg_mmio_rlc(adev, *pos >> 2, value, 0);
164 - }
165 - if (r) {
166 - result = r;
167 - goto end;
168 - }
169 + if (read)
170 + data[result >> 2] = RREG32(*pos >> 2);
171 + else
172 + amdgpu_mm_wreg_mmio_rlc(adev, *pos >> 2, data[result >> 2], 0);
169 173
170 174 result += 4;
171 - buf += 4;
172 175 *pos += 4;
173 176 size -= 4;
174 177 }
175 178
176 - end:
177 179 if (use_bank) {
178 180 amdgpu_gfx_select_se_sh(adev, 0xffffffff, 0xffffffff, 0xffffffff, 0);
179 181 mutex_unlock(&adev->grbm_idx_mutex);
@@ -188,6 +190,10 @@ end:
188 190 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
189 191
190 192 amdgpu_virt_disable_access_debugfs(adev);
193 +
194 + if (read && copy_to_user(buf, data, result))
195 + return -EFAULT;
196 +
191 197 return result;
192 198 }
193 199
@@ -238,11 +244,24 @@ static ssize_t amdgpu_debugfs_regs2_op(struct file *f, char __user *buf, u32 off
238 244 struct amdgpu_device *adev = rd->adev;
239 245 ssize_t result = 0;
240 246 int r;
241 - uint32_t value;
242 247
243 248 if (size & 0x3 || offset & 0x3)
244 249 return -EINVAL;
245 250
251 + if (size > PAGE_SIZE)
252 + return -EINVAL;
253 +
254 + /*
255 + * Access the user buffer only while none of the locks below are held:
256 + * a fault takes mmap_lock, and grbm_idx_mutex and srbm_mutex nest
257 + * inside it.
258 + */
259 + u32 *data __free(kfree) = kmalloc(size, GFP_KERNEL);
260 + if (!data)
261 + return -ENOMEM;
262 + if (write_en && copy_from_user(data, buf, size))
263 + return -EFAULT;
264 +
246 265 r = pm_runtime_get_sync(adev_to_drm(adev)->dev);
247 266 if (r < 0) {
248 267 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
@@ -281,24 +300,16 @@ static ssize_t amdgpu_debugfs_regs2_op(struct file *f, char __user *buf, u32 off
281 300 mutex_lock(&adev->pm.mutex);
282 301
283 302 while (size) {
284 - if (!write_en) {
285 - value = RREG32(offset >> 2);
286 - r = put_user(value, (uint32_t *)buf);
287 - } else {
288 - r = get_user(value, (uint32_t *)buf);
289 - if (!r)
290 - amdgpu_mm_wreg_mmio_rlc(adev, offset >> 2, value, rd->id.xcc_id);
291 - }
292 - if (r) {
293 - result = r;
294 - goto end;
295 - }
303 + if (!write_en)
304 + data[result >> 2] = RREG32(offset >> 2);
305 + else
306 + amdgpu_mm_wreg_mmio_rlc(adev, offset >> 2, data[result >> 2],
307 + rd->id.xcc_id);
296 308 offset += 4;
297 309 size -= 4;
298 310 result += 4;
299 - buf += 4;
300 311 }
301 - end:
312 +
302 313 if (rd->id.use_grbm) {
303 314 amdgpu_gfx_select_se_sh(adev, 0xffffffff, 0xffffffff, 0xffffffff, rd->id.xcc_id);
304 315 mutex_unlock(&adev->grbm_idx_mutex);
@@ -317,6 +328,10 @@ end:
317 328 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
318 329
319 330 amdgpu_virt_disable_access_debugfs(adev);
331 +
332 + if (!write_en && copy_to_user(buf, data, result))
333 + return -EFAULT;
334 +
320 335 return result;
321 336 }
322 337
@@ -1251,7 +1266,6 @@ static ssize_t amdgpu_debugfs_gpr_read(struct file *f, char __user *buf,
1251 1266 {
1252 1267 struct amdgpu_device *adev = f->f_inode->i_private;
1253 1268 int r;
1254 - ssize_t result = 0;
1255 1269 uint32_t offset, se, sh, cu, wave, simd, thread, bank, *data;
1256 1270
1257 1271 if (size > 4096 || size & 3 || *pos & 3)
@@ -1295,25 +1309,11 @@ static ssize_t amdgpu_debugfs_gpr_read(struct file *f, char __user *buf,
1295 1309 mutex_unlock(&adev->grbm_idx_mutex);
1296 1310
1297 1311 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
1312 + amdgpu_virt_disable_access_debugfs(adev);
1298 1313
1299 - while (size) {
1300 - uint32_t value;
1301 -
1302 - value = data[result >> 2];
1303 - r = put_user(value, (uint32_t *)buf);
1304 - if (r) {
1305 - amdgpu_virt_disable_access_debugfs(adev);
1306 - goto err;
1307 - }
1308 -
1309 - result += 4;
1310 - buf += 4;
1311 - size -= 4;
1312 - }
1313 -
1314 + r = copy_to_user(buf, data, size) ? -EFAULT : size;
1314 1315 kfree(data);
1315 - amdgpu_virt_disable_access_debugfs(adev);
1316 - return result;
1316 + return r;
1317 1317
1318 1318 err:
1319 1319 pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
modified drivers/gpu/drm/amd/amdgpu/amdgpu_gem.c
@@ -337,11 +337,14 @@ static void amdgpu_gem_object_close(struct drm_gem_object *obj,
337 337 goto out_unlock;
338 338 }
339 339
340 + bo_va = amdgpu_vm_bo_find(vm, bo);
341 + /* the fence is attached once per bo_va, so keep it for other handles */
342 + if (bo_va && --bo_va->ref_count)
343 + goto out_unlock;
344 +
340 345 if (!amdgpu_vm_is_bo_always_valid(vm, bo))
341 346 amdgpu_evf_mgr_detach_fence(&fpriv->evf_mgr, bo);
342 -
343 - bo_va = amdgpu_vm_bo_find(vm, bo);
344 - if (!bo_va || --bo_va->ref_count)
347 + if (!bo_va)
345 348 goto out_unlock;
346 349
347 350 amdgpu_vm_bo_del(adev, bo_va);
@@ -567,8 +570,10 @@ int amdgpu_gem_userptr_ioctl(struct drm_device *dev, void *data,
567 570
568 571 if (args->flags & AMDGPU_GEM_USERPTR_VALIDATE) {
569 572 range = amdgpu_hmm_range_alloc(NULL);
570 - if (unlikely(!range))
571 - return -ENOMEM;
573 + if (unlikely(!range)) {
574 + r = -ENOMEM;
575 + goto release_object;
576 + }
572 577 r = amdgpu_ttm_tt_get_user_pages(bo, range);
573 578 if (r) {
574 579 amdgpu_hmm_range_free(range);
@@ -1236,7 +1241,7 @@ int amdgpu_gem_list_handles_ioctl(struct drm_device *dev, void *data,
1236 1241 bo_entry->alloc_flags = bo->flags & AMDGPU_GEM_CREATE_SETTABLE_MASK;
1237 1242 bo_entry->preferred_domains = bo->preferred_domains;
1238 1243 bo_entry->gem_handle = id;
1239 - bo_entry->alignment = bo->tbo.page_alignment;
1244 + bo_entry->alignment = (u64)bo->tbo.page_alignment << PAGE_SHIFT;
1240 1245
1241 1246 if (bo->tbo.base.import_attach)
1242 1247 bo_entry->flags |= AMDGPU_GEM_LIST_HANDLES_FLAG_IS_IMPORT;
modified drivers/gpu/drm/amd/amdgpu/amdgpu_gmc.c
@@ -1080,20 +1080,17 @@ void amdgpu_gmc_init_vga_resv_regions(struct amdgpu_device *adev)
1080 1080 case CHIP_RENOIR:
1081 1081 adev->mman.keep_stolen_vga_memory = true;
1082 1082 break;
1083 - case CHIP_POLARIS10:
1084 - case CHIP_POLARIS11:
1085 - case CHIP_POLARIS12:
1086 - /* MacBookPros with switchable graphics put VRAM at 0 when
1087 - * the iGPU is enabled which results in cursor issues if
1088 - * the cursor ends up at 0. Reserve vram at 0 in that case.
1089 - */
1090 - if (adev->gmc.vram_start == 0)
1091 - adev->mman.keep_stolen_vga_memory = true;
1092 - break;
1093 1083 default:
1094 1084 adev->mman.keep_stolen_vga_memory = false;
1095 1085 break;
1096 1086 }
1087 + /* MacBookPros with switchable graphics put VRAM at 0 when
1088 + * the iGPU is enabled which results in cursor issues if
1089 + * the cursor ends up at 0. Reserve vram at 0 in that case.
1090 + */
1091 + if ((adev->pdev->subsystem_vendor == PCI_VENDOR_ID_APPLE) &&
1092 + (adev->gmc.vram_start == 0))
1093 + adev->mman.keep_stolen_vga_memory = true;
1097 1094
1098 1095 if (amdgpu_sriov_vf(adev) ||
1099 1096 !amdgpu_device_has_display_hardware(adev)) {
modified drivers/gpu/drm/amd/amdgpu/amdgpu_kms.c
@@ -30,6 +30,7 @@
30 30 #include <drm/amdgpu_drm.h>
31 31 #include <drm/drm_drv.h>
32 32 #include <drm/drm_fb_helper.h>
33 + #include <drm/drm_vblank.h>
33 34 #include "amdgpu_uvd.h"
34 35 #include "amdgpu_vce.h"
35 36 #include "atom.h"
@@ -1660,6 +1661,9 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc)
1660 1661 DRM_ERROR("Invalid crtc %u\n", pipe);
1661 1662 return -EINVAL;
1662 1663 }
1664 + if (!down_read_trylock(&adev->reset_domain->sem))
1665 + return drm_crtc_vblank_count(crtc);
1666 +
1663 1667
1664 1668 /* The hw increments its frame counter at start of vsync, not at start
1665 1669 * of vblank, as is required by DRM core vblank counter handling.
@@ -1705,6 +1709,7 @@ u32 amdgpu_get_vblank_counter_kms(struct drm_crtc *crtc)
1705 1709 DRM_DEBUG_VBL("NULL mode info! Returned count may be wrong.\n");
1706 1710 }
1707 1711
1712 + up_read(&adev->reset_domain->sem);
1708 1713 return count;
1709 1714 }
1710 1715
modified drivers/gpu/drm/amd/amdgpu/amdgpu_ttm.c
@@ -2065,14 +2065,15 @@ static int amdgpu_ttm_buffer_entity_init(struct amdgpu_gtt_mgr *mgr,
2065 2065 int i, r, num_pages;
2066 2066 const u64 GTT_MAX_PAGES = (AMDGPU_GTT_MAX_TRANSFER_SIZE >> PAGE_SHIFT);
2067 2067
2068 + if (ARRAY_SIZE(entity->gart_window_offs) < num_gart_windows)
2069 + return -EINVAL;
2070 +
2068 2071 r = drm_sched_entity_init(&entity->base, prio, scheds, num_schedulers, NULL);
2069 2072 if (r)
2070 2073 return r;
2071 2074
2072 2075 mutex_init(&entity->lock);
2073 2076
2074 - if (ARRAY_SIZE(entity->gart_window_offs) < num_gart_windows)
2075 - return -EINVAL;
2076 2077 if (num_gart_windows == 0)
2077 2078 return 0;
2078 2079
@@ -2080,6 +2081,7 @@ static int amdgpu_ttm_buffer_entity_init(struct amdgpu_gtt_mgr *mgr,
2080 2081 r = amdgpu_gtt_mgr_alloc_entries(mgr, &entity->gart_node, num_pages,
2081 2082 DRM_MM_INSERT_BEST);
2082 2083 if (r) {
2084 + mutex_destroy(&entity->lock);
2083 2085 drm_sched_entity_destroy(&entity->base);
2084 2086 return r;
2085 2087 }
@@ -2097,6 +2099,7 @@ static void amdgpu_ttm_buffer_entity_fini(struct amdgpu_gtt_mgr *mgr,
2097 2099 struct amdgpu_ttm_buffer_entity *entity)
2098 2100 {
2099 2101 amdgpu_gtt_mgr_free_entries(mgr, &entity->gart_node);
2102 + mutex_destroy(&entity->lock);
2100 2103 drm_sched_entity_destroy(&entity->base);
2101 2104 }
2102 2105
modified drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c
@@ -472,6 +472,7 @@ amdgpu_userq_get_doorbell_index(struct amdgpu_userq_mgr *uq_mgr,
472 472 u64 doorbell_index;
473 473 struct drm_gem_object *gobj;
474 474 struct amdgpu_userq_obj *db_obj = db_info->db_obj;
475 + struct amdgpu_bo *abo;
475 476 int r, db_size;
476 477
477 478 gobj = drm_gem_object_lookup(filp, db_info->doorbell_handle);
@@ -480,7 +481,17 @@ amdgpu_userq_get_doorbell_index(struct amdgpu_userq_mgr *uq_mgr,
480 481 return -EINVAL;
481 482 }
482 483
483 - db_obj->obj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
484 + /*
485 + * Pinning a regular BO into the doorbell domain would discard its
486 + * contents, possibly those of a buffer shared by another client.
487 + */
488 + abo = gem_to_amdgpu_bo(gobj);
489 + if (!(abo->preferred_domains & AMDGPU_GEM_DOMAIN_DOORBELL)) {
490 + drm_gem_object_put(gobj);
491 + return -EINVAL;
492 + }
493 +
494 + db_obj->obj = amdgpu_bo_ref(abo);
484 495 drm_gem_object_put(gobj);
485 496
486 497 r = amdgpu_bo_reserve(db_obj->obj, true);
@@ -969,19 +980,21 @@ amdgpu_userq_bo_validate(struct amdgpu_device *adev, struct drm_exec *exec,
969 980 {
970 981 struct ttm_operation_ctx ctx = { false, false };
971 982 struct amdgpu_bo_va *bo_va;
972 - struct amdgpu_bo *bo;
983 + struct amdgpu_bo *bo, *tmp;
973 984 int ret;
974 985
975 986 spin_lock(&vm->individual_lock);
976 - while (!list_empty(&vm->always_valid.evicted)) {
977 - bo_va = list_first_entry(&vm->always_valid.evicted,
987 + while (!list_empty(&vm->individual.evicted)) {
988 + bo_va = list_first_entry(&vm->individual.evicted,
978 989 struct amdgpu_bo_va,
979 990 base.vm_status);
991 + bo = bo_va->base.bo;
992 + tmp = amdgpu_bo_ref(bo);
980 993 spin_unlock(&vm->individual_lock);
981 994
982 - bo = bo_va->base.bo;
983 995 ret = drm_exec_prepare_obj(exec, &bo->tbo.base,
984 996 TTM_NUM_MOVE_FENCES + 1);
997 + amdgpu_bo_unref(&tmp);
985 998 if (unlikely(ret))
986 999 return ret;
987 1000
modified drivers/gpu/drm/amd/amdgpu/mes_userqueue.c
@@ -361,8 +361,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue,
361 361
362 362 compute_mqd = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size);
363 363 if (IS_ERR(compute_mqd)) {
364 - DRM_ERROR("Failed to read user MQD\n");
365 - r = -ENOMEM;
364 + r = PTR_ERR(compute_mqd);
366 365 goto free_mqd;
367 366 }
368 367
@@ -406,8 +405,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue,
406 405
407 406 mqd_gfx_v11 = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size);
408 407 if (IS_ERR(mqd_gfx_v11)) {
409 - DRM_ERROR("Failed to read user MQD\n");
410 - r = -ENOMEM;
408 + r = PTR_ERR(mqd_gfx_v11);
411 409 goto free_mqd;
412 410 }
413 411
@@ -451,8 +449,7 @@ static int mes_userq_mqd_create(struct amdgpu_usermode_queue *queue,
451 449
452 450 mqd_sdma_v11 = memdup_user(u64_to_user_ptr(mqd_user->mqd), mqd_user->mqd_size);
453 451 if (IS_ERR(mqd_sdma_v11)) {
454 - DRM_ERROR("Failed to read sdma user MQD\n");
455 - r = -ENOMEM;
452 + r = PTR_ERR(mqd_sdma_v11);
456 453 goto free_mqd;
457 454 }
458 455
modified drivers/gpu/drm/amd/amdgpu/sdma_v3_0.c
@@ -457,6 +457,9 @@ static void sdma_v3_0_ring_emit_hdp_flush(struct amdgpu_ring *ring)
457 457 else
458 458 ref_and_mask = REG_SET_FIELD(ref_and_mask, GPU_HDP_FLUSH_DONE, SDMA1, 1);
459 459
460 + /* Hang workaround */
461 + amdgpu_ring_write(ring, SDMA_PKT_NOP_HEADER_OP(SDMA_OP_NOP));
462 +
460 463 amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_POLL_REGMEM) |
461 464 SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH(1) |
462 465 SDMA_PKT_POLL_REGMEM_HEADER_FUNC(3)); /* == */
@@ -484,6 +487,10 @@ static void sdma_v3_0_ring_emit_fence(struct amdgpu_ring *ring, u64 addr, u64 se
484 487 unsigned flags)
485 488 {
486 489 bool write64bit = flags & AMDGPU_FENCE_FLAG_64BIT;
490 +
491 + /* Hang workaround */
492 + amdgpu_ring_write(ring, SDMA_PKT_NOP_HEADER_OP(SDMA_OP_NOP));
493 +
487 494 /* write the fence */
488 495 amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_FENCE));
489 496 amdgpu_ring_write(ring, lower_32_bits(addr));
@@ -492,7 +499,11 @@ static void sdma_v3_0_ring_emit_fence(struct amdgpu_ring *ring, u64 addr, u64 se
492 499
493 500 /* optionally write high bits as well */
494 501 if (write64bit) {
502 + /* Hang workaround */
503 + amdgpu_ring_write(ring, SDMA_PKT_NOP_HEADER_OP(SDMA_OP_NOP));
504 +
495 505 addr += 4;
506 +
496 507 amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_FENCE));
497 508 amdgpu_ring_write(ring, lower_32_bits(addr));
498 509 amdgpu_ring_write(ring, upper_32_bits(addr));
@@ -1033,6 +1044,9 @@ static void sdma_v3_0_ring_emit_pipeline_sync(struct amdgpu_ring *ring)
1033 1044 uint32_t seq = ring->fence_drv.sync_seq;
1034 1045 uint64_t addr = ring->fence_drv.gpu_addr;
1035 1046
1047 + /* Hang workaround */
1048 + amdgpu_ring_write(ring, SDMA_PKT_NOP_HEADER_OP(SDMA_OP_NOP));
1049 +
1036 1050 /* wait for idle */
1037 1051 amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_POLL_REGMEM) |
1038 1052 SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH(0) |
@@ -1061,6 +1075,9 @@ static void sdma_v3_0_ring_emit_vm_flush(struct amdgpu_ring *ring,
1061 1075 {
1062 1076 amdgpu_gmc_emit_flush_gpu_tlb(ring, vmid, pd_addr);
1063 1077
1078 + /* Hang workaround */
1079 + amdgpu_ring_write(ring, SDMA_PKT_NOP_HEADER_OP(SDMA_OP_NOP));
1080 +
1064 1081 /* wait for flush */
1065 1082 amdgpu_ring_write(ring, SDMA_PKT_HEADER_OP(SDMA_OP_POLL_REGMEM) |
1066 1083 SDMA_PKT_POLL_REGMEM_HEADER_HDP_FLUSH(0) |
@@ -1510,11 +1527,11 @@ static const struct amdgpu_ring_funcs sdma_v3_0_ring_funcs = {
1510 1527 .get_wptr = sdma_v3_0_ring_get_wptr,
1511 1528 .set_wptr = sdma_v3_0_ring_set_wptr,
1512 1529 .emit_frame_size =
1513 - 6 + /* sdma_v3_0_ring_emit_hdp_flush */
1530 + 6 + 1 + /* sdma_v3_0_ring_emit_hdp_flush */
1514 1531 3 + /* hdp invalidate */
1515 - 6 + /* sdma_v3_0_ring_emit_pipeline_sync */
1516 - VI_FLUSH_GPU_TLB_NUM_WREG * 3 + 6 + /* sdma_v3_0_ring_emit_vm_flush */
1517 - 10 + 10 + 10, /* sdma_v3_0_ring_emit_fence x3 for user fence, vm fence */
1532 + 6 + 1 + /* sdma_v3_0_ring_emit_pipeline_sync */
1533 + VI_FLUSH_GPU_TLB_NUM_WREG * 3 + 6 + 1 + /* sdma_v3_0_ring_emit_vm_flush */
1534 + (10 + 1) * 3, /* sdma_v3_0_ring_emit_fence x3 for user fence, vm fence */
1518 1535 .emit_ib_size = 7 + 6, /* sdma_v3_0_ring_emit_ib */
1519 1536 .emit_ib = sdma_v3_0_ring_emit_ib,
1520 1537 .emit_fence = sdma_v3_0_ring_emit_fence,
modified drivers/gpu/drm/amd/amdgpu/uvd_v3_1.c
@@ -288,7 +288,7 @@ static int uvd_v3_1_fw_validate(struct amdgpu_device *adev)
288 288 int i;
289 289 uint32_t keysel = adev->uvd.keyselect;
290 290
291 - if (RREG32(mmUVD_FW_START) & UVD_FW_STATUS__PASS_MASK) {
291 + if (RREG32(mmUVD_FW_START)) {
292 292 dev_dbg(adev->dev, "UVD keyselect already set: 0x%x (on CPU: 0x%x)\n",
293 293 RREG32(mmUVD_FW_START), adev->uvd.keyselect);
294 294 return 0;
modified drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c
@@ -572,12 +572,32 @@ static int allocate_doorbell(struct qcm_process_device *qpd,
572 572 * we need the physical sdma engine id in order to get the
573 573 * correct doorbell offset.
574 574 */
575 - uint32_t valid_id = idx_offset[qpd->dqm->dev->node_id *
576 - get_num_all_sdma_engines(qpd->dqm) +
577 - q->properties.sdma_engine_id]
578 - + (q->properties.sdma_queue_id & 1)
579 - * KFD_QUEUE_DOORBELL_MIRROR_OFFSET
580 - + (q->properties.sdma_queue_id >> 1);
575 + u32 engine_base = idx_offset[dev->node_id *
576 + get_num_all_sdma_engines(qpd->dqm) +
577 + q->properties.sdma_engine_id];
578 + u32 valid_id;
579 +
580 + /*
581 + * With the aqua_vanjaram doorbell layout, a shader doorbell
582 + * write whose 32-byte block starts in the previous engine's
583 + * range rings that engine instead. Engine ranges are 10
584 + * indices apart (sdma_doorbell_range = 20 dwords, halved for
585 + * 8-byte doorbells, in aqua_vanjaram_doorbell_index_init()),
586 + * which puts odd engines 2 indices into a shared block.
587 + * Aligning costs at most 2 indices, and 8 queues per engine use
588 + * only 4 of the 10, so the aligned base stays in range. The
589 + * 512-index mirror offset keeps the alignment.
590 + */
591 + if (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3) ||
592 + KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4) ||
593 + KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0))
594 + engine_base = ALIGN(engine_base,
595 + KFD_SDMA_SHADER_DOORBELL_GRANULARITY);
596 +
597 + valid_id = engine_base +
598 + (q->properties.sdma_queue_id & 1) *
599 + KFD_QUEUE_DOORBELL_MIRROR_OFFSET +
600 + (q->properties.sdma_queue_id >> 1);
581 601
582 602 if (restore_id && *restore_id != valid_id)
583 603 return -EINVAL;
modified drivers/gpu/drm/amd/amdkfd/kfd_priv.h
@@ -133,6 +133,13 @@
133 133 */
134 134 #define KFD_QUEUE_DOORBELL_MIRROR_OFFSET 512
135 135
136 + /*
137 + * On GC 9.4.3, 9.4.4 and 9.5.0, doorbell writes issued from shaders are
138 + * routed to an SDMA engine at 32-byte granularity, i.e. 4 indices with the
139 + * 8-byte SDMA doorbells used on SOC15.
140 + */
141 + #define KFD_SDMA_SHADER_DOORBELL_GRANULARITY 4
142 +
136 143 /**
137 144 * enum kfd_ioctl_flags - KFD ioctl flags
138 145 * Various flags that can be set in &amdkfd_ioctl_desc.flags to control how
modified drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c
@@ -3708,6 +3708,13 @@ static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
3708 3708 struct amdgpu_dm_connector *aconn =
3709 3709 (struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
3710 3710
3711 + if (!acrtc_state->base.async_flip) {
3712 + amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
3713 + psr_event_immediate_flip, false);
3714 + amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
3715 + replay_event_immediate_flip, false);
3716 + }
3717 +
3711 3718 /* Decrement skip count when SR is enabled and we're doing fast updates. */
3712 3719 if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
3713 3720 (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
@@ -4118,6 +4125,18 @@ static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
4118 4125 spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4119 4126 }
4120 4127 mutex_lock(&dm->dc_lock);
4128 + /*
4129 + * Tearing (immediate) flips cannot work with panel self-refresh
4130 + * features. The event is cleared by
4131 + * amdgpu_dm_enable_self_refresh() once async flips stop.
4132 + */
4133 + if (immediate_flip) {
4134 + dc_exit_ips_for_hw_access(dm->dc);
4135 + amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
4136 + psr_event_immediate_flip, true);
4137 + amdgpu_dm_replay_set_event(dm, acrtc_state->stream, true,
4138 + replay_event_immediate_flip, true);
4139 + }
4121 4140 update_planes_and_stream_adapter(dm->dc,
4122 4141 acrtc_state->update_type,
4123 4142 planes_count,
modified drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_connector.c
@@ -1012,10 +1012,15 @@ decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
1012 1012 const struct drm_display_mode *native_mode,
1013 1013 bool scale_enabled)
1014 1014 {
1015 + /* Inserted modes copy the native sync; a sink mode with equal totals may not */
1015 1016 if (scale_enabled || (
1016 1017 native_mode->clock == drm_mode->clock &&
1017 1018 native_mode->htotal == drm_mode->htotal &&
1018 - native_mode->vtotal == drm_mode->vtotal)) {
1019 + native_mode->vtotal == drm_mode->vtotal &&
1020 + native_mode->hsync_start == drm_mode->hsync_start &&
1021 + native_mode->hsync_end == drm_mode->hsync_end &&
1022 + native_mode->vsync_start == drm_mode->vsync_start &&
1023 + native_mode->vsync_end == drm_mode->vsync_end)) {
1019 1024 if (native_mode->crtc_clock)
1020 1025 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
1021 1026 } else {
modified drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_plane.c
@@ -112,25 +112,7 @@ void amdgpu_dm_plane_fill_blending_from_plane_state(const struct drm_plane_state
112 112
113 113 if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI ||
114 114 plane_state->pixel_blend_mode == DRM_MODE_BLEND_COVERAGE) {
115 - static const uint32_t alpha_formats[] = {
116 - DRM_FORMAT_ARGB8888,
117 - DRM_FORMAT_RGBA8888,
118 - DRM_FORMAT_ABGR8888,
119 - DRM_FORMAT_ARGB2101010,
120 - DRM_FORMAT_ABGR2101010,
121 - DRM_FORMAT_ARGB16161616,
122 - DRM_FORMAT_ABGR16161616,
123 - DRM_FORMAT_ARGB16161616F,
124 - };
125 - uint32_t format = plane_state->fb->format->format;
126 - unsigned int i;
127 -
128 - for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
129 - if (format == alpha_formats[i]) {
130 - *per_pixel_alpha = true;
131 - break;
132 - }
133 - }
115 + *per_pixel_alpha = plane_state->fb->format->has_alpha;
134 116
135 117 if (*per_pixel_alpha && plane_state->pixel_blend_mode == DRM_MODE_BLEND_COVERAGE)
136 118 *pre_multiplied_alpha = false;
modified drivers/gpu/drm/amd/display/amdgpu_dm/tests/amdgpu_dm_connector_test.c
@@ -1572,6 +1572,46 @@ static void dm_test_decide_crtc_timing_no_crtc_clock(struct kunit *test)
1572 1572 KUNIT_EXPECT_EQ(test, drm_mode.crtc_hdisplay, 0);
1573 1573 }
1574 1574
1575 + static void dm_test_decide_crtc_timing_sink_mode_same_totals(struct kunit *test)
1576 + {
1577 + struct drm_display_mode native_mode = {
1578 + DRM_MODE("3840x2160", DRM_MODE_TYPE_DRIVER, 594000, 3840, 4016, 4104,
1579 + 4400, 0, 2160, 2168, 2178, 2250, 0,
1580 + DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) };
1581 + struct drm_display_mode drm_mode = {
1582 + DRM_MODE("4096x2160", DRM_MODE_TYPE_DRIVER, 594000, 4096, 4184, 4272,
1583 + 4400, 0, 2160, 2168, 2178, 2250, 0,
1584 + DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) };
1585 +
1586 + drm_mode_set_crtcinfo(&native_mode, 0);
1587 + drm_mode_set_crtcinfo(&drm_mode, 0);
1588 +
1589 + decide_crtc_timing_for_drm_display_mode(&drm_mode, &native_mode, false);
1590 +
1591 + KUNIT_EXPECT_EQ(test, drm_mode.crtc_hdisplay, 4096);
1592 + KUNIT_EXPECT_EQ(test, drm_mode.crtc_hsync_start, 4184);
1593 + }
1594 +
1595 + static void dm_test_decide_crtc_timing_inserted_mode(struct kunit *test)
1596 + {
1597 + struct drm_display_mode native_mode = {
1598 + DRM_MODE("3840x2160", DRM_MODE_TYPE_DRIVER, 594000, 3840, 4016, 4104,
1599 + 4400, 0, 2160, 2168, 2178, 2250, 0,
1600 + DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC) };
1601 + struct drm_display_mode drm_mode;
1602 +
1603 + drm_mode_set_crtcinfo(&native_mode, 0);
1604 + drm_mode = native_mode;
1605 + drm_mode.hdisplay = 1920;
1606 + drm_mode.vdisplay = 1080;
1607 + drm_mode_set_crtcinfo(&drm_mode, 0);
1608 +
1609 + decide_crtc_timing_for_drm_display_mode(&drm_mode, &native_mode, false);
1610 +
1611 + KUNIT_EXPECT_EQ(test, drm_mode.crtc_hdisplay, 3840);
1612 + KUNIT_EXPECT_EQ(test, drm_mode.crtc_vdisplay, 2160);
1613 + }
1614 +
1575 1615 /* Tests for amdgpu_dm_connector_funcs_reset() */
1576 1616
1577 1617 static const struct drm_connector_funcs dm_test_connector_funcs = {
@@ -5635,6 +5675,8 @@ static struct kunit_case amdgpu_dm_connector_tests[] = {
5635 5675 KUNIT_CASE(dm_test_decide_crtc_timing_matching_mode),
5636 5676 KUNIT_CASE(dm_test_decide_crtc_timing_no_copy),
5637 5677 KUNIT_CASE(dm_test_decide_crtc_timing_no_crtc_clock),
5678 + KUNIT_CASE(dm_test_decide_crtc_timing_sink_mode_same_totals),
5679 + KUNIT_CASE(dm_test_decide_crtc_timing_inserted_mode),
5638 5680 /* amdgpu_dm_connector_funcs_reset */
5639 5681 KUNIT_CASE(dm_test_funcs_reset_sets_defaults),
5640 5682 KUNIT_CASE(dm_test_funcs_reset_edp_abm_level),
modified drivers/gpu/drm/amd/pm/swsmu/smu14/smu_v14_0_2_ppt.c
@@ -89,6 +89,7 @@ static const struct smu_feature_bits smu_v14_0_2_dpm_features = {
89 89 #define PP_OD_FEATURE_FAN_TARGET_TEMPERATURE 9
90 90 #define PP_OD_FEATURE_FAN_MINIMUM_PWM 10
91 91 #define PP_OD_FEATURE_FAN_ZERO_RPM_ENABLE 11
92 + #define PP_OD_FEATURE_FAN_ZERO_RPM_STOP_TEMP 12
92 93
93 94 static struct cmn2asic_msg_mapping smu_v14_0_2_message_map[SMU_MSG_MAX_COUNT] = {
94 95 MSG_MAP(TestMessage, PPSMC_MSG_TestMessage, 1),
@@ -1020,6 +1021,10 @@ static void smu_v14_0_2_get_od_setting_limits(struct smu_context *smu,
1020 1021 od_min_setting = overdrive_lowerlimits->FanZeroRpmEnable;
1021 1022 od_max_setting = overdrive_upperlimits->FanZeroRpmEnable;
1022 1023 break;
1024 + case PP_OD_FEATURE_FAN_ZERO_RPM_STOP_TEMP:
1025 + od_min_setting = pptable->SkuTable.MsgLimits.FanStopTempMin;
1026 + od_max_setting = pptable->SkuTable.MsgLimits.FanStopTempMax;
1027 + break;
1023 1028 default:
1024 1029 od_min_setting = od_max_setting = INT_MAX;
1025 1030 break;
@@ -1244,6 +1249,24 @@ static int smu_v14_0_2_emit_clk_levels(struct smu_context *smu,
1244 1249 min_value, max_value);
1245 1250 break;
1246 1251
1252 + case SMU_OD_FAN_ZERO_RPM_STOP_TEMP:
1253 + if (!smu_v14_0_2_is_od_feature_supported(smu,
1254 + PP_OD_FEATURE_ZERO_FAN_BIT))
1255 + break;
1256 +
1257 + size += sysfs_emit_at(buf, size, "FAN_ZERO_RPM_STOP_TEMPERATURE:\n");
1258 + size += sysfs_emit_at(buf, size, "%d\n",
1259 + (int)od_table->OverDriveTable.FanZeroRpmStopTemp);
1260 +
1261 + size += sysfs_emit_at(buf, size, "%s:\n", "OD_RANGE");
1262 + smu_v14_0_2_get_od_setting_limits(smu,
1263 + PP_OD_FEATURE_FAN_ZERO_RPM_STOP_TEMP,
1264 + &min_value,
1265 + &max_value);
1266 + size += sysfs_emit_at(buf, size, "ZERO_RPM_STOP_TEMPERATURE: %u %u\n",
1267 + min_value, max_value);
1268 + break;
1269 +
1247 1270 case SMU_OD_RANGE:
1248 1271 if (!smu_v14_0_2_is_od_feature_supported(smu, PP_OD_FEATURE_GFXCLK_BIT) &&
1249 1272 !smu_v14_0_2_is_od_feature_supported(smu, PP_OD_FEATURE_UCLK_BIT) &&
@@ -2311,7 +2334,9 @@ static void smu_v14_0_2_set_supported_od_feature_mask(struct smu_context *smu)
2311 2334 OD_OPS_SUPPORT_FAN_MINIMUM_PWM_RETRIEVE |
2312 2335 OD_OPS_SUPPORT_FAN_MINIMUM_PWM_SET |
2313 2336 OD_OPS_SUPPORT_FAN_ZERO_RPM_ENABLE_RETRIEVE |
2314 - OD_OPS_SUPPORT_FAN_ZERO_RPM_ENABLE_SET;
2337 + OD_OPS_SUPPORT_FAN_ZERO_RPM_ENABLE_SET |
2338 + OD_OPS_SUPPORT_FAN_ZERO_RPM_STOP_TEMP_RETRIEVE |
2339 + OD_OPS_SUPPORT_FAN_ZERO_RPM_STOP_TEMP_SET;
2315 2340 }
2316 2341
2317 2342 static int smu_v14_0_2_get_overdrive_table(struct smu_context *smu,
@@ -2392,6 +2417,8 @@ static int smu_v14_0_2_set_default_od_settings(struct smu_context *smu)
2392 2417 user_od_table_bak.OverDriveTable.FanMinimumPwm;
2393 2418 user_od_table->OverDriveTable.FanZeroRpmEnable =
2394 2419 user_od_table_bak.OverDriveTable.FanZeroRpmEnable;
2420 + user_od_table->OverDriveTable.FanZeroRpmStopTemp =
2421 + user_od_table_bak.OverDriveTable.FanZeroRpmStopTemp;
2395 2422 }
2396 2423
2397 2424 smu_v14_0_2_set_supported_od_feature_mask(smu);
@@ -2446,6 +2473,11 @@ static int smu_v14_0_2_od_restore_table_single(struct smu_context *smu, long inp
2446 2473 boot_overdrive_table->OverDriveTable.FanZeroRpmEnable;
2447 2474 od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT);
2448 2475 break;
2476 + case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP:
2477 + od_table->OverDriveTable.FanZeroRpmStopTemp =
2478 + boot_overdrive_table->OverDriveTable.FanZeroRpmStopTemp;
2479 + od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT);
2480 + break;
2449 2481 case PP_OD_EDIT_ACOUSTIC_LIMIT:
2450 2482 od_table->OverDriveTable.AcousticLimitRpmThreshold =
2451 2483 boot_overdrive_table->OverDriveTable.AcousticLimitRpmThreshold;
@@ -2752,6 +2784,27 @@ static int smu_v14_0_2_od_edit_dpm_table(struct smu_context *smu,
2752 2784 od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT);
2753 2785 break;
2754 2786
2787 + case PP_OD_EDIT_FAN_ZERO_RPM_STOP_TEMP:
2788 + if (!smu_v14_0_2_is_od_feature_supported(smu, PP_OD_FEATURE_ZERO_FAN_BIT)) {
2789 + dev_warn(adev->dev, "Zero RPM setting not supported!\n");
2790 + return -ENOTSUPP;
2791 + }
2792 +
2793 + smu_v14_0_2_get_od_setting_limits(smu,
2794 + PP_OD_FEATURE_FAN_ZERO_RPM_STOP_TEMP,
2795 + &minimum,
2796 + &maximum);
2797 + if (input[0] < minimum ||
2798 + input[0] > maximum) {
2799 + dev_info(adev->dev, "zero RPM stop temperature setting(%ld) must be within [%d, %d]!\n",
2800 + input[0], minimum, maximum);
2801 + return -EINVAL;
2802 + }
2803 +
2804 + od_table->OverDriveTable.FanZeroRpmStopTemp = input[0];
2805 + od_table->OverDriveTable.FeatureCtrlMask |= BIT(PP_OD_FEATURE_ZERO_FAN_BIT);
2806 + break;
2807 +
2755 2808 case PP_OD_RESTORE_DEFAULT_TABLE:
2756 2809 if (size == 1) {
2757 2810 ret = smu_v14_0_2_od_restore_table_single(smu, input[0]);
modified drivers/gpu/drm/aspeed/aspeed_gfx_drv.c
@@ -189,13 +189,12 @@ static int aspeed_gfx_load(struct drm_device *drm)
189 189 }
190 190 reset_control_deassert(priv->rst);
191 191
192 - priv->clk = devm_clk_get(drm->dev, NULL);
192 + priv->clk = devm_clk_get_enabled(drm->dev, NULL);
193 193 if (IS_ERR(priv->clk)) {
194 194 dev_err(&pdev->dev,
195 - "missing or invalid clk device tree entry");
195 + "failed to get and enable clock\n");
196 196 return PTR_ERR(priv->clk);
197 197 }
198 - clk_prepare_enable(priv->clk);
199 198
200 199 /* Sanitize control registers */
201 200 writel(0, priv->base + CRT_CTRL1);
modified drivers/gpu/drm/bridge/th1520-dw-hdmi.c
@@ -135,8 +135,8 @@ static int th1520_dw_hdmi_probe(struct platform_device *pdev)
135 135 plat_data->priv_data = hdmi;
136 136
137 137 hdmi->dw_hdmi = dw_hdmi_probe(pdev, plat_data);
138 - if (IS_ERR(hdmi))
139 - return PTR_ERR(hdmi);
138 + if (IS_ERR(hdmi->dw_hdmi))
139 + return PTR_ERR(hdmi->dw_hdmi);
140 140
141 141 platform_set_drvdata(pdev, hdmi);
142 142
@@ -145,9 +145,9 @@ static int th1520_dw_hdmi_probe(struct platform_device *pdev)
145 145
146 146 static void th1520_dw_hdmi_remove(struct platform_device *pdev)
147 147 {
148 - struct dw_hdmi *hdmi = platform_get_drvdata(pdev);
148 + struct th1520_hdmi *hdmi = platform_get_drvdata(pdev);
149 149
150 - dw_hdmi_remove(hdmi);
150 + dw_hdmi_remove(hdmi->dw_hdmi);
151 151 }
152 152
153 153 static const struct of_device_id th1520_dw_hdmi_of_table[] = {
modified drivers/gpu/drm/display/drm_dp_helper.c
@@ -4634,7 +4634,9 @@ static int dp_aux_backlight_update_status(struct backlight_device *bd)
4634 4634
4635 4635 if (!backlight_is_blank(bd)) {
4636 4636 if (!bl->enabled) {
4637 - drm_edp_backlight_enable(bl->aux, &bl->info, brightness);
4637 + ret = drm_edp_backlight_enable(bl->aux, &bl->info, brightness);
4638 + if (ret)
4639 + return ret;
4638 4640 bl->enabled = true;
4639 4641 return 0;
4640 4642 }
modified drivers/gpu/drm/drm_bridge.c
@@ -454,8 +454,10 @@ void drm_bridge_add(struct drm_bridge *bridge)
454 454 * in bridge_lingering_list. Remove it or bridge_lingering_list will be
455 455 * corrupted when adding this bridge to bridge_list below.
456 456 */
457 + mutex_lock(&bridge_lock);
457 458 if (!list_empty(&bridge->list))
458 459 list_del_init(&bridge->list);
460 + mutex_unlock(&bridge_lock);
459 461
460 462 mutex_init(&bridge->hpd_state_mutex);
461 463 mutex_init(&bridge->hpd_mutex);
@@ -593,8 +595,10 @@ int drm_bridge_attach(struct drm_encoder *encoder, struct drm_bridge *bridge,
593 595 if (!bridge->container)
594 596 DRM_WARN("DRM bridge corrupted or not allocated by devm_drm_bridge_alloc()\n");
595 597
596 - if (list_empty(&bridge->list))
597 - DRM_WARN("Missing drm_bridge_add() before attach\n");
598 + scoped_guard(mutex, &bridge_lock) {
599 + if (list_empty(&bridge->list))
600 + DRM_WARN("Missing drm_bridge_add() before attach\n");
601 + }
598 602
599 603 drm_bridge_get(bridge);
600 604
modified drivers/gpu/drm/drm_exec.c
@@ -48,6 +48,16 @@
48 48 * See struct dma_exec for more details.
49 49 */
50 50
51 + /* Unlock and put the prelocked obj */
52 + static void drm_exec_drop_prelocked(struct drm_exec *exec)
53 + {
54 + if (exec->prelocked) {
55 + dma_resv_unlock(exec->prelocked->resv);
56 + drm_gem_object_put(exec->prelocked);
57 + exec->prelocked = NULL;
58 + }
59 + }
60 +
51 61 /* Unlock all objects and drop references */
52 62 static void drm_exec_unlock_all(struct drm_exec *exec)
53 63 {
@@ -58,8 +68,7 @@ static void drm_exec_unlock_all(struct drm_exec *exec)
58 68 drm_gem_object_put(obj);
59 69 }
60 70
61 - drm_gem_object_put(exec->prelocked);
62 - exec->prelocked = NULL;
71 + drm_exec_drop_prelocked(exec);
63 72 }
64 73
65 74 /**
@@ -118,6 +127,14 @@ EXPORT_SYMBOL(drm_exec_fini);
118 127 bool drm_exec_cleanup(struct drm_exec *exec)
119 128 {
120 129 if (likely(!exec->contended)) {
130 +
131 + /*
132 + * The contended and prelocked object might never be passed to
133 + * drm_exec_lock_obj() again. This can happen when the object
134 + * is about to be cleaned up and we now hold the last reference
135 + * to it. Make sure that we don't unnecessarily keep it around.
136 + */
137 + drm_exec_drop_prelocked(exec);
121 138 ww_acquire_done(&exec->ticket);
122 139 return false;
123 140 }
@@ -175,16 +192,16 @@ static int drm_exec_lock_contended(struct drm_exec *exec)
175 192 dma_resv_lock_slow(obj->resv, &exec->ticket);
176 193 }
177 194
178 - ret = drm_exec_obj_locked(exec, obj);
179 - if (unlikely(ret))
180 - goto error_unlock;
195 + /*
196 + * It is perfectly possible that we see another contention before the
197 + * first one is fully handled.
198 + */
199 + drm_exec_drop_prelocked(exec);
181 200
201 + /* We move the reference from contended to prelocked here */
182 202 exec->prelocked = obj;
183 203 return 0;
184 204
185 - error_unlock:
186 - dma_resv_unlock(obj->resv);
187 -
188 205 error_dropref:
189 206 drm_gem_object_put(obj);
190 207 return ret;
@@ -212,35 +229,31 @@ int drm_exec_lock_obj(struct drm_exec *exec, struct drm_gem_object *obj)
212 229 if (exec->prelocked == obj) {
213 230 drm_gem_object_put(exec->prelocked);
214 231 exec->prelocked = NULL;
215 - return 0;
216 - }
232 + } else {
233 + if (exec->flags & DRM_EXEC_INTERRUPTIBLE_WAIT)
234 + ret = dma_resv_lock_interruptible(obj->resv,
235 + &exec->ticket);
236 + else
237 + ret = dma_resv_lock(obj->resv, &exec->ticket);
238 +
239 + if (unlikely(ret == -EDEADLK)) {
240 + drm_gem_object_get(obj);
241 + exec->contended = obj;
242 + return -EDEADLK;
243 + }
217 244
218 - if (exec->flags & DRM_EXEC_INTERRUPTIBLE_WAIT)
219 - ret = dma_resv_lock_interruptible(obj->resv, &exec->ticket);
220 - else
221 - ret = dma_resv_lock(obj->resv, &exec->ticket);
245 + if (unlikely(ret == -EALREADY) &&
246 + exec->flags & DRM_EXEC_IGNORE_DUPLICATES)
247 + return 0;
222 248
223 - if (unlikely(ret == -EDEADLK)) {
224 - drm_gem_object_get(obj);
225 - exec->contended = obj;
226 - return -EDEADLK;
249 + if (unlikely(ret))
250 + return ret;
227 251 }
228 252
229 - if (unlikely(ret == -EALREADY) &&
230 - exec->flags & DRM_EXEC_IGNORE_DUPLICATES)
231 - return 0;
232 -
233 - if (unlikely(ret))
234 - return ret;
235 -
236 253 ret = drm_exec_obj_locked(exec, obj);
237 254 if (ret)
238 - goto error_unlock;
239 -
240 - return 0;
255 + dma_resv_unlock(obj->resv);
241 256
242 - error_unlock:
243 - dma_resv_unlock(obj->resv);
244 257 return ret;
245 258 }
246 259 EXPORT_SYMBOL(drm_exec_lock_obj);
modified drivers/gpu/drm/drm_fb_helper.c
@@ -1724,10 +1724,10 @@ __drm_fb_helper_initial_config_and_unlock(struct drm_fb_helper *fb_helper)
1724 1724
1725 1725 ret = drm_fb_helper_single_fb_probe(fb_helper);
1726 1726 if (ret < 0) {
1727 - if (ret == -EAGAIN) {
1728 - fb_helper->deferred_setup = true;
1727 + /* modesets are probed but fb_helper->fb isn't; defer restore too */
1728 + fb_helper->deferred_setup = true;
1729 + if (ret == -EAGAIN)
1729 1730 ret = 0;
1730 - }
1731 1731 mutex_unlock(&fb_helper->lock);
1732 1732
1733 1733 goto err_drm_fb_helper_release_info;
modified drivers/gpu/drm/gud/gud_pipe.c
@@ -507,6 +507,7 @@ int gud_plane_atomic_check(struct drm_plane *plane,
507 507 for_each_new_connector_in_state(state, connector, connector_state, i) {
508 508 if (connector_state->crtc)
509 509 break;
510 + connector_state = NULL;
510 511 }
511 512
512 513 /*
modified drivers/gpu/drm/i915/display/intel_cx0_phy.c
@@ -2342,12 +2342,14 @@ static void intel_c10pll_dump_hw_state(struct drm_printer *p,
2342 2342 static bool is_arrowlake_s_by_host_bridge(void)
2343 2343 {
2344 2344 struct pci_dev *pdev = NULL;
2345 - u16 host_bridge_pci_dev_id;
2346 -
2347 - while ((pdev = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, pdev)))
2348 - host_bridge_pci_dev_id = pdev->device;
2345 + while ((pdev = pci_get_class(PCI_CLASS_BRIDGE_HOST << 8, pdev))) {
2346 + if (IS_ARROWLAKE_S_BY_HOST_BRIDGE_ID(pdev->device)) {
2347 + pci_dev_put(pdev);
2348 + return true;
2349 + }
2350 + }
2349 2351
2350 - return pdev && IS_ARROWLAKE_S_BY_HOST_BRIDGE_ID(host_bridge_pci_dev_id);
2352 + return false;
2351 2353 }
2352 2354
2353 2355 static u16 intel_c20_hdmi_tmds_tx_cgf_1(struct intel_display *display)
modified drivers/gpu/drm/i915/display/intel_dmc.c
@@ -1023,6 +1023,55 @@ static void dmc_set_fw_offset(struct intel_dmc *dmc,
1023 1023 }
1024 1024 }
1025 1025
1026 + /*
1027 + * Check if the load address is within the valid range for the given DMC ID.
1028 + */
1029 + static bool dmc_load_addr_sanity_check(struct intel_dmc *dmc,
1030 + u32 start_addr, u32 payload_size,
1031 + int header_ver, enum intel_dmc_id dmc_id)
1032 + {
1033 + u32 start_range, end_range, end_addr;
1034 +
1035 + if (header_ver != 3)
1036 + return true;
1037 +
1038 + switch (dmc_id) {
1039 + case DMC_FW_MAIN:
1040 + start_range = DMC_MAIN_PROGRAM_BASE_START;
1041 + end_range = DMC_MAIN_PROGRAM_BASE_END;
1042 + break;
1043 + case DMC_FW_PIPEA:
1044 + start_range = DMC_PIPEA_PROGRAM_BASE_START;
1045 + end_range = DMC_PIPEA_PROGRAM_BASE_END;
1046 + break;
1047 + case DMC_FW_PIPEB:
1048 + start_range = DMC_PIPEB_PROGRAM_BASE_START;
1049 + end_range = DMC_PIPEB_PROGRAM_BASE_END;
1050 + break;
1051 + case DMC_FW_PIPEC:
1052 + start_range = DMC_PIPEC_PROGRAM_BASE_START;
1053 + end_range = DMC_PIPEC_PROGRAM_BASE_END;
1054 + break;
1055 + case DMC_FW_PIPED:
1056 + start_range = DMC_PIPED_PROGRAM_BASE_START;
1057 + end_range = DMC_PIPED_PROGRAM_BASE_END;
1058 + break;
1059 + default:
1060 + MISSING_CASE(dmc_id);
1061 + return false;
1062 + }
1063 +
1064 + if (payload_size == 0)
1065 + end_addr = start_addr;
1066 + else if (check_add_overflow(start_addr, payload_size - 1, &end_addr))
1067 + return false;
1068 +
1069 + if (start_addr < start_range || end_addr > end_range)
1070 + return false;
1071 +
1072 + return true;
1073 + }
1074 +
1026 1075 static bool dmc_mmio_addr_sanity_check(struct intel_dmc *dmc,
1027 1076 const u32 *mmioaddr, u32 mmio_count,
1028 1077 int header_ver, enum intel_dmc_id dmc_id)
@@ -1120,7 +1169,7 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,
1120 1169 }
1121 1170
1122 1171 /* Cache the dmc header info. */
1123 - if (mmio_count > mmio_count_max) {
1172 + if (!mmio_count || mmio_count > mmio_count_max) {
1124 1173 drm_err(display->drm, "DMC firmware has wrong mmio count %u\n", mmio_count);
1125 1174 return 0;
1126 1175 }
@@ -1166,13 +1215,21 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,
1166 1215 disable_dmc_evt(display, dmc_id, dmc_info->mmioaddr[i],
1167 1216 dmc_info->mmiodata[i]) ? " (disabling)" : "");
1168 1217 }
1169 - dmc_info->mmio_count = mmio_count;
1170 - dmc_info->start_mmioaddr = start_mmioaddr;
1171 1218
1172 1219 rem_size -= header_len_bytes;
1173 1220
1174 1221 /* fw_size is in dwords, so multiplied by 4 to convert into bytes. */
1175 - payload_size = dmc_header->fw_size * 4;
1222 + if (check_mul_overflow(dmc_header->fw_size, 4u, &payload_size)) {
1223 + drm_err(display->drm, "DMC fw_size too large (%u dwords)\n",
1224 + dmc_header->fw_size);
1225 + return 0;
1226 + }
1227 +
1228 + if (!payload_size) {
1229 + drm_err(display->drm, "DMC firmware has empty payload\n");
1230 + return 0;
1231 + }
1232 +
1176 1233 if (rem_size < payload_size)
1177 1234 goto error_truncated;
1178 1235
@@ -1180,12 +1237,21 @@ static u32 parse_dmc_fw_header(struct intel_dmc *dmc,
1180 1237 drm_err(display->drm, "DMC FW too big (%u bytes)\n", payload_size);
1181 1238 return 0;
1182 1239 }
1183 - dmc_info->dmc_fw_size = dmc_header->fw_size;
1240 +
1241 + if (!dmc_load_addr_sanity_check(dmc, start_mmioaddr, payload_size,
1242 + dmc_header->header_ver, dmc_id)) {
1243 + drm_err(display->drm, "DMC %d: firmware has wrong load address\n", dmc_id);
1244 + return 0;
1245 + }
1184 1246
1185 1247 dmc_info->payload = kmalloc(payload_size, GFP_KERNEL);
1186 1248 if (!dmc_info->payload)
1187 1249 return 0;
1188 1250
1251 + dmc_info->mmio_count = mmio_count;
1252 + dmc_info->start_mmioaddr = start_mmioaddr;
1253 + dmc_info->dmc_fw_size = dmc_header->fw_size;
1254 +
1189 1255 payload = (u8 *)(dmc_header) + header_len_bytes;
1190 1256 memcpy(dmc_info->payload, payload, payload_size);
1191 1257
modified drivers/gpu/drm/i915/display/intel_dmc_regs.h
@@ -521,6 +521,18 @@ enum pipedmc_event_id {
521 521 #define TGL_PIPE_MMIO_END(dmc_id) _PICK_EVEN(((dmc_id) - 1), _TGL_PIPEA_MMIO_END,\
522 522 _TGL_PIPEB_MMIO_END)
523 523
524 + /* For DMC header version v3*/
525 + #define DMC_MAIN_PROGRAM_BASE_START 0x80000
526 + #define DMC_MAIN_PROGRAM_BASE_END 0x86fff
527 + #define DMC_PIPEA_PROGRAM_BASE_START 0x90000
528 + #define DMC_PIPEA_PROGRAM_BASE_END 0x96fff
529 + #define DMC_PIPEB_PROGRAM_BASE_START 0x98000
530 + #define DMC_PIPEB_PROGRAM_BASE_END 0x9efff
531 + #define DMC_PIPEC_PROGRAM_BASE_START 0x52000
532 + #define DMC_PIPEC_PROGRAM_BASE_END 0x53fff
533 + #define DMC_PIPED_PROGRAM_BASE_START 0x59000
534 + #define DMC_PIPED_PROGRAM_BASE_END 0x5afff
535 +
524 536 #define SKL_DMC_DC3_DC5_COUNT _MMIO(0x80030)
525 537 #define SKL_DMC_DC5_DC6_COUNT _MMIO(0x8002C)
526 538 #define BXT_DMC_DC3_DC5_COUNT _MMIO(0x80038)
modified drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c
@@ -1766,6 +1766,7 @@ static int eb_reinit_userptr(struct i915_execbuffer *eb)
1766 1766
1767 1767 static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb)
1768 1768 {
1769 + const unsigned int count = eb->buffer_count;
1769 1770 bool have_copy = false;
1770 1771 struct eb_vma *ev;
1771 1772 int err = 0;
@@ -1868,7 +1869,6 @@ err:
1868 1869
1869 1870 out:
1870 1871 if (have_copy) {
1871 - const unsigned int count = eb->buffer_count;
1872 1872 unsigned int i;
1873 1873
1874 1874 for (i = 0; i < count; i++) {
modified drivers/gpu/drm/i915/gt/intel_rps.c
@@ -1904,7 +1904,8 @@ static void rps_work(struct work_struct *work)
1904 1904
1905 1905 out:
1906 1906 spin_lock_irq(gt->irq_lock);
1907 - gen6_gt_pm_unmask_irq(gt, rps->pm_events);
1907 + if (intel_rps_is_active(rps))
1908 + gen6_gt_pm_unmask_irq(gt, rps->pm_events);
1908 1909 spin_unlock_irq(gt->irq_lock);
1909 1910 }
1910 1911
modified drivers/gpu/drm/imagination/pvr_mmu.c
@@ -2337,7 +2337,7 @@ void pvr_mmu_op_context_destroy(struct pvr_mmu_op_context *op_ctx)
2337 2337 * @ctx: MMU context associated with owning VM context.
2338 2338 * @sgt: Scatter gather table containing pages pinned for use by this context.
2339 2339 * @device_addr: Virtual device address at the start of the requested mapping.
2340 - * @sgt_offset: Start offset of the requested device-virtual memory mapping.
2340 + * @sgt_offset: Offset into @sgt of the start of the requested mapping.
2341 2341 * @size: Size in bytes of the requested device-virtual memory mapping. For an
2342 2342 * unmapping, this should be zero so that no page tables are allocated.
2343 2343 *
@@ -2350,7 +2350,6 @@ struct pvr_mmu_op_context *
2350 2350 pvr_mmu_op_context_create(struct pvr_mmu_context *ctx, struct sg_table *sgt,
2351 2351 u64 device_addr, u64 sgt_offset, u64 size)
2352 2352 {
2353 - u64 start_addr = device_addr + sgt_offset;
2354 2353 int err;
2355 2354
2356 2355 struct pvr_mmu_op_context *op_ctx = kzalloc_obj(*op_ctx);
@@ -2365,18 +2364,18 @@ pvr_mmu_op_context_create(struct pvr_mmu_context *ctx, struct sg_table *sgt,
2365 2364
2366 2365 if (size) {
2367 2366 /*
2368 - * The number of page table objects we need to prealloc is
2369 - * indicated by the mapping size, start address and the sizes
2370 - * of the areas mapped per PT or PD. The range calculation is
2371 - * identical to that for the index into a table for a device
2372 - * address, so we reuse those functions here.
2367 + * The page tables needed are set by the device-virtual range
2368 + * being mapped: one level 1 table per 1GiB region and one
2369 + * level 0 table per 2MiB region the range touches. Tables that
2370 + * already exist are not consumed, so this is an upper bound.
2373 2371 */
2374 - const u32 l1_start_idx = pvr_page_table_l2_idx(start_addr);
2375 - const u32 l1_end_idx = pvr_page_table_l2_idx(start_addr + size);
2376 - const u32 l1_count = l1_end_idx - l1_start_idx + 1;
2377 - const u32 l0_start_idx = pvr_page_table_l1_idx(start_addr);
2378 - const u32 l0_end_idx = pvr_page_table_l1_idx(start_addr + size);
2379 - const u32 l0_count = l0_end_idx - l0_start_idx + 1;
2372 + const u64 last_addr = device_addr + size - 1;
2373 + const u64 l1_count =
2374 + (last_addr >> ROGUE_MMUCTRL_VADDR_PC_INDEX_SHIFT) -
2375 + (device_addr >> ROGUE_MMUCTRL_VADDR_PC_INDEX_SHIFT) + 1;
2376 + const u64 l0_count =
2377 + (last_addr >> ROGUE_MMUCTRL_VADDR_PD_INDEX_SHIFT) -
2378 + (device_addr >> ROGUE_MMUCTRL_VADDR_PD_INDEX_SHIFT) + 1;
2380 2379
2381 2380 /*
2382 2381 * Alloc and push page table entries until we have enough of
modified drivers/gpu/drm/imagination/pvr_vm.c
@@ -418,6 +418,8 @@ pvr_vm_gpuva_unmap(struct drm_gpuva_op *op, void *op_ctx)
418 418 static int
419 419 pvr_vm_gpuva_remap(struct drm_gpuva_op *op, void *op_ctx)
420 420 {
421 + /* The split parts belong to the object of the mapping being split. */
422 + struct drm_gpuvm_bo *vm_bo = op->remap.unmap->va->vm_bo;
421 423 struct pvr_vm_bind_op *ctx = op_ctx;
422 424 u64 va_start = 0, va_range = 0;
423 425 int err;
@@ -433,14 +435,12 @@ pvr_vm_gpuva_remap(struct drm_gpuva_op *op, void *op_ctx)
433 435 drm_gpuva_remap(&ctx->prev_va->base, &ctx->next_va->base, &op->remap);
434 436
435 437 if (op->remap.prev) {
436 - pvr_gem_object_get(gem_to_pvr_gem(ctx->prev_va->base.gem.obj));
437 - drm_gpuva_link(&ctx->prev_va->base, ctx->gpuvm_bo);
438 + drm_gpuva_link(&ctx->prev_va->base, vm_bo);
438 439 ctx->prev_va = NULL;
439 440 }
440 441
441 442 if (op->remap.next) {
442 - pvr_gem_object_get(gem_to_pvr_gem(ctx->next_va->base.gem.obj));
443 - drm_gpuva_link(&ctx->next_va->base, ctx->gpuvm_bo);
443 + drm_gpuva_link(&ctx->next_va->base, vm_bo);
444 444 ctx->next_va = NULL;
445 445 }
446 446
modified drivers/gpu/drm/nouveau/nouveau_abi16.c
@@ -488,7 +488,7 @@ nouveau_abi16_ioctl_channel_alloc(ABI16_IOCTL_ARGS)
488 488 goto done;
489 489 break;
490 490 case NV_DEVICE_INFO_V0_TURING:
491 - if (engine != NV_DEVICE_HOST_RUNLIST_ENGINES_NVDEC) {
491 + if (engine == NV_DEVICE_HOST_RUNLIST_ENGINES_GR) {
492 492 ret = nvif_object_ctor(&chan->chan->user, "abi16CeWar",
493 493 0, TURING_DMA_COPY_A, NULL, 0,
494 494 &chan->ce);
modified drivers/gpu/drm/nouveau/nvkm/engine/device/user.c
@@ -201,7 +201,7 @@ nvkm_udevice_gcx_ready(struct nvkm_udevice *udev, void *data, u32 size)
201 201 } *args = data;
202 202 int ret = -ENOSYS;
203 203
204 - if (!gsp) {
204 + if (!gsp || !gsp->rm) {
205 205 args->v0.ready = NV_DEVICE_GC6_READY | NV_DEVICE_GCOFF_READY;
206 206 return 0;
207 207 }
modified drivers/gpu/drm/panthor/panthor_hw.c
@@ -136,7 +136,7 @@ static char *get_gpu_model_name(struct panthor_device *ptdev)
136 136 case GPU_PROD_ID_MAKE(10, 7):
137 137 return "Mali-G610";
138 138 case GPU_PROD_ID_MAKE(11, 2):
139 - if (shader_core_count > 10 && ray_intersection)
139 + if (shader_core_count >= 10 && ray_intersection)
140 140 return "Mali-G715-Immortalis";
141 141 else if (shader_core_count >= 7)
142 142 return "Mali-G715";
modified drivers/gpu/drm/panthor/panthor_sched.c
@@ -3674,6 +3674,9 @@ int panthor_group_create(struct panthor_file *pfile,
3674 3674 hweight64(group_args->tiler_core_mask) < group_args->max_tiler_cores)
3675 3675 return -EINVAL;
3676 3676
3677 + if (group_args->queues.count > sched->cs_slot_count)
3678 + return -EINVAL;
3679 +
3677 3680 group = kzalloc_obj(*group);
3678 3681 if (!group)
3679 3682 return -ENOMEM;
modified drivers/gpu/drm/vc4/vc4_bo.c
@@ -204,7 +204,7 @@ static struct list_head *vc4_get_cache_list_for_size(struct drm_device *dev,
204 204 struct list_head *new_list;
205 205 uint32_t i;
206 206
207 - new_list = kmalloc_objs(struct list_head, new_size);
207 + new_list = kvmalloc_objs(struct list_head, new_size);
208 208 if (!new_list)
209 209 return NULL;
210 210
@@ -224,7 +224,7 @@ static struct list_head *vc4_get_cache_list_for_size(struct drm_device *dev,
224 224 for (i = vc4->bo_cache.size_list_size; i < new_size; i++)
225 225 INIT_LIST_HEAD(&new_list[i]);
226 226
227 - kfree(vc4->bo_cache.size_list);
227 + kvfree(vc4->bo_cache.size_list);
228 228 vc4->bo_cache.size_list = new_list;
229 229 vc4->bo_cache.size_list_size = new_size;
230 230 }
@@ -1052,6 +1052,7 @@ static void vc4_bo_cache_destroy(struct drm_device *dev, void *unused)
1052 1052 cancel_work_sync(&vc4->bo_cache.time_work);
1053 1053
1054 1054 vc4_bo_cache_purge(dev);
1055 + kvfree(vc4->bo_cache.size_list);
1055 1056
1056 1057 for (i = 0; i < vc4->num_labels; i++) {
1057 1058 if (vc4->bo_labels[i].num_allocated) {
modified drivers/gpu/drm/vc4/vc4_drv.c
@@ -360,8 +360,11 @@ static int vc4_drm_bind(struct device *dev)
360 360 }
361 361
362 362 ret = aperture_remove_all_conflicting_devices(driver->name);
363 - if (ret)
363 + if (ret) {
364 + if (firmware)
365 + rpi_firmware_put(firmware);
364 366 goto err;
367 + }
365 368
366 369 if (firmware) {
367 370 ret = rpi_firmware_property(firmware,
modified drivers/gpu/drm/vc4/vc4_drv.h
@@ -1051,7 +1051,7 @@ void vc4_plane_async_set_fb(struct drm_plane *plane,
1051 1051 /* vc4_v3d.c */
1052 1052 extern struct platform_driver vc4_v3d_driver;
1053 1053 extern const struct of_device_id vc4_v3d_dt_match[];
1054 - int vc4_v3d_get_bin_slot(struct vc4_dev *vc4);
1054 + int vc4_v3d_get_bin_slot(struct vc4_dev *vc4, long timeout);
1055 1055 int vc4_v3d_bin_bo_get(struct vc4_dev *vc4, bool *used);
1056 1056 void vc4_v3d_bin_bo_put(struct vc4_dev *vc4);
1057 1057 int vc4_v3d_pm_get(struct vc4_dev *vc4);
modified drivers/gpu/drm/vc4/vc4_gem.c
@@ -877,11 +877,17 @@ vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec)
877 877 drm_gem_object_put(&bo->base.base);
878 878 }
879 879
880 - /* Free up the allocation of any bin slots we used. */
880 + /* Free up the allocation of any bin slots we used. Jobs that ran to
881 + * completion had their slots released in vc4_irq_finish_render_job().
882 + * Only jobs that never completed still have slots to be released here.
883 + */
881 884 spin_lock_irqsave(&vc4->job_lock, irqflags);
882 885 vc4->bin_alloc_used &= ~exec->bin_slots;
883 886 spin_unlock_irqrestore(&vc4->job_lock, irqflags);
884 887
888 + /* Let anyone waiting on the binner pool retry. */
889 + wake_up_all(&vc4->job_wait_queue);
890 +
885 891 /* Release the reference on the binner BO if needed. */
886 892 if (exec->bin_bo_used)
887 893 vc4_v3d_bin_bo_put(vc4);
modified drivers/gpu/drm/vc4/vc4_hdmi.c
@@ -894,7 +894,7 @@ static void vc4_hdmi_encoder_post_crtc_disable(struct drm_encoder *encoder,
894 894
895 895 spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
896 896
897 - HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, 0);
897 + HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, VC4_HDMI_RAM_PACKET_ENABLE);
898 898
899 899 HDMI_WRITE(HDMI_VID_CTL, HDMI_READ(HDMI_VID_CTL) | VC4_HD_VID_CTL_CLRRGB);
900 900
@@ -1663,9 +1663,6 @@ static void vc4_hdmi_encoder_post_crtc_enable(struct drm_encoder *encoder,
1663 1663 WARN_ONCE(ret, "Timeout waiting for "
1664 1664 "VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE\n");
1665 1665 } else {
1666 - HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1667 - HDMI_READ(HDMI_RAM_PACKET_CONFIG) &
1668 - ~(VC4_HDMI_RAM_PACKET_ENABLE));
1669 1666 HDMI_WRITE(HDMI_SCHEDULER_CONTROL,
1670 1667 HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1671 1668 ~VC4_HDMI_SCHEDULER_CONTROL_MODE_HDMI);
@@ -1684,9 +1681,6 @@ static void vc4_hdmi_encoder_post_crtc_enable(struct drm_encoder *encoder,
1684 1681 WARN_ON(!(HDMI_READ(HDMI_SCHEDULER_CONTROL) &
1685 1682 VC4_HDMI_SCHEDULER_CONTROL_HDMI_ACTIVE));
1686 1683
1687 - HDMI_WRITE(HDMI_RAM_PACKET_CONFIG,
1688 - VC4_HDMI_RAM_PACKET_ENABLE);
1689 -
1690 1684 spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
1691 1685 vc4_hdmi->packet_ram_enabled = true;
1692 1686
@@ -3143,6 +3137,11 @@ static int vc5_hdmi_init_resources(struct drm_device *drm,
3143 3137 static int vc4_hdmi_runtime_suspend(struct device *dev)
3144 3138 {
3145 3139 struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3140 + unsigned long flags;
3141 +
3142 + spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3143 + HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, 0);
3144 + spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3146 3145
3147 3146 clk_disable_unprepare(vc4_hdmi->audio_clock);
3148 3147 clk_disable_unprepare(vc4_hdmi->hsm_clock);
@@ -3153,9 +3152,8 @@ static int vc4_hdmi_runtime_suspend(struct device *dev)
3153 3152 static int vc4_hdmi_runtime_resume(struct device *dev)
3154 3153 {
3155 3154 struct vc4_hdmi *vc4_hdmi = dev_get_drvdata(dev);
3156 - unsigned long __maybe_unused flags;
3155 + unsigned long rate, flags;
3157 3156 u32 __maybe_unused value;
3158 - unsigned long rate;
3159 3157 int ret;
3160 3158
3161 3159 ret = clk_prepare_enable(vc4_hdmi->hsm_clock);
@@ -3201,6 +3199,10 @@ static int vc4_hdmi_runtime_resume(struct device *dev)
3201 3199 }
3202 3200 #endif
3203 3201
3202 + spin_lock_irqsave(&vc4_hdmi->hw_lock, flags);
3203 + HDMI_WRITE(HDMI_RAM_PACKET_CONFIG, VC4_HDMI_RAM_PACKET_ENABLE);
3204 + spin_unlock_irqrestore(&vc4_hdmi->hw_lock, flags);
3205 +
3204 3206 return 0;
3205 3207
3206 3208 err_disable_clk:
modified drivers/gpu/drm/vc4/vc4_irq.c
@@ -74,7 +74,7 @@ vc4_overflow_mem_work(struct work_struct *work)
74 74
75 75 bo = vc4->bin_bo;
76 76
77 - bin_bo_slot = vc4_v3d_get_bin_slot(vc4);
77 + bin_bo_slot = vc4_v3d_get_bin_slot(vc4, msecs_to_jiffies(500));
78 78 if (bin_bo_slot < 0) {
79 79 drm_err(&vc4->base, "Couldn't allocate binner overflow mem\n");
80 80 goto complete;
@@ -165,6 +165,10 @@ vc4_irq_finish_render_job(struct drm_device *dev)
165 165 trace_vc4_rcl_end_irq(dev, exec->seqno);
166 166
167 167 vc4->finished_seqno++;
168 +
169 + vc4->bin_alloc_used &= ~exec->bin_slots;
170 + exec->bin_slots = 0;
171 +
168 172 list_move_tail(&exec->head, &vc4->job_done_list);
169 173
170 174 nextbin = vc4_first_bin_job(vc4);
@@ -276,7 +280,7 @@ vc4_irq_disable(struct drm_device *dev)
276 280 V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS);
277 281
278 282 /* Finish any interrupt handler still in flight. */
279 - synchronize_irq(vc4->irq);
283 + disable_irq(vc4->irq);
280 284
281 285 cancel_work_sync(&vc4->overflow_mem_work);
282 286 }
@@ -284,7 +288,6 @@ vc4_irq_disable(struct drm_device *dev)
284 288 int vc4_irq_install(struct drm_device *dev, int irq)
285 289 {
286 290 struct vc4_dev *vc4 = to_vc4_dev(dev);
287 - int ret;
288 291
289 292 if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
290 293 return -ENODEV;
@@ -298,19 +301,8 @@ int vc4_irq_install(struct drm_device *dev, int irq)
298 301 init_waitqueue_head(&vc4->job_wait_queue);
299 302 INIT_WORK(&vc4->overflow_mem_work, vc4_overflow_mem_work);
300 303
301 - /* Clear any pending interrupts someone might have left around
302 - * for us.
303 - */
304 - V3D_WRITE(V3D_INTCTL, V3D_DRIVER_IRQS);
305 -
306 - ret = devm_request_irq(dev->dev, irq, vc4_irq, 0,
307 - dev_name(dev->dev), dev);
308 - if (ret)
309 - return ret;
310 -
311 - vc4_irq_enable(dev);
312 -
313 - return 0;
304 + return devm_request_irq(dev->dev, irq, vc4_irq, IRQF_NO_AUTOEN,
305 + dev_name(dev->dev), dev);
314 306 }
315 307
316 308 void vc4_irq_uninstall(struct drm_device *dev)
modified drivers/gpu/drm/vc4/vc4_v3d.c
@@ -9,6 +9,7 @@
9 9 #include <linux/component.h>
10 10 #include <linux/platform_device.h>
11 11 #include <linux/pm_runtime.h>
12 + #include <linux/timer.h>
12 13
13 14 #include <drm/drm_print.h>
14 15
@@ -172,46 +173,42 @@ static void vc4_v3d_init_hw(struct drm_device *dev)
172 173 V3D_WRITE(V3D_VPMBASE, 0);
173 174 }
174 175
175 - int vc4_v3d_get_bin_slot(struct vc4_dev *vc4)
176 + static int bin_slot_try_alloc(struct vc4_dev *vc4)
176 177 {
177 - struct drm_device *dev = &vc4->base;
178 - unsigned long irqflags;
179 178 int slot;
180 - uint64_t seqno = 0;
181 - struct vc4_exec_info *exec;
182 179
183 - if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
184 - return -ENODEV;
180 + guard(spinlock_irqsave)(&vc4->job_lock);
185 181
186 - try_again:
187 - spin_lock_irqsave(&vc4->job_lock, irqflags);
188 182 slot = ffs(~vc4->bin_alloc_used);
189 183 if (slot != 0) {
190 184 /* Switch from ffs() bit index to a 0-based index. */
191 185 slot--;
192 186 vc4->bin_alloc_used |= BIT(slot);
193 - spin_unlock_irqrestore(&vc4->job_lock, irqflags);
194 - return slot;
187 + } else {
188 + slot = -ENOMEM;
195 189 }
196 190
197 - /* Couldn't find an open slot. Wait for render to complete
198 - * and try again.
199 - */
200 - exec = vc4_last_render_job(vc4);
201 - if (exec)
202 - seqno = exec->seqno;
203 - spin_unlock_irqrestore(&vc4->job_lock, irqflags);
191 + return slot;
192 + }
204 193
205 - if (seqno) {
206 - int ret = vc4_wait_for_seqno(dev, seqno, ~0ull, true);
194 + int vc4_v3d_get_bin_slot(struct vc4_dev *vc4, long timeout)
195 + {
196 + int slot;
197 + long ret;
207 198
208 - if (ret == 0)
209 - goto try_again;
199 + if (WARN_ON_ONCE(vc4->gen > VC4_GEN_4))
200 + return -ENODEV;
210 201
202 + /* If the pool is full, wait for a job to release its slots. */
203 + ret = wait_event_interruptible_timeout(vc4->job_wait_queue,
204 + (slot = bin_slot_try_alloc(vc4)) >= 0,
205 + timeout);
206 + if (ret < 0)
211 207 return ret;
212 - }
208 + if (ret == 0)
209 + return -ENOMEM;
213 210
214 - return -ENOMEM;
211 + return slot;
215 212 }
216 213
217 214 /*
@@ -396,6 +393,7 @@ static int vc4_v3d_runtime_resume(struct device *dev)
396 393 vc4_v3d_init_hw(&vc4->base);
397 394
398 395 vc4_irq_enable(&vc4->base);
396 + enable_irq(vc4->irq);
399 397
400 398 return 0;
401 399 }
@@ -452,6 +450,12 @@ static int vc4_v3d_bind(struct device *dev, struct device *master, void *data)
452 450 return ret;
453 451 vc4->irq = ret;
454 452
453 + ret = vc4_irq_install(drm, vc4->irq);
454 + if (ret) {
455 + drm_err(drm, "Failed to install IRQ handler\n");
456 + return ret;
457 + }
458 +
455 459 ret = devm_pm_runtime_enable(dev);
456 460 if (ret)
457 461 return ret;
@@ -473,12 +477,6 @@ static int vc4_v3d_bind(struct device *dev, struct device *master, void *data)
473 477 V3D_WRITE(V3D_BPOA, 0);
474 478 V3D_WRITE(V3D_BPOS, 0);
475 479
476 - ret = vc4_irq_install(drm, vc4->irq);
477 - if (ret) {
478 - drm_err(drm, "Failed to install IRQ handler\n");
479 - goto err_put_runtime_pm;
480 - }
481 -
482 480 pm_runtime_use_autosuspend(dev);
483 481 pm_runtime_set_autosuspend_delay(dev, 40); /* a little over 2 frames. */
484 482 pm_runtime_put_autosuspend(dev);
@@ -497,8 +495,15 @@ static void vc4_v3d_unbind(struct device *dev, struct device *master,
497 495 struct drm_device *drm = data;
498 496 struct vc4_dev *vc4 = to_vc4_dev(drm);
499 497
498 + /* A straggler vc4_reset() re-enables the interrupt. */
499 + timer_shutdown_sync(&vc4->hangcheck.timer);
500 + cancel_work_sync(&vc4->hangcheck.reset_work);
501 +
500 502 vc4_irq_uninstall(drm);
501 503
504 + /* Flush rather than cancel, so queued completions release their jobs. */
505 + flush_work(&vc4->job_done_work);
506 +
502 507 /* Disable the binner's overflow memory address, so the next
503 508 * driver probe (if any) doesn't try to reuse our old
504 509 * allocation.
modified drivers/gpu/drm/vc4/vc4_validate.c
@@ -402,7 +402,7 @@ validate_tile_binning_config(VALIDATE_ARGS)
402 402 return -EINVAL;
403 403 }
404 404
405 - bin_slot = vc4_v3d_get_bin_slot(vc4);
405 + bin_slot = vc4_v3d_get_bin_slot(vc4, MAX_SCHEDULE_TIMEOUT);
406 406 if (bin_slot < 0) {
407 407 if (bin_slot != -EINTR && bin_slot != -ERESTARTSYS) {
408 408 drm_err(dev, "Failed to allocate binner memory: %d\n",
modified drivers/gpu/drm/virtio/virtgpu_drv.c
@@ -225,6 +225,7 @@ static int virtgpu_freeze(struct virtio_device *vdev)
225 225 goto err_resume;
226 226 }
227 227
228 + virtio_reset_device(vdev);
228 229 vdev->config->del_vqs(vdev);
229 230
230 231 return 0;
modified drivers/gpu/drm/virtio/virtgpu_plane.c
@@ -589,7 +589,6 @@ struct drm_plane *virtio_gpu_plane_init(struct virtio_gpu_device *vgdev,
589 589 struct drm_plane *plane;
590 590 const uint32_t *formats;
591 591 int nformats;
592 - int ret;
593 592
594 593 if (type == DRM_PLANE_TYPE_CURSOR) {
595 594 formats = virtio_gpu_cursor_formats;
@@ -615,17 +614,5 @@ struct drm_plane *virtio_gpu_plane_init(struct virtio_gpu_device *vgdev,
615 614 drm_plane_create_blend_mode_property(plane,
616 615 BIT(DRM_MODE_BLEND_PREMULTI));
617 616
618 - if (type == DRM_PLANE_TYPE_CURSOR) {
619 - /*
620 - * The cursor plane exposes a format with an alpha channel,
621 - * which requires a blend mode property. The host blends
622 - * premultiplied alpha, matching the property's default.
623 - */
624 - ret = drm_plane_create_blend_mode_property(plane,
625 - BIT(DRM_MODE_BLEND_PREMULTI));
626 - if (ret)
627 - return ERR_PTR(ret);
628 - }
629 -
630 617 return plane;
631 618 }
modified drivers/gpu/drm/vmwgfx/vmwgfx_cursor_plane.c
@@ -324,6 +324,7 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,
324 324 unsigned long kmap_num;
325 325 SVGA3dCopyBox *box;
326 326 u32 box_count;
327 + u64 src_extent;
327 328 void *virtual;
328 329 bool is_iomem;
329 330 struct vmw_dma_cmd {
@@ -335,6 +336,8 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,
335 336 vmw_surface_get_desc(VMW_CURSOR_SNOOP_FORMAT);
336 337 const u32 image_pitch = VMW_CURSOR_SNOOP_WIDTH * desc->pitchBytesPerBlock;
337 338
339 + BUILD_BUG_ON(sizeof(*srf->snooper.image) != desc->pitchBytesPerBlock);
340 +
338 341 cmd = container_of(header, struct vmw_dma_cmd, header);
339 342
340 343 /* No snooper installed, nothing to copy */
@@ -372,8 +375,19 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,
372 375 return;
373 376 }
374 377
378 + if (box->w == 0 || box->h == 0)
379 + return;
380 +
381 + src_extent = (u64)(box->h - 1) * cmd->dma.guest.pitch +
382 + (u64)box->w * desc->pitchBytesPerBlock;
383 + if (src_extent > bo->base.size) {
384 + DRM_ERROR("Cursor snoop source of %llu bytes exceeds the %zu byte buffer\n",
385 + src_extent, bo->base.size);
386 + return;
387 + }
388 +
375 389 kmap_offset = cmd->dma.guest.ptr.offset >> PAGE_SHIFT;
376 - kmap_num = (VMW_CURSOR_SNOOP_HEIGHT * image_pitch) >> PAGE_SHIFT;
390 + kmap_num = PFN_UP(src_extent);
377 391
378 392 ret = ttm_bo_reserve(bo, true, false, NULL);
379 393 if (unlikely(ret != 0)) {
@@ -387,14 +401,16 @@ void vmw_kms_cursor_snoop(struct vmw_surface *srf,
387 401
388 402 virtual = ttm_kmap_obj_virtual(&map, &is_iomem);
389 403
390 - if (box->w == VMW_CURSOR_SNOOP_WIDTH && cmd->dma.guest.pitch == image_pitch) {
404 + if (box->w == VMW_CURSOR_SNOOP_WIDTH &&
405 + box->h == VMW_CURSOR_SNOOP_HEIGHT &&
406 + cmd->dma.guest.pitch == image_pitch) {
391 407 memcpy(srf->snooper.image, virtual,
392 408 VMW_CURSOR_SNOOP_HEIGHT * image_pitch);
393 409 } else {
394 - /* Image is unsigned pointer. */
410 + /* The destination stride is in pixels. */
395 411 for (i = 0; i < box->h; i++)
396 - memcpy(srf->snooper.image + i * image_pitch,
397 - virtual + i * cmd->dma.guest.pitch,
412 + memcpy(srf->snooper.image + i * VMW_CURSOR_SNOOP_WIDTH,
413 + virtual + (size_t)i * cmd->dma.guest.pitch,
398 414 box->w * desc->pitchBytesPerBlock);
399 415 }
400 416 srf->snooper.id++;
modified drivers/gpu/drm/vmwgfx/vmwgfx_kms.c
@@ -20,10 +20,18 @@
20 20 #include <drm/drm_rect.h>
21 21 #include <drm/drm_sysfs.h>
22 22 #include <drm/drm_edid.h>
23 + #include <drm/drm_blend.h>
23 24
24 25 void vmw_du_init(struct vmw_display_unit *du)
25 26 {
26 27 vmw_vkms_crtc_init(&du->crtc);
28 + drm_plane_create_blend_mode_property(&du->primary,
29 + BIT(DRM_MODE_BLEND_PIXEL_NONE) |
30 + BIT(DRM_MODE_BLEND_PREMULTI));
31 + // Check that the cursor plane was actually initialized
32 + if (du->crtc.cursor == &du->cursor.base)
33 + drm_plane_create_blend_mode_property(&du->cursor.base,
34 + BIT(DRM_MODE_BLEND_PREMULTI));
27 35 }
28 36
29 37 void vmw_du_cleanup(struct vmw_display_unit *du)
modified drivers/gpu/drm/xe/display/xe_fb_pin.c
@@ -356,7 +356,7 @@ static struct i915_vma *__xe_pin_fb_vma(struct drm_gem_object *obj, bool is_dpt,
356 356 drm_exec_retry_on_contention(&exec);
357 357 xe_validation_retry_on_oom(&ctx, &ret);
358 358 if (!ret)
359 - ttm_bo_pin(&bo->ttm);
359 + xe_bo_pin_account(bo);
360 360 }
361 361 if (ret)
362 362 goto err;
@@ -373,7 +373,7 @@ static struct i915_vma *__xe_pin_fb_vma(struct drm_gem_object *obj, bool is_dpt,
373 373
374 374 err_unpin:
375 375 ttm_bo_reserve(&bo->ttm, false, false, NULL);
376 - ttm_bo_unpin(&bo->ttm);
376 + xe_bo_unpin_account(bo);
377 377 ttm_bo_unreserve(&bo->ttm);
378 378 err:
379 379 kfree(vma);
@@ -393,7 +393,7 @@ static void __xe_unpin_fb_vma(struct i915_vma *vma)
393 393 xe_ggtt_node_remove(vma->node, false);
394 394
395 395 ttm_bo_reserve(&vma->bo->ttm, false, false, NULL);
396 - ttm_bo_unpin(&vma->bo->ttm);
396 + xe_bo_unpin_account(vma->bo);
397 397 ttm_bo_unreserve(&vma->bo->ttm);
398 398 kfree(vma);
399 399 }
modified drivers/gpu/drm/xe/xe_bo.c
@@ -330,6 +330,12 @@ static void xe_evict_flags(struct ttm_buffer_object *tbo,
330 330 return;
331 331 }
332 332
333 + /* No resource: nothing is placed/mapped, so there is nothing to evict. */
334 + if (!tbo->resource) {
335 + placement->num_placement = 0;
336 + return;
337 + }
338 +
333 339 bo = ttm_to_xe_bo(tbo);
334 340 if (bo->flags & XE_BO_FLAG_CPU_ADDR_MIRROR) {
335 341 *placement = sys_placement;
@@ -455,6 +461,100 @@ static void xe_ttm_tt_account_subtract(struct xe_device *xe, struct ttm_tt *tt)
455 461 xe_shrinker_mod_pages(xe->mem.shrinker, -(long)tt->num_pages, 0);
456 462 }
457 463
464 + static bool xe_ttm_bo_is_imported(struct ttm_buffer_object *tbo)
465 + {
466 + dma_resv_assert_held(tbo->base.resv);
467 +
468 + return tbo->ttm &&
469 + (tbo->ttm->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE)) ==
470 + TTM_TT_FLAG_EXTERNAL;
471 + }
472 +
473 + /*
474 + * Account @bo's pages as pinned for the shrinker. Removes @bo's pages
475 + * from the shrinker's shrinkable / purgeable counts on the transition
476 + * from unpinned to pinned. Must be called with @bo's dma-resv held,
477 + * after &ttm_buffer_object.pin_count has been incremented by
478 + * ttm_bo_pin(). Safe to call unconditionally regardless of which pin
479 + * path (kernel, external, framebuffer, backup object, ...) is pinning
480 + * @bo, since it only acts on the true 0->1 pin_count transition.
481 + *
482 + * Imported bos (xe_ttm_bo_is_imported()) are excluded: for those,
483 + * xe_ttm_tt_populate() never actually populates the tt or calls
484 + * xe_ttm_tt_account_add(), but TTM core's ttm_tt_populate() still
485 + * unconditionally marks the tt as populated on driver-hook success.
486 + * Relying on ttm_tt_is_populated() for these would subtract pages that
487 + * were never added, underflowing the shrinker's counts.
488 + */
489 + static void xe_bo_account_pin(struct xe_bo *bo)
490 + {
491 + struct xe_device *xe = xe_bo_device(bo);
492 +
493 + if (bo->ttm.pin_count == 1 && bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm) &&
494 + !xe_ttm_bo_is_imported(&bo->ttm))
495 + xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
496 + }
497 +
498 + /*
499 + * Counterpart to xe_bo_account_pin(). Must be called with @bo's dma-resv
500 + * held, before &ttm_buffer_object.pin_count is decremented by
501 + * ttm_bo_unpin(), so that the check against the true 1->0 transition sees
502 + * the pin count that is about to be released. See xe_bo_account_pin() for
503 + * why imported bos are excluded.
504 + *
505 + * On the true last unpin, also removes @bo from whichever pinned-bo list
506 + * (external or kernel_bo_present) it may currently be linked on, since a
507 + * bo's final unpin can happen through a pin path (e.g. framebuffer,
508 + * backup object) that has no notion of, or ownership over, that list.
509 + * This is safe and list-agnostic: list_del_init() only needs the node
510 + * itself, not knowledge of which list it is threaded through, and is a
511 + * no-op if @bo is not linked.
512 + */
513 + static void xe_bo_account_unpin(struct xe_bo *bo)
514 + {
515 + struct xe_device *xe = xe_bo_device(bo);
516 + bool last_unpin = bo->ttm.pin_count == 1;
517 +
518 + if (last_unpin && !list_empty(&bo->pinned_link)) {
519 + spin_lock(&xe->pinned.lock);
520 + list_del_init(&bo->pinned_link);
521 + spin_unlock(&xe->pinned.lock);
522 + }
523 +
524 + if (last_unpin && bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm) &&
525 + !xe_ttm_bo_is_imported(&bo->ttm))
526 + xe_ttm_tt_account_add(xe, bo->ttm.ttm);
527 + }
528 +
529 + /**
530 + * xe_bo_pin_account() - Pin a bo and account its pages for the shrinker
531 + * @bo: The buffer object to pin.
532 + *
533 + * Pins @bo via ttm_bo_pin() and updates the shrinker's shrinkable /
534 + * purgeable page accounting to match. Must be called with @bo's dma-resv
535 + * held. Safe to call regardless of which pin path (kernel, external,
536 + * framebuffer, backup object, ...) is pinning @bo.
537 + */
538 + void xe_bo_pin_account(struct xe_bo *bo)
539 + {
540 + ttm_bo_pin(&bo->ttm);
541 + xe_bo_account_pin(bo);
542 + }
543 +
544 + /**
545 + * xe_bo_unpin_account() - Unpin a bo and account its pages for the shrinker
546 + * @bo: The buffer object to unpin.
547 + *
548 + * Counterpart to xe_bo_pin_account(). Updates the shrinker's shrinkable /
549 + * purgeable page accounting to match, then unpins @bo via ttm_bo_unpin().
550 + * Must be called with @bo's dma-resv held.
551 + */
552 + void xe_bo_unpin_account(struct xe_bo *bo)
553 + {
554 + xe_bo_account_unpin(bo);
555 + ttm_bo_unpin(&bo->ttm);
556 + }
557 +
458 558 static void update_global_total_pages(struct ttm_device *ttm_dev,
459 559 long num_pages)
460 560 {
@@ -850,6 +950,8 @@ static int xe_bo_move_notify(struct xe_bo *bo,
850 950 *
851 951 * Transfers pages between shrinkable and purgeable buckets when the BO
852 952 * purgeable state changes. Called automatically from xe_bo_set_purgeable_state().
953 + * For pinned BOs, whose pages are not accounted, only the purgeable flag is
954 + * updated, so that the correct bucket is used when the BO is unpinned.
853 955 */
854 956 static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
855 957 enum xe_madv_purgeable_state new_state)
@@ -866,7 +968,8 @@ static void xe_bo_set_purgeable_shrinker(struct xe_bo *bo,
866 968 return;
867 969
868 970 xe_tt = container_of(tt, struct xe_ttm_tt, ttm);
869 - tt_pages = tt->num_pages;
971 + /* Pinned bos are not accounted. Only update the purgeable flag. */
972 + tt_pages = xe_bo_is_pinned(bo) ? 0 : tt->num_pages;
870 973
871 974 if (!xe_tt->purgeable && new_state == XE_MADV_PURGEABLE_DONTNEED) {
872 975 xe_tt->purgeable = true;
@@ -1389,7 +1492,8 @@ int xe_bo_notifier_prepare_pinned(struct xe_bo *bo)
1389 1492 }
1390 1493
1391 1494 backup->parent_obj = xe_bo_get(bo); /* Released by bo_destroy */
1392 - ttm_bo_pin(&backup->ttm);
1495 + /* Note: XE_BO_FLAG_SYSTEM resolves to XE_PL_TT so already populated. */
1496 + xe_bo_pin_account(backup);
1393 1497 bo->backup_obj = backup;
1394 1498 }
1395 1499
@@ -1409,7 +1513,7 @@ int xe_bo_notifier_unprepare_pinned(struct xe_bo *bo)
1409 1513 {
1410 1514 xe_bo_lock(bo, false);
1411 1515 if (bo->backup_obj) {
1412 - ttm_bo_unpin(&bo->backup_obj->ttm);
1516 + xe_bo_unpin_account(bo->backup_obj);
1413 1517 xe_bo_put(bo->backup_obj);
1414 1518 bo->backup_obj = NULL;
1415 1519 }
@@ -1620,7 +1724,7 @@ out_backup:
1620 1724 xe_bo_vunmap(backup);
1621 1725 if (!bo->backup_obj) {
1622 1726 if (xe_bo_is_pinned(backup))
1623 - ttm_bo_unpin(&backup->ttm);
1727 + xe_bo_unpin_account(backup);
1624 1728 xe_bo_put(backup);
1625 1729 }
1626 1730 out_unlock_bo:
@@ -2012,15 +2116,6 @@ static vm_fault_t xe_err_to_fault_t(int err)
2012 2116 return VM_FAULT_SIGBUS;
2013 2117 }
2014 2118
2015 - static bool xe_ttm_bo_is_imported(struct ttm_buffer_object *tbo)
2016 - {
2017 - dma_resv_assert_held(tbo->base.resv);
2018 -
2019 - return tbo->ttm &&
2020 - (tbo->ttm->page_flags & (TTM_TT_FLAG_EXTERNAL | TTM_TT_FLAG_EXTERNAL_MAPPABLE)) ==
2021 - TTM_TT_FLAG_EXTERNAL;
2022 - }
2023 -
2024 2119 static vm_fault_t xe_bo_cpu_fault_fastpath(struct vm_fault *vmf, struct xe_device *xe,
2025 2120 struct xe_bo *bo, bool needs_rpm)
2026 2121 {
@@ -3141,12 +3236,13 @@ uint64_t vram_region_gpu_offset(struct ttm_resource *res)
3141 3236 int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
3142 3237 {
3143 3238 struct xe_device *xe = xe_bo_device(bo);
3239 + bool first_pin = !xe_bo_is_pinned(bo);
3144 3240 int err;
3145 3241
3146 3242 xe_assert(xe, !bo->vm);
3147 3243 xe_assert(xe, xe_bo_is_user(bo));
3148 3244
3149 - if (!xe_bo_is_pinned(bo)) {
3245 + if (first_pin) {
3150 3246 if (!in_place) {
3151 3247 err = xe_bo_validate(bo, NULL, false, exec);
3152 3248 if (err)
@@ -3158,9 +3254,7 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec)
3158 3254 spin_unlock(&xe->pinned.lock);
3159 3255 }
3160 3256
3161 - ttm_bo_pin(&bo->ttm);
3162 - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3163 - xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
3257 + xe_bo_pin_account(bo);
3164 3258
3165 3259 /*
3166 3260 * FIXME: If we always use the reserve / unreserve functions for locking
@@ -3216,9 +3310,7 @@ int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec)
3216 3310 spin_unlock(&xe->pinned.lock);
3217 3311 }
3218 3312
3219 - ttm_bo_pin(&bo->ttm);
3220 - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3221 - xe_ttm_tt_account_subtract(xe, bo->ttm.ttm);
3313 + xe_bo_pin_account(bo);
3222 3314
3223 3315 /*
3224 3316 * FIXME: If we always use the reserve / unreserve functions for locking
@@ -3247,14 +3339,7 @@ void xe_bo_unpin_external(struct xe_bo *bo)
3247 3339 xe_assert(xe, xe_bo_is_pinned(bo));
3248 3340 xe_assert(xe, xe_bo_is_user(bo));
3249 3341
3250 - spin_lock(&xe->pinned.lock);
3251 - if (bo->ttm.pin_count == 1 && !list_empty(&bo->pinned_link))
3252 - list_del_init(&bo->pinned_link);
3253 - spin_unlock(&xe->pinned.lock);
3254 -
3255 - ttm_bo_unpin(&bo->ttm);
3256 - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3257 - xe_ttm_tt_account_add(xe, bo->ttm.ttm);
3342 + xe_bo_unpin_account(bo);
3258 3343
3259 3344 /*
3260 3345 * FIXME: If we always use the reserve / unreserve functions for locking
@@ -3272,21 +3357,16 @@ void xe_bo_unpin(struct xe_bo *bo)
3272 3357 xe_assert(xe, xe_bo_is_pinned(bo));
3273 3358
3274 3359 if (mem_type_is_vram(place->mem_type) || bo->flags & XE_BO_FLAG_GGTT) {
3275 - spin_lock(&xe->pinned.lock);
3276 3360 xe_assert(xe, !list_empty(&bo->pinned_link));
3277 - list_del_init(&bo->pinned_link);
3278 - spin_unlock(&xe->pinned.lock);
3279 3361
3280 3362 if (bo->backup_obj) {
3281 3363 if (xe_bo_is_pinned(bo->backup_obj))
3282 - ttm_bo_unpin(&bo->backup_obj->ttm);
3364 + xe_bo_unpin_account(bo->backup_obj);
3283 3365 xe_bo_put(bo->backup_obj);
3284 3366 bo->backup_obj = NULL;
3285 3367 }
3286 3368 }
3287 - ttm_bo_unpin(&bo->ttm);
3288 - if (bo->ttm.ttm && ttm_tt_is_populated(bo->ttm.ttm))
3289 - xe_ttm_tt_account_add(xe, bo->ttm.ttm);
3369 + xe_bo_unpin_account(bo);
3290 3370 }
3291 3371
3292 3372 /**
modified drivers/gpu/drm/xe/xe_bo.h
@@ -229,6 +229,8 @@ int xe_bo_pin_external(struct xe_bo *bo, bool in_place, struct drm_exec *exec);
229 229 int xe_bo_pin(struct xe_bo *bo, struct drm_exec *exec);
230 230 void xe_bo_unpin_external(struct xe_bo *bo);
231 231 void xe_bo_unpin(struct xe_bo *bo);
232 + void xe_bo_pin_account(struct xe_bo *bo);
233 + void xe_bo_unpin_account(struct xe_bo *bo);
232 234 int xe_bo_validate(struct xe_bo *bo, struct xe_vm *vm, bool allow_res_evict,
233 235 struct drm_exec *exec);
234 236
modified drivers/gpu/drm/xe/xe_exec.c
@@ -346,11 +346,8 @@ retry:
346 346 xe_sched_job_push(job);
347 347 xe_vm_reactivate_rebind(vm);
348 348
349 - if (!err && !xe_vm_in_lr_mode(vm)) {
350 - spin_lock(&xe->ttm.lru_lock);
351 - ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
352 - spin_unlock(&xe->ttm.lru_lock);
353 - }
349 + if (!err && !xe_vm_in_lr_mode(vm))
350 + xe_vm_bump_lru(vm, exec);
354 351
355 352 if (mode == EXEC_MODE_LR)
356 353 xe_hw_engine_group_resume_faulting_lr_jobs(group);
modified drivers/gpu/drm/xe/xe_i2c.c
@@ -324,12 +324,15 @@ static void xe_i2c_remove(void *data)
324 324 xe_i2c_irq_reset(xe);
325 325 xe_amc_exit(i2c);
326 326
327 + /* Stop the notifier from arming the client work before teardown. */
328 + bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier);
329 + cancel_work_sync(&i2c->work);
330 +
327 331 for (i = 0; i < XE_I2C_MAX_CLIENTS; i++) {
328 332 i2c_unregister_device(i2c->client[i]);
329 333 i2c->client[i] = NULL;
330 334 }
331 335
332 - bus_unregister_notifier(&i2c_bus_type, &i2c->bus_notifier);
333 336 xe_i2c_unregister_adapter(i2c);
334 337 xe->i2c = NULL;
335 338 }
modified drivers/gpu/drm/xe/xe_lrc.c
@@ -1099,8 +1099,7 @@ static void xe_lrc_finish(struct xe_lrc *lrc)
1099 1099 #define CONTEXT_ACTIVE XE_LRC_CTX_TIMESTAMP_ACTIVE
1100 1100 static ssize_t setup_utilization_wa(struct xe_lrc *lrc,
1101 1101 struct xe_hw_engine *hwe,
1102 - u32 *batch,
1103 - size_t max_len)
1102 + u32 *batch, size_t max_len, bool indirect)
1104 1103 {
1105 1104 u32 *cmd = batch;
1106 1105
@@ -1131,19 +1130,25 @@ static ssize_t setup_utilization_wa(struct xe_lrc *lrc,
1131 1130 }
1132 1131
1133 1132 static ssize_t setup_timestamp_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe,
1134 - u32 *batch, size_t max_len)
1133 + u32 *batch, size_t max_len, bool indirect)
1135 1134 {
1136 1135 const u32 ts_addr = __xe_lrc_ctx_timestamp_ggtt_addr(lrc);
1137 1136 u32 *cmd = batch;
1138 1137
1139 - if (!XE_GT_WA(lrc->gt, 16010904313) ||
1140 - !(hwe->class == XE_ENGINE_CLASS_RENDER ||
1141 - hwe->class == XE_ENGINE_CLASS_COMPUTE ||
1142 - hwe->class == XE_ENGINE_CLASS_COPY ||
1138 + if (!XE_GT_WA(lrc->gt, 16010904313))
1139 + return 0;
1140 +
1141 + if (!indirect &&
1142 + !(hwe->class == XE_ENGINE_CLASS_COPY ||
1143 1143 hwe->class == XE_ENGINE_CLASS_VIDEO_DECODE ||
1144 1144 hwe->class == XE_ENGINE_CLASS_VIDEO_ENHANCE))
1145 1145 return 0;
1146 1146
1147 + if (indirect &&
1148 + !(hwe->class == XE_ENGINE_CLASS_RENDER ||
1149 + hwe->class == XE_ENGINE_CLASS_COMPUTE))
1150 + return 0;
1151 +
1147 1152 if (xe_gt_WARN_ON(lrc->gt, max_len < 12))
1148 1153 return -ENOSPC;
1149 1154
@@ -1169,7 +1174,8 @@ static ssize_t setup_timestamp_wa(struct xe_lrc *lrc, struct xe_hw_engine *hwe,
1169 1174
1170 1175 static ssize_t setup_configfs_post_ctx_restore_bb(struct xe_lrc *lrc,
1171 1176 struct xe_hw_engine *hwe,
1172 - u32 *batch, size_t max_len)
1177 + u32 *batch, size_t max_len,
1178 + bool indirect)
1173 1179 {
1174 1180 struct xe_device *xe = gt_to_xe(lrc->gt);
1175 1181 const u32 *user_batch;
@@ -1198,7 +1204,8 @@ static ssize_t setup_configfs_post_ctx_restore_bb(struct xe_lrc *lrc,
1198 1204
1199 1205 static ssize_t setup_configfs_mid_ctx_restore_bb(struct xe_lrc *lrc,
1200 1206 struct xe_hw_engine *hwe,
1201 - u32 *batch, size_t max_len)
1207 + u32 *batch, size_t max_len,
1208 + bool indirect)
1202 1209 {
1203 1210 struct xe_device *xe = gt_to_xe(lrc->gt);
1204 1211 const u32 *user_batch;
@@ -1227,7 +1234,8 @@ static ssize_t setup_configfs_mid_ctx_restore_bb(struct xe_lrc *lrc,
1227 1234
1228 1235 static ssize_t setup_invalidate_state_cache_wa(struct xe_lrc *lrc,
1229 1236 struct xe_hw_engine *hwe,
1230 - u32 *batch, size_t max_len)
1237 + u32 *batch, size_t max_len,
1238 + bool indirect)
1231 1239 {
1232 1240 u32 *cmd = batch;
1233 1241
@@ -1247,7 +1255,8 @@ static ssize_t setup_invalidate_state_cache_wa(struct xe_lrc *lrc,
1247 1255
1248 1256 static ssize_t setup_invalidate_auxccs_wa(struct xe_lrc *lrc,
1249 1257 struct xe_hw_engine *hwe,
1250 - u32 *batch, size_t max_len)
1258 + u32 *batch, size_t max_len,
1259 + bool indirect)
1251 1260 {
1252 1261 struct xe_gt *gt = lrc->gt;
1253 1262 u32 *(*emit)(struct xe_gt *gt, u32 *cmd) =
@@ -1264,7 +1273,7 @@ static ssize_t setup_invalidate_auxccs_wa(struct xe_lrc *lrc,
1264 1273
1265 1274 struct bo_setup {
1266 1275 ssize_t (*setup)(struct xe_lrc *lrc, struct xe_hw_engine *hwe,
1267 - u32 *batch, size_t max_size);
1276 + u32 *batch, size_t max_size, bool indirect);
1268 1277 };
1269 1278
1270 1279 struct bo_setup_state {
@@ -1273,6 +1282,7 @@ struct bo_setup_state {
1273 1282 struct xe_hw_engine *hwe;
1274 1283 size_t max_size;
1275 1284 size_t reserve_dw;
1285 + bool indirect;
1276 1286 unsigned int offset;
1277 1287 const struct bo_setup *funcs;
1278 1288 unsigned int num_funcs;
@@ -1298,7 +1308,8 @@ static int setup_bo(struct bo_setup_state *state)
1298 1308
1299 1309 for (size_t i = 0; i < state->num_funcs; i++) {
1300 1310 ssize_t len = state->funcs[i].setup(state->lrc, state->hwe,
1301 - state->ptr, remain);
1311 + state->ptr, remain,
1312 + state->indirect);
1302 1313
1303 1314 remain -= len;
1304 1315
@@ -1404,6 +1415,7 @@ setup_indirect_ctx(struct xe_lrc *lrc, struct xe_hw_engine *hwe)
1404 1415 struct bo_setup_state state = {
1405 1416 .lrc = lrc,
1406 1417 .hwe = hwe,
1418 + .indirect = true,
1407 1419 .max_size = (63 * 64) /* max 63 cachelines */,
1408 1420 .buffer = NULL,
1409 1421 .offset = __xe_lrc_indirect_ctx_offset(lrc),
modified drivers/gpu/drm/xe/xe_mmio.c
@@ -320,6 +320,7 @@ u64 xe_mmio_read64_2x32(struct xe_mmio *mmio, struct xe_reg reg)
320 320 return (u64)udw << 32 | ldw;
321 321 }
322 322
323 + #define __XE_MMIO_WAIT_MAX_BACKOFF_100MS (100 * USEC_PER_MSEC)
323 324 static int __xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u32 val,
324 325 u32 timeout_us, u32 *out_val, bool atomic, bool expect_match)
325 326 {
@@ -350,10 +351,10 @@ static int __xe_mmio_wait32(struct xe_mmio *mmio, struct xe_reg reg, u32 mask, u
350 351 wait = ktime_us_delta(end, cur);
351 352
352 353 if (atomic)
353 - udelay(wait);
354 + udelay(min_t(s64, wait, (MAX_UDELAY_MS * 1000)));
354 355 else
355 356 usleep_range(wait, wait << 1);
356 - wait <<= 1;
357 + wait = min_t(s64, wait << 1, __XE_MMIO_WAIT_MAX_BACKOFF_100MS);
357 358 }
358 359
359 360 if (ret != 0) {
modified drivers/gpu/drm/xe/xe_oa.c
@@ -914,6 +914,13 @@ static int xe_oa_alloc_oa_buffer(struct xe_oa_stream *stream, size_t size)
914 914 if (IS_ERR(bo))
915 915 return PTR_ERR(bo);
916 916
917 + /*
918 + * ttm_bo_type_kernel BOs are not zeroed on allocation, so the buffer can
919 + * hold stale data from previously freed pages. Since the OA buffer is
920 + * mmap'able by userspace, clear it here to avoid leaking kernel memory.
921 + */
922 + xe_map_memset(stream->oa->xe, &bo->vmap, 0, 0, xe_bo_size(bo));
923 +
917 924 stream->oa_buffer.bo = bo;
918 925
919 926 stream->oa_buffer.bounce = kmalloc(stream->oa_buffer.format->size, GFP_KERNEL);
modified drivers/gpu/drm/xe/xe_sysctrl_mailbox.c
@@ -19,20 +19,20 @@
19 19 #include "xe_sysctrl_mailbox_types.h"
20 20
21 21 struct xe_sysctrl_mailbox_msg_hdr {
22 - __le32 data;
23 - } __packed;
22 + u32 data;
23 + };
24 24
25 25 #define XE_SYSCTRL_HDR_GROUP_ID(hdr) \
26 - FIELD_GET(SYSCTRL_HDR_GROUP_ID_MASK, le32_to_cpu((hdr)->data))
26 + FIELD_GET(SYSCTRL_HDR_GROUP_ID_MASK, (hdr)->data)
27 27
28 28 #define XE_SYSCTRL_HDR_COMMAND(hdr) \
29 - FIELD_GET(SYSCTRL_HDR_COMMAND_MASK, le32_to_cpu((hdr)->data))
29 + FIELD_GET(SYSCTRL_HDR_COMMAND_MASK, (hdr)->data)
30 30
31 31 #define XE_SYSCTRL_HDR_IS_RESPONSE(hdr) \
32 - FIELD_GET(SYSCTRL_HDR_IS_RESPONSE, le32_to_cpu((hdr)->data))
32 + FIELD_GET(SYSCTRL_HDR_IS_RESPONSE, (hdr)->data)
33 33
34 34 #define XE_SYSCTRL_HDR_RESULT(hdr) \
35 - FIELD_GET(SYSCTRL_HDR_RESULT_MASK, le32_to_cpu((hdr)->data))
35 + FIELD_GET(SYSCTRL_HDR_RESULT_MASK, (hdr)->data)
36 36
37 37 static bool sysctrl_wait_bit_clear(struct xe_sysctrl *sc, u32 bit_mask,
38 38 unsigned int timeout_ms)
@@ -126,8 +126,8 @@ static int sysctrl_prepare_command(struct xe_device *xe,
126 126 return -ENOMEM;
127 127
128 128 hdr = (struct xe_sysctrl_mailbox_msg_hdr *)buffer;
129 - hdr->data = cpu_to_le32(FIELD_PREP(SYSCTRL_HDR_GROUP_ID_MASK, group_id) |
130 - FIELD_PREP(SYSCTRL_HDR_COMMAND_MASK, command));
129 + hdr->data = FIELD_PREP(SYSCTRL_HDR_GROUP_ID_MASK, group_id) |
130 + FIELD_PREP(SYSCTRL_HDR_COMMAND_MASK, command);
131 131
132 132 if (data_in && data_in_len)
133 133 memcpy(buffer + sizeof(*hdr), data_in, data_in_len);
modified drivers/gpu/drm/xe/xe_vm.c
@@ -410,6 +410,33 @@ int xe_vm_validate_rebind(struct xe_vm *vm, struct drm_exec *exec,
410 410 return 0;
411 411 }
412 412
413 + /**
414 + * xe_vm_bump_lru() - Bump the LRU position of BOs used by a submission
415 + * @vm: The vm for which we are bumping LRUs.
416 + * @exec: The struct drm_exec with the locked GEM objects.
417 + *
418 + * Move the VM's private BOs, and all external objects locked by @exec,
419 + * to the LRU tail. Private BOs are moved in bulk using @vm's
420 + * &xe_vm.lru_bulk_move. External objects, which may be shared with other
421 + * VMs, are not part of that bulk move and are bumped individually.
422 + */
423 + void xe_vm_bump_lru(struct xe_vm *vm, struct drm_exec *exec)
424 + {
425 + spinlock_t *lru_lock = &vm->xe->ttm.lru_lock;
426 + struct drm_gem_object *obj;
427 +
428 + spin_lock(lru_lock);
429 + ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
430 + drm_exec_for_each_locked_object(exec, obj) {
431 + if (!drm_gpuvm_is_extobj(&vm->gpuvm, obj))
432 + continue;
433 +
434 + ttm_bo_move_to_lru_tail(&gem_to_xe_bo(obj)->ttm);
435 + cond_resched_lock(lru_lock);
436 + }
437 + spin_unlock(lru_lock);
438 + }
439 +
413 440 static int xe_preempt_work_begin(struct drm_exec *exec, struct xe_vm *vm,
414 441 bool *done)
415 442 {
@@ -560,9 +587,7 @@ retry:
560 587
561 588 #undef retry_required
562 589
563 - spin_lock(&vm->xe->ttm.lru_lock);
564 - ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
565 - spin_unlock(&vm->xe->ttm.lru_lock);
590 + xe_vm_bump_lru(vm, &exec);
566 591
567 592 /* Point of no return. */
568 593 arm_preempt_fences(vm, &preempt_fences);
modified drivers/gpu/drm/xe/xe_vm.h
@@ -284,6 +284,8 @@ int xe_vm_lock_vma(struct drm_exec *exec, struct xe_vma *vma);
284 284 int xe_vm_validate_rebind(struct xe_vm *vm, struct drm_exec *exec,
285 285 unsigned int num_fences);
286 286
287 + void xe_vm_bump_lru(struct xe_vm *vm, struct drm_exec *exec);
288 +
287 289 struct dma_fence *xe_vm_bind_kernel_bo(struct xe_vm *vm, struct xe_bo *bo,
288 290 struct xe_exec_queue *q, u64 addr,
289 291 enum xe_cache_level cache_lvl);
modified drivers/hv/channel.c
@@ -79,7 +79,7 @@ static inline u32 hv_ring_gpadl_send_hvpgoffset(u32 offset)
79 79 * therefore leaving a (PAGE_SIZE - HV_HYP_PAGE_SIZE) gap.
80 80 *
81 81 * And to calculate the effective send offset in gpadl, we need to
82 - * substract this gap.
82 + * subtract this gap.
83 83 */
84 84 return (offset - (PAGE_SIZE - HV_HYP_PAGE_SIZE)) >> HV_HYP_PAGE_SHIFT;
85 85 }
modified drivers/hv/channel_mgmt.c
@@ -752,13 +752,14 @@ static void init_vp_index(struct vmbus_channel *channel)
752 752 u32 i, ncpu = num_online_cpus();
753 753 cpumask_var_t available_mask;
754 754 struct cpumask *allocated_mask;
755 + const struct cpumask *node_mask;
755 756 const struct cpumask *hk_mask = housekeeping_cpumask(HK_TYPE_MANAGED_IRQ);
756 757 u32 target_cpu;
757 758 int numa_node;
758 759
759 760 if (!perf_chn ||
760 761 !alloc_cpumask_var(&available_mask, GFP_KERNEL) ||
761 - cpumask_empty(hk_mask)) {
762 + !cpumask_intersects(hk_mask, cpu_online_mask)) {
762 763 /*
763 764 * If the channel is not a performance critical
764 765 * channel, bind it to VMBUS_CONNECT_CPU.
@@ -780,14 +781,19 @@ static void init_vp_index(struct vmbus_channel *channel)
780 781 next_numa_node_id = 0;
781 782 continue;
782 783 }
783 - if (cpumask_empty(cpumask_of_node(numa_node)))
784 + /*
785 + * Try next NUMA node if current NUMA node has no CPU
786 + * or doesn't contain any housekeeping CPU.
787 + */
788 + node_mask = cpumask_of_node(numa_node);
789 + if (!cpumask_intersects(node_mask, hk_mask))
784 790 continue;
785 791 break;
786 792 }
787 793 allocated_mask = &hv_context.hv_numa_map[numa_node];
788 794
789 795 retry:
790 - cpumask_xor(available_mask, allocated_mask, cpumask_of_node(numa_node));
796 + cpumask_xor(available_mask, allocated_mask, node_mask);
791 797 cpumask_and(available_mask, available_mask, hk_mask);
792 798
793 799 if (cpumask_empty(available_mask)) {
modified drivers/hv/connection.c
@@ -346,7 +346,6 @@ int vmbus_connect(void)
346 346 cleanup:
347 347 pr_err("Unable to connect to host\n");
348 348
349 - vmbus_connection.conn_state = DISCONNECTED;
350 349 vmbus_disconnect();
351 350
352 351 kfree(msginfo);
modified drivers/hv/mshv_vtl_main.c
@@ -819,6 +819,9 @@ static vm_fault_t mshv_vtl_fault(struct vm_fault *vmf)
819 819 return VM_FAULT_NOPAGE;
820 820 }
821 821
822 + if (!page)
823 + return VM_FAULT_SIGBUS;
824 +
822 825 get_page(page);
823 826 vmf->page = page;
824 827
modified drivers/hv/vmbus_drv.c
@@ -2923,23 +2923,19 @@ static void hv_crash_handler(struct pt_regs *regs)
2923 2923 static int hv_synic_suspend(void *data)
2924 2924 {
2925 2925 /*
2926 - * When we reach here, all the non-boot CPUs have been offlined.
2927 - * If we're in a legacy configuration where stimer Direct Mode is
2928 - * not enabled, the stimers on the non-boot CPUs have been unbound
2929 - * in hv_synic_cleanup() -> hv_stimer_legacy_cleanup() ->
2930 - * hv_stimer_cleanup() -> clockevents_unbind_device().
2926 + * When we reach here, all the non-boot CPUs have been offlined,
2927 + * and their stimers have been cleaned up by the cpuhp teardown
2928 + * callback hv_stimer_cleanup().
2931 2929 *
2932 2930 * hv_synic_suspend() only runs on CPU0 with interrupts disabled.
2933 - * Here we do not call hv_stimer_legacy_cleanup() on CPU0 because:
2934 - * 1) it's unnecessary as interrupts remain disabled between
2935 - * syscore_suspend() and syscore_resume(): see create_image() and
2931 + * The stimer on CPU0 is not explicitly cleaned up here because:
2932 + * 1) it's harmless as interrupts remain disabled between
2933 + * syscore_suspend() and syscore_resume(), so the stimer cannot
2934 + * fire during this window: see create_image() and
2936 2935 * resume_target_kernel()
2937 2936 * 2) the stimer on CPU0 is automatically disabled later by
2938 2937 * syscore_suspend() -> timekeeping_suspend() -> tick_suspend() -> ...
2939 2938 * -> clockevents_shutdown() -> ... -> hv_ce_shutdown()
2940 - * 3) a warning would be triggered if we call
2941 - * clockevents_unbind_device(), which may sleep, in an
2942 - * interrupts-disabled context.
2943 2939 */
2944 2940
2945 2941 hv_hyp_synic_disable_regs(0);
@@ -3043,7 +3039,6 @@ static void __exit vmbus_exit(void)
3043 3039
3044 3040 hv_remove_kexec_handler();
3045 3041 hv_remove_crash_handler();
3046 - vmbus_connection.conn_state = DISCONNECTED;
3047 3042 hv_stimer_global_cleanup();
3048 3043 vmbus_disconnect();
3049 3044 if (vmbus_irq == -1)
modified drivers/i2c/busses/i2c-qcom-cci.c
@@ -164,12 +164,12 @@ static irqreturn_t cci_isr(int irq, void *dev)
164 164 }
165 165
166 166 if (unlikely(val & CCI_IRQ_STATUS_0_I2C_M0_Q0Q1_HALT_ACK)) {
167 - reset = CCI_RESET_CMD_M0_MASK;
167 + reset |= CCI_RESET_CMD_M0_MASK;
168 168 ret = IRQ_HANDLED;
169 169 }
170 170
171 171 if (unlikely(val & CCI_IRQ_STATUS_0_I2C_M1_Q0Q1_HALT_ACK)) {
172 - reset = CCI_RESET_CMD_M1_MASK;
172 + reset |= CCI_RESET_CMD_M1_MASK;
173 173 ret = IRQ_HANDLED;
174 174 }
175 175
modified drivers/i2c/busses/i2c-qcom-geni.c
@@ -201,28 +201,31 @@ static const struct geni_i2c_clk_fld geni_i2c_clk_map_32mhz[] = {
201 201 static int geni_i2c_clk_map_idx(struct geni_i2c_dev *gi2c)
202 202 {
203 203 const struct geni_i2c_clk_fld *itr;
204 - unsigned long res_freq;
204 + unsigned long req_freq, res_freq;
205 + int ret;
205 206
206 207 /*
207 - * Frequency counter tables are calibrated for a specific source
208 - * clock frequency and are not valid for any multiple of it
209 - * (e.g. 64 MHz, 128 MHz).
210 - * Use exact=true and verify res_freq matches req_freq literally
211 - * to reject harmonics: a 64 MHz clock that divides evenly to
212 - * 32 MHz would pass exact matching but produce double the intended
213 - * I2C frequency with these counter values.
208 + * Use 32 MHz only if already selected, otherwise use 19.2 MHz.
209 + * Preferring 32 MHz merely because DFS supports it breaks I2C
210 + * transfers on X1E80100 CRD.
214 211 */
215 - if (!geni_se_clk_freq_match(&gi2c->se, GENI_SE_CLK_32MHZ,
216 - &gi2c->clk_idx, &res_freq, true) &&
217 - res_freq == GENI_SE_CLK_32MHZ) {
212 + if (clk_get_rate(gi2c->se.clk) == GENI_SE_CLK_32MHZ) {
213 + req_freq = GENI_SE_CLK_32MHZ;
218 214 itr = geni_i2c_clk_map_32mhz;
219 - } else if (!geni_se_clk_freq_match(&gi2c->se, GENI_SE_CLK_19P2MHZ,
220 - &gi2c->clk_idx, &res_freq, true) &&
221 - res_freq == GENI_SE_CLK_19P2MHZ) {
222 - itr = geni_i2c_clk_map_19p2mhz;
223 215 } else {
224 - dev_err(gi2c->se.dev,
225 - "Unsupported SE source clock: must be exactly 32 MHz or 19.2 MHz\n");
216 + req_freq = GENI_SE_CLK_19P2MHZ;
217 + itr = geni_i2c_clk_map_19p2mhz;
218 + }
219 +
220 + ret = geni_se_clk_freq_match(&gi2c->se, req_freq, &gi2c->clk_idx,
221 + &res_freq, true);
222 + if (ret)
223 + return dev_err_probe(gi2c->se.dev, ret,
224 + "Failed to find SE source clock %lu Hz\n",
225 + req_freq);
226 + if (res_freq != req_freq) {
227 + dev_err(gi2c->se.dev, "Unsupported SE source clock %lu Hz\n",
228 + res_freq);
226 229 return -EINVAL;
227 230 }
228 231
@@ -1003,13 +1006,14 @@ static int geni_i2c_xfer(struct i2c_adapter *adap,
1003 1006
1004 1007 ret = gi2c->dev_data->set_rate(&gi2c->se, gi2c->clk_freq_out);
1005 1008 if (ret)
1006 - return ret;
1009 + goto out_pm;
1007 1010
1008 1011 if (gi2c->gpi_mode)
1009 1012 ret = geni_i2c_gpi_xfer(gi2c, msgs, num);
1010 1013 else
1011 1014 ret = geni_i2c_fifo_xfer(gi2c, msgs, num);
1012 1015
1016 + out_pm:
1013 1017 pm_runtime_put_autosuspend(gi2c->se.dev);
1014 1018 gi2c->cur = NULL;
1015 1019 gi2c->err = 0;
modified drivers/i2c/busses/i2c-viai2c-wmt.c
@@ -116,7 +116,7 @@ static int wmt_i2c_probe(struct platform_device *pdev)
116 116 if (err)
117 117 return err;
118 118
119 - i2c->clk = of_clk_get(np, 0);
119 + i2c->clk = devm_clk_get(&pdev->dev, NULL);
120 120 if (IS_ERR(i2c->clk))
121 121 return dev_err_probe(&pdev->dev, PTR_ERR(i2c->clk),
122 122 "unable to request clock\n");
modified drivers/i2c/busses/i2c-xiic.c
@@ -67,6 +67,7 @@ enum i2c_scl_freq {
67 67 * @rx_pos: Position within current RX message
68 68 * @endianness: big/little-endian byte order
69 69 * @clk: Pointer to AXI4-lite input clock
70 + * @irq: Interrupt number
70 71 * @state: See STATE_
71 72 * @singlemaster: Indicates bus is single master
72 73 * @dynamic: Mode of controller
@@ -95,6 +96,7 @@ struct xiic_i2c {
95 96 int rx_pos;
96 97 enum xiic_endian endianness;
97 98 struct clk *clk;
99 + int irq;
98 100 enum xilinx_i2c_state state;
99 101 bool singlemaster;
100 102 bool dynamic;
@@ -1506,9 +1508,17 @@ static int xiic_i2c_probe(struct platform_device *pdev)
1506 1508
1507 1509 pm_runtime_set_autosuspend_delay(dev, XIIC_PM_TIMEOUT);
1508 1510 pm_runtime_use_autosuspend(dev);
1509 - ret = devm_pm_runtime_set_active_enabled(dev);
1510 - if (ret)
1511 + /*
1512 + * Enable runtime PM by hand: devm_pm_runtime_set_active_enabled()
1513 + * tears down in an order that races the devm-enabled clock release and
1514 + * makes clk_core_disable() WARN (see xiic_i2c_remove()).
1515 + */
1516 + ret = pm_runtime_set_active(dev);
1517 + if (ret) {
1518 + pm_runtime_dont_use_autosuspend(dev);
1511 1519 return ret;
1520 + }
1521 + pm_runtime_enable(dev);
1512 1522
1513 1523 /* SCL frequency configuration */
1514 1524 i2c->input_clk = clk_get_rate(i2c->clk);
@@ -1517,10 +1527,15 @@ static int xiic_i2c_probe(struct platform_device *pdev)
1517 1527 if (ret || i2c->i2c_clk > I2C_MAX_FAST_MODE_PLUS_FREQ)
1518 1528 i2c->i2c_clk = 0;
1519 1529
1520 - ret = devm_request_threaded_irq(dev, irq, NULL, xiic_process,
1521 - IRQF_ONESHOT, pdev->name, i2c);
1530 + /*
1531 + * Request the IRQ non-managed: later probe steps unwind manually via
1532 + * goto, so a devm handler could still be live after that teardown runs.
1533 + */
1534 + i2c->irq = irq;
1535 + ret = request_threaded_irq(irq, NULL, xiic_process, IRQF_ONESHOT,
1536 + pdev->name, i2c);
1522 1537 if (ret)
1523 - return ret;
1538 + goto err_pm_disable;
1524 1539
1525 1540 i2c->singlemaster = device_property_read_bool(dev, "single-master");
1526 1541
@@ -1537,14 +1552,16 @@ static int xiic_i2c_probe(struct platform_device *pdev)
1537 1552 i2c->endianness = BIG;
1538 1553
1539 1554 ret = xiic_reinit(i2c);
1540 - if (ret)
1541 - return dev_err_probe(dev, ret, "Cannot xiic_reinit\n");
1555 + if (ret) {
1556 + dev_err_probe(dev, ret, "Cannot xiic_reinit\n");
1557 + goto err_free_irq;
1558 + }
1542 1559
1543 1560 /* add i2c adapter to i2c tree */
1544 1561 ret = i2c_add_numbered_adapter(&i2c->adap);
1545 1562 if (ret) {
1546 1563 xiic_deinit(i2c);
1547 - return ret;
1564 + goto err_free_irq;
1548 1565 }
1549 1566
1550 1567 if (pdata) {
@@ -1557,6 +1574,15 @@ static int xiic_i2c_probe(struct platform_device *pdev)
1557 1574 res, irq, i2c->i2c_clk);
1558 1575
1559 1576 return 0;
1577 +
1578 + err_free_irq:
1579 + free_irq(irq, i2c);
1580 + err_pm_disable:
1581 + pm_runtime_disable(dev);
1582 + pm_runtime_set_suspended(dev);
1583 + pm_runtime_dont_use_autosuspend(dev);
1584 +
1585 + return ret;
1560 1586 }
1561 1587
1562 1588 static void xiic_i2c_remove(struct platform_device *pdev)
@@ -1568,6 +1594,8 @@ static void xiic_i2c_remove(struct platform_device *pdev)
1568 1594 /* remove adapter & data */
1569 1595 i2c_del_adapter(&i2c->adap);
1570 1596
1597 + free_irq(i2c->irq, i2c);
1598 +
1571 1599 ret = pm_runtime_get_sync(dev);
1572 1600 if (ret < 0)
1573 1601 dev_warn(dev, "Failed to activate device for removal (%pe)\n",
@@ -1575,7 +1603,10 @@ static void xiic_i2c_remove(struct platform_device *pdev)
1575 1603 else
1576 1604 xiic_deinit(i2c);
1577 1605
1578 - pm_runtime_put_sync(dev);
1606 + pm_runtime_disable(dev);
1607 + pm_runtime_put_noidle(dev);
1608 + pm_runtime_set_suspended(dev);
1609 + pm_runtime_dont_use_autosuspend(dev);
1579 1610 }
1580 1611
1581 1612 static const struct dev_pm_ops xiic_dev_pm_ops = {
modified drivers/input/joystick/xpad.c
@@ -302,6 +302,8 @@ static const struct xpad_device {
302 302 { 0x17ef, 0x6182, "Lenovo Legion Controller for Windows", 0, XTYPE_XBOX360 },
303 303 { 0x1949, 0x041a, "Amazon Game Controller", 0, XTYPE_XBOX360 },
304 304 { 0x1a86, 0xe310, "Legion Go S", 0, XTYPE_XBOX360 },
305 + { 0x1b1c, 0x2b1f, "Corsair Novablade Pro (Wired)", 0, XTYPE_XBOX360 },
306 + { 0x1b1c, 0x2b2b, "Corsair Novablade Pro (2.4 GHz Receiver)", 0, XTYPE_XBOX360 },
305 307 { 0x1bad, 0x0002, "Harmonix Rock Band Guitar", 0, XTYPE_XBOX360 },
306 308 { 0x1bad, 0x0003, "Harmonix Rock Band Drumkit", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
307 309 { 0x1bad, 0x0130, "Ion Drum Rocker", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
@@ -379,6 +381,7 @@ static const struct xpad_device {
379 381 { 0x2993, 0x2001, "TECNO Pocket Go", 0, XTYPE_XBOX360 },
380 382 { 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE },
381 383 { 0x2dc8, 0x200f, "8BitDo Ultimate 3-mode Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE },
384 + { 0x2dc8, 0x201e, "8BitDo Pro 2 Wired Controller for Xbox", MAP_SHARE_BUTTON, XTYPE_XBOXONE },
382 385 { 0x2dc8, 0x3106, "8BitDo Ultimate Wireless / Pro 2 Wired Controller", 0, XTYPE_XBOX360 },
383 386 { 0x2dc8, 0x3109, "8BitDo Ultimate Wireless Bluetooth", 0, XTYPE_XBOX360 },
384 387 { 0x2dc8, 0x310a, "8BitDo Ultimate 2C Wireless Controller", 0, XTYPE_XBOX360 },
@@ -545,6 +548,7 @@ static const struct usb_device_id xpad_table[] = {
545 548 XPAD_XBOX360_VENDOR(0x17ef), /* Lenovo */
546 549 XPAD_XBOX360_VENDOR(0x1949), /* Amazon controllers */
547 550 XPAD_XBOX360_VENDOR(0x1a86), /* Nanjing Qinheng Microelectronics (WCH) */
551 + XPAD_XBOX360_VENDOR(0x1b1c), /* Corsair controllers */
548 552 XPAD_XBOX360_VENDOR(0x1bad), /* Harmonix Rock Band guitar and drums */
549 553 XPAD_XBOX360_VENDOR(0x1ee9), /* ZOTAC Technology Limited */
550 554 XPAD_XBOX360_VENDOR(0x20bc), /* BETOP wireless dongles */
modified drivers/input/misc/ati_remote2.c
@@ -672,8 +672,7 @@ static ssize_t ati_remote2_show_channel_mask(struct device *dev,
672 672 struct device_attribute *attr,
673 673 char *buf)
674 674 {
675 - struct usb_device *udev = to_usb_device(dev);
676 - struct usb_interface *intf = usb_ifnum_to_if(udev, 0);
675 + struct usb_interface *intf = to_usb_interface(dev);
677 676 struct ati_remote2 *ar2 = usb_get_intfdata(intf);
678 677
679 678 return sprintf(buf, "0x%04x\n", ar2->channel_mask);
@@ -683,8 +682,7 @@ static ssize_t ati_remote2_store_channel_mask(struct device *dev,
683 682 struct device_attribute *attr,
684 683 const char *buf, size_t count)
685 684 {
686 - struct usb_device *udev = to_usb_device(dev);
687 - struct usb_interface *intf = usb_ifnum_to_if(udev, 0);
685 + struct usb_interface *intf = to_usb_interface(dev);
688 686 struct ati_remote2 *ar2 = usb_get_intfdata(intf);
689 687 unsigned int mask;
690 688 int r;
@@ -720,8 +718,7 @@ static ssize_t ati_remote2_show_mode_mask(struct device *dev,
720 718 struct device_attribute *attr,
721 719 char *buf)
722 720 {
723 - struct usb_device *udev = to_usb_device(dev);
724 - struct usb_interface *intf = usb_ifnum_to_if(udev, 0);
721 + struct usb_interface *intf = to_usb_interface(dev);
725 722 struct ati_remote2 *ar2 = usb_get_intfdata(intf);
726 723
727 724 return sprintf(buf, "0x%02x\n", ar2->mode_mask);
@@ -731,8 +728,7 @@ static ssize_t ati_remote2_store_mode_mask(struct device *dev,
731 728 struct device_attribute *attr,
732 729 const char *buf, size_t count)
733 730 {
734 - struct usb_device *udev = to_usb_device(dev);
735 - struct usb_interface *intf = usb_ifnum_to_if(udev, 0);
731 + struct usb_interface *intf = to_usb_interface(dev);
736 732 struct ati_remote2 *ar2 = usb_get_intfdata(intf);
737 733 unsigned int mask;
738 734 int err;
modified drivers/iommu/amd/amd_iommu_types.h
@@ -421,6 +421,9 @@ struct irq_remap_table {
421 421 u32 *table;
422 422 };
423 423
424 + /* Interrupt remapping feature used? */
425 + extern bool amd_iommu_irq_remap;
426 +
424 427 extern const struct iommu_ops amd_iommu_ops;
425 428
426 429 /* IVRS indicates that pre-boot remapping was enabled */
modified drivers/iommu/amd/init.c
@@ -152,7 +152,7 @@ struct ivmd_header {
152 152 } __attribute__((packed));
153 153
154 154 bool amd_iommu_dump;
155 - static bool amd_iommu_irq_remap __read_mostly;
155 + bool amd_iommu_irq_remap __read_mostly;
156 156
157 157 enum protection_domain_mode amd_iommu_pgtable = PD_MODE_V1;
158 158 /* Virtual address size */
modified drivers/iommu/amd/iommu.c
@@ -3973,6 +3973,9 @@ static int irq_remapping_select(struct irq_domain *d, struct irq_fwspec *fwspec,
3973 3973 struct amd_iommu *iommu;
3974 3974 int devid = -1;
3975 3975
3976 + if (!amd_iommu_irq_remap)
3977 + return 0;
3978 +
3976 3979 if (x86_fwspec_is_ioapic(fwspec))
3977 3980 devid = get_ioapic_devid(fwspec->param[0]);
3978 3981 else if (x86_fwspec_is_hpet(fwspec))
modified drivers/iommu/dma-iommu.c
@@ -1228,9 +1228,9 @@ dma_addr_t iommu_dma_map_phys(struct device *dev, phys_addr_t phys, size_t size,
1228 1228 * If both the physical buffer start address and size are page aligned,
1229 1229 * we don't need to use a bounce page.
1230 1230 */
1231 - if (dev_use_swiotlb(dev, size, dir) &&
1231 + if (!(attrs & DMA_ATTR_MMIO) && dev_use_swiotlb(dev, size, dir) &&
1232 1232 iova_unaligned(iovad, phys, size)) {
1233 - if (attrs & (DMA_ATTR_MMIO | DMA_ATTR_REQUIRE_COHERENT))
1233 + if (attrs & DMA_ATTR_REQUIRE_COHERENT)
1234 1234 return DMA_MAPPING_ERROR;
1235 1235
1236 1236 phys = iommu_dma_map_swiotlb(dev, phys, size, dir, attrs);
modified drivers/iommu/generic_pt/fmt/Makefile
@@ -25,6 +25,6 @@ $(eval $(foreach fmt,$(iommu_pt_fmt-m),$(call create_format,$(fmt),m)))
25 25 # with -DGENERIC_PT_KUNIT
26 26 $(obj)/kunit_iommu_%.o: $(src)/iommu_%.c FORCE
27 27 $(call rule_mkdir)
28 - $(call if_changed_dep,cc_o_c)
28 + $(call if_changed_rule,cc_o_c)
29 29
30 30 obj-$(CONFIG_IOMMU_PT_KUNIT_TEST) += $(IOMMU_PT_KUNIT_TEST)
modified drivers/md/dm-crypt.c
@@ -2894,8 +2894,13 @@ static int crypt_ctr_cipher_new(struct dm_target *ti, char *cipher_in, char *key
2894 2894 }
2895 2895 }
2896 2896
2897 - if (*ivmode && !strcmp(*ivmode, "lmk"))
2897 + if (*ivmode && !strcmp(*ivmode, "lmk")) {
2898 + if (crypt_integrity_aead(cc)) {
2899 + ti->error = "AEAD transforms not supported for LMK";
2900 + return -EINVAL;
2901 + }
2898 2902 cc->tfms_count = 64;
2903 + }
2899 2904
2900 2905 if (*ivmode && !strcmp(*ivmode, "essiv")) {
2901 2906 if (!*ivopts) {
modified drivers/md/dm-integrity.c
@@ -180,6 +180,7 @@ struct dm_integrity_c {
180 180 struct dm_bufio_client *bufio;
181 181 struct workqueue_struct *metadata_wq;
182 182 struct superblock *sb;
183 + struct superblock *sb_copy;
183 184 unsigned int journal_pages;
184 185 unsigned int n_bitmap_blocks;
185 186
@@ -2721,7 +2722,7 @@ static void dm_integrity_inline_recheck(struct work_struct *w)
2721 2722 outgoing_data = dio->integrity_payload + PAGE_SIZE;
2722 2723
2723 2724 while (dio->bio_details.bi_iter.bi_size) {
2724 - char digest[HASH_MAX_DIGESTSIZE];
2725 + char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2725 2726 int r;
2726 2727 struct bio_integrity_payload *bip;
2727 2728 struct bio_vec bv;
@@ -2788,7 +2789,7 @@ static inline bool dm_integrity_check(struct dm_integrity_c *ic, struct dm_integ
2788 2789 unsigned pos = 0;
2789 2790
2790 2791 while (dio->bio_details.bi_iter.bi_size) {
2791 - char digest[HASH_MAX_DIGESTSIZE];
2792 + char digest[MAX_T(size_t, HASH_MAX_DIGESTSIZE, MAX_TAG_SIZE)];
2792 2793 struct bio_vec bv = bio_iter_iovec(bio, dio->bio_details.bi_iter);
2793 2794 char *mem = integrity_kmap(ic, bv.bv_page);
2794 2795 integrity_sector_checksum(ic, &dio->ahash_req, dio->bio_details.bi_iter.bi_sector, mem, bv.bv_offset, digest);
@@ -3858,6 +3859,35 @@ static void dm_integrity_postsuspend(struct dm_target *ti)
3858 3859 ic->journal_uptodate = true;
3859 3860 }
3860 3861
3862 + /*
3863 + * The superblock is re-read from the device on every resume, so that we pick
3864 + * up the flags and the recalculate position. The geometry described by the
3865 + * superblock must not change though - the in-memory structures (and the
3866 + * journal in particular) were sized according to the superblock that was
3867 + * validated in the constructor. Reject a superblock that was modified behind
3868 + * our back.
3869 + *
3870 + * Only the fields that the driver never rewrites may be tested here. In
3871 + * particular, "version" is recalculated by sb_set_version on every superblock
3872 + * write and it depends on SB_FLAG_RECALCULATING and SB_FLAG_DIRTY_BITMAP, and
3873 + * SB_FLAG_DISCARD_KEYED may be set by dm_integrity_resume itself.
3874 + */
3875 + static bool superblock_changed(struct dm_integrity_c *ic)
3876 + {
3877 + const __le32 immutable_flags = cpu_to_le32(SB_FLAG_HAVE_JOURNAL_MAC |
3878 + SB_FLAG_FIXED_PADDING |
3879 + SB_FLAG_FIXED_HMAC |
3880 + SB_FLAG_INLINE);
3881 +
3882 + return memcmp(ic->sb->magic, ic->sb_copy->magic, sizeof(ic->sb->magic)) != 0 ||
3883 + ic->sb->log2_interleave_sectors != ic->sb_copy->log2_interleave_sectors ||
3884 + ic->sb->integrity_tag_size != ic->sb_copy->integrity_tag_size ||
3885 + ic->sb->journal_sections != ic->sb_copy->journal_sections ||
3886 + ic->sb->log2_sectors_per_block != ic->sb_copy->log2_sectors_per_block ||
3887 + ((ic->sb->flags ^ ic->sb_copy->flags) & immutable_flags) != 0 ||
3888 + memcmp(ic->sb->salt, ic->sb_copy->salt, SALT_SIZE) != 0;
3889 + }
3890 +
3861 3891 static void dm_integrity_resume(struct dm_target *ti)
3862 3892 {
3863 3893 struct dm_integrity_c *ic = ti->private;
@@ -3876,6 +3906,18 @@ static void dm_integrity_resume(struct dm_target *ti)
3876 3906 if (r)
3877 3907 dm_integrity_io_error(ic, "reading superblock", r);
3878 3908
3909 + if (unlikely(superblock_changed(ic))) {
3910 + /*
3911 + * Restore the superblock that we validated in the constructor,
3912 + * so that the rest of the driver doesn't operate on values
3913 + * that don't match the in-memory structures.
3914 + */
3915 + memcpy(ic->sb, ic->sb_copy, sizeof(struct superblock));
3916 + DMERR("The superblock was changed while the device was suspended");
3917 + dm_integrity_io_error(ic, "superblock check", -EINVAL);
3918 + goto skip_writes;
3919 + }
3920 +
3879 3921 if (ic->mode == 'R')
3880 3922 goto skip_writes;
3881 3923
@@ -5427,6 +5469,13 @@ try_smaller_buffer:
5427 5469 ic->just_formatted = true;
5428 5470 }
5429 5471
5472 + ic->sb_copy = kmemdup(ic->sb, sizeof(struct superblock), GFP_KERNEL);
5473 + if (!ic->sb_copy) {
5474 + ti->error = "Cannot allocate superblock copy";
5475 + r = -ENOMEM;
5476 + goto bad;
5477 + }
5478 +
5430 5479 if (!ic->meta_dev && ic->mode != 'I') {
5431 5480 r = dm_set_target_max_io_len(ti, 1U << ic->sb->log2_interleave_sectors);
5432 5481 if (r)
@@ -5525,6 +5574,7 @@ static void dm_integrity_dtr(struct dm_target *ti)
5525 5574 kvfree(ic->journal_tree);
5526 5575 if (ic->sb)
5527 5576 free_pages_exact(ic->sb, SB_SECTORS << SECTOR_SHIFT);
5577 + kfree(ic->sb_copy);
5528 5578
5529 5579 if (ic->internal_shash)
5530 5580 crypto_free_shash(ic->internal_shash);
modified drivers/md/dm-ioctl.c
@@ -656,10 +656,16 @@ static void *get_result_buffer(struct dm_ioctl *param, size_t param_size,
656 656 {
657 657 param->data_start = align_ptr(param + 1) - (void *) param;
658 658
659 - if (param->data_start < param_size)
659 + if (param->data_start < param_size) {
660 660 *len = param_size - param->data_start;
661 - else
661 + } else {
662 + /*
663 + * The buffer can be as small as offsetof(*param, data), which
664 + * is less than sizeof(*param), so don't run off the end of it.
665 + */
662 666 *len = 0;
667 + param->data_start = param_size;
668 + }
663 669
664 670 return ((void *) param) + param->data_start;
665 671 }
@@ -1267,6 +1273,7 @@ static int do_resume(struct dm_ioctl *param)
1267 1273 /* Do we need to load a new map ? */
1268 1274 if (new_map) {
1269 1275 sector_t old_size, new_size;
1276 + blk_mode_t new_map_mode;
1270 1277
1271 1278 dm_ima_context_table_op(md, ima_context, DM_IMA_TABLE_SAVE);
1272 1279 /* Suspend if it isn't already suspended */
@@ -1299,6 +1306,7 @@ static int do_resume(struct dm_ioctl *param)
1299 1306 }
1300 1307 }
1301 1308
1309 + new_map_mode = dm_table_get_mode(new_map);
1302 1310 old_size = dm_get_size(md);
1303 1311 old_map = dm_swap_table(md, new_map);
1304 1312 if (IS_ERR(old_map)) {
@@ -1314,7 +1322,7 @@ static int do_resume(struct dm_ioctl *param)
1314 1322 if (old_size && new_size && old_size != new_size)
1315 1323 need_resize_uevent = true;
1316 1324
1317 - if (dm_table_get_mode(new_map) & BLK_OPEN_WRITE)
1325 + if (new_map_mode & BLK_OPEN_WRITE)
1318 1326 set_disk_ro(dm_disk(md), 0);
1319 1327 else
1320 1328 set_disk_ro(dm_disk(md), 1);
modified drivers/md/dm-snap.c
@@ -1292,6 +1292,20 @@ static int snapshot_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1292 1292 goto bad_store;
1293 1293 }
1294 1294
1295 + /*
1296 + * snapshot-merge requires the optional prepare_merge/commit_merge
1297 + * callbacks; the transient exception store does not implement them.
1298 + * The handover path checks this in __validate_exception_handover(),
1299 + * but a directly constructed snapshot-merge never goes through it.
1300 + */
1301 + if (dm_target_is_snapshot_merge(ti) &&
1302 + (!s->store->type->prepare_merge ||
1303 + !s->store->type->commit_merge)) {
1304 + ti->error = "Snapshot exception store does not support snapshot-merge.";
1305 + r = -EINVAL;
1306 + goto bad_hash_tables;
1307 + }
1308 +
1295 1309 argv += args_used;
1296 1310 argc -= args_used;
1297 1311
modified drivers/media/usb/em28xx/em28xx-video.c
@@ -2416,7 +2416,7 @@ static int em28xx_v4l2_fini(struct em28xx *dev)
2416 2416 if (video_is_registered(&v4l2->radio_dev)) {
2417 2417 dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
2418 2418 video_device_node_name(&v4l2->radio_dev));
2419 - vb2_video_unregister_device(&v4l2->radio_dev);
2419 + video_unregister_device(&v4l2->radio_dev);
2420 2420 }
2421 2421 if (video_is_registered(&v4l2->vbi_dev)) {
2422 2422 dev_info(&dev->intf->dev, "V4L2 device %s deregistered\n",
@@ -3082,7 +3082,7 @@ unregister_dev:
3082 3082 dev_info(&dev->intf->dev,
3083 3083 "V4L2 device %s deregistered\n",
3084 3084 video_device_node_name(&v4l2->radio_dev));
3085 - vb2_video_unregister_device(&v4l2->radio_dev);
3085 + video_unregister_device(&v4l2->radio_dev);
3086 3086 }
3087 3087 if (video_is_registered(&v4l2->vbi_dev)) {
3088 3088 dev_info(&dev->intf->dev,
modified drivers/memstick/core/memstick.c
@@ -370,9 +370,7 @@ int memstick_set_rw_addr(struct memstick_dev *card)
370 370 {
371 371 card->next_request = h_memstick_set_rw_addr;
372 372 memstick_new_req(card->host);
373 - if (!wait_for_completion_timeout(&card->mrq_complete,
374 - msecs_to_jiffies(500)))
375 - card->current_mrq.error = -ETIMEDOUT;
373 + wait_for_completion(&card->mrq_complete);
376 374
377 375 return card->current_mrq.error;
378 376 }
@@ -405,9 +403,7 @@ static struct memstick_dev *memstick_alloc_card(struct memstick_host *host)
405 403
406 404 card->next_request = h_memstick_read_dev_id;
407 405 memstick_new_req(host);
408 - if (!wait_for_completion_timeout(&card->mrq_complete,
409 - msecs_to_jiffies(500)))
410 - card->current_mrq.error = -ETIMEDOUT;
406 + wait_for_completion(&card->mrq_complete);
411 407
412 408 if (card->current_mrq.error)
413 409 goto err_out;
modified drivers/memstick/host/rtsx_usb_ms.c
@@ -27,7 +27,6 @@ struct rtsx_usb_ms {
27 27 struct memstick_host *msh;
28 28 struct memstick_request *req;
29 29
30 - struct mutex host_mutex;
31 30 struct work_struct handle_req;
32 31 struct delayed_work poll_card;
33 32
@@ -514,6 +513,13 @@ static void rtsx_usb_ms_handle_req(struct work_struct *work)
514 513 struct memstick_host *msh = host->msh;
515 514 int rc;
516 515
516 + /* Fail requests after eject so their waiters are released. */
517 + if (host->eject) {
518 + while (!memstick_next_req(msh, &host->req))
519 + host->req->error = -ENOMEDIUM;
520 + return;
521 + }
522 +
517 523 if (!host->req) {
518 524 pm_runtime_get_sync(ms_dev(host));
519 525 do {
@@ -547,8 +553,7 @@ static void rtsx_usb_ms_request(struct memstick_host *msh)
547 553
548 554 dev_dbg(ms_dev(host), "--> %s\n", __func__);
549 555
550 - if (!host->eject)
551 - schedule_work(&host->handle_req);
556 + schedule_work(&host->handle_req);
552 557 }
553 558
554 559 static int rtsx_usb_ms_set_param(struct memstick_host *msh,
@@ -781,7 +786,6 @@ static int rtsx_usb_ms_drv_probe(struct platform_device *pdev)
781 786 host->power_mode = MEMSTICK_POWER_OFF;
782 787 platform_set_drvdata(pdev, host);
783 788
784 - mutex_init(&host->host_mutex);
785 789 INIT_WORK(&host->handle_req, rtsx_usb_ms_handle_req);
786 790
787 791 INIT_DELAYED_WORK(&host->poll_card, rtsx_usb_ms_poll_card);
@@ -812,27 +816,12 @@ static void rtsx_usb_ms_drv_remove(struct platform_device *pdev)
812 816 {
813 817 struct rtsx_usb_ms *host = platform_get_drvdata(pdev);
814 818 struct memstick_host *msh = host->msh;
815 - int err;
816 819
817 820 host->eject = true;
818 821 msh->removing = true;
819 - cancel_work_sync(&host->handle_req);
822 + flush_work(&host->handle_req);
820 823 cancel_delayed_work_sync(&host->poll_card);
821 824
822 - mutex_lock(&host->host_mutex);
823 - if (host->req) {
824 - dev_dbg(ms_dev(host),
825 - "%s: Controller removed during transfer\n",
826 - dev_name(&msh->dev));
827 - host->req->error = -ENOMEDIUM;
828 - do {
829 - err = memstick_next_req(msh, &host->req);
830 - if (!err)
831 - host->req->error = -ENOMEDIUM;
832 - } while (!err);
833 - }
834 - mutex_unlock(&host->host_mutex);
835 -
836 825 /* Balance possible unbalanced usage count
837 826 * e.g. unconditional module removal
838 827 */
@@ -841,6 +830,8 @@ static void rtsx_usb_ms_drv_remove(struct platform_device *pdev)
841 830
842 831 pm_runtime_disable(ms_dev(host));
843 832 memstick_remove_host(msh);
833 + /* No card, no new requests; wait for the last failed one to finish. */
834 + cancel_work_sync(&host->handle_req);
844 835 dev_dbg(ms_dev(host),
845 836 ": Realtek USB Memstick controller has been removed\n");
846 837 memstick_free_host(msh);
modified drivers/mmc/host/cavium-octeon.c
@@ -295,9 +295,12 @@ static void octeon_mmc_remove(struct platform_device *pdev)
295 295 u64 dma_cfg;
296 296 int i;
297 297
298 - for (i = 0; i < CAVIUM_MAX_MMC; i++)
298 + for (i = 0; i < CAVIUM_MAX_MMC; i++) {
299 299 if (host->slot[i])
300 300 cvm_mmc_of_slot_remove(host->slot[i]);
301 + if (host->slot_pdev[i])
302 + of_platform_device_destroy(&host->slot_pdev[i]->dev, NULL);
303 + }
301 304
302 305 dma_cfg = readq(host->dma_base + MIO_EMM_DMA_CFG(host));
303 306 dma_cfg &= ~MIO_EMM_DMA_CFG_EN;
modified drivers/mmc/host/cavium-thunderx.c
@@ -173,9 +173,12 @@ static void thunder_mmc_remove(struct pci_dev *pdev)
173 173 u64 dma_cfg;
174 174 int i;
175 175
176 - for (i = 0; i < CAVIUM_MAX_MMC; i++)
176 + for (i = 0; i < CAVIUM_MAX_MMC; i++) {
177 177 if (host->slot[i])
178 178 cvm_mmc_of_slot_remove(host->slot[i]);
179 + if (host->slot_pdev[i])
180 + of_platform_device_destroy(&host->slot_pdev[i]->dev, NULL);
181 + }
179 182
180 183 dma_cfg = readq(host->dma_base + MIO_EMM_DMA_CFG(host));
181 184 dma_cfg &= ~MIO_EMM_DMA_CFG_EN;
modified drivers/mmc/host/mtk-sd.c
@@ -3216,6 +3216,7 @@ static void msdc_drv_remove(struct platform_device *pdev)
3216 3216
3217 3217 platform_set_drvdata(pdev, NULL);
3218 3218 mmc_remove_host(mmc);
3219 + cancel_delayed_work_sync(&host->req_timeout);
3219 3220 msdc_deinit_hw(host);
3220 3221 msdc_gate_clock(host);
3221 3222
modified drivers/mmc/host/sdhci-sprd.c
@@ -890,6 +890,10 @@ static void sdhci_sprd_remove(struct platform_device *pdev)
890 890 struct sdhci_host *host = platform_get_drvdata(pdev);
891 891 struct sdhci_sprd_host *sprd_host = TO_SPRD_HOST(host);
892 892
893 + pm_runtime_get_sync(&pdev->dev);
894 + pm_runtime_disable(&pdev->dev);
895 + pm_runtime_put_noidle(&pdev->dev);
896 +
893 897 sdhci_remove_host(host, 0);
894 898
895 899 clk_disable_unprepare(sprd_host->clk_sdio);
modified drivers/net/amt.c
@@ -80,15 +80,6 @@ static struct in6_addr mld2_all_node = MLD2_ALL_NODE_INIT;
80 80 static struct mld2_grec mldv2_zero_grec;
81 81 #endif
82 82
83 - static struct amt_skb_cb *amt_skb_cb(struct sk_buff *skb)
84 - {
85 - BUILD_BUG_ON(sizeof(struct amt_skb_cb) + sizeof(struct tc_skb_cb) >
86 - sizeof_field(struct sk_buff, cb));
87 -
88 - return (struct amt_skb_cb *)((void *)skb->cb +
89 - sizeof(struct tc_skb_cb));
90 - }
91 -
92 83 static void __amt_source_gc_work(void)
93 84 {
94 85 struct amt_source_node *snode;
@@ -791,6 +782,11 @@ out:
791 782 rcu_read_unlock();
792 783 }
793 784
785 + static bool amt_send_membership_query(struct amt_dev *amt,
786 + struct sk_buff *skb,
787 + struct amt_tunnel_list *tunnel,
788 + bool v6);
789 +
794 790 static void amt_send_igmp_gq(struct amt_dev *amt,
795 791 struct amt_tunnel_list *tunnel)
796 792 {
@@ -800,8 +796,11 @@ static void amt_send_igmp_gq(struct amt_dev *amt,
800 796 if (!skb)
801 797 return;
802 798
803 - amt_skb_cb(skb)->tunnel = tunnel;
804 - dev_queue_xmit(skb);
799 + skb_pull(skb, sizeof(struct ethhdr));
800 + if (amt_send_membership_query(amt, skb, tunnel, false)) {
801 + amt->dev->stats.tx_dropped++;
802 + kfree_skb(skb);
803 + }
805 804 }
806 805
807 806 #if IS_ENABLED(CONFIG_IPV6)
@@ -885,8 +884,11 @@ static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel)
885 884 if (!skb)
886 885 return;
887 886
888 - amt_skb_cb(skb)->tunnel = tunnel;
889 - dev_queue_xmit(skb);
887 + skb_pull(skb, sizeof(struct ethhdr));
888 + if (amt_send_membership_query(amt, skb, tunnel, true)) {
889 + amt->dev->stats.tx_dropped++;
890 + kfree_skb(skb);
891 + }
890 892 }
891 893 #else
892 894 static void amt_send_mld_gq(struct amt_dev *amt, struct amt_tunnel_list *tunnel)
@@ -1186,7 +1188,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev)
1186 1188 #endif
1187 1189 bool report = false;
1188 1190 struct igmphdr *ih;
1189 - bool query = false;
1190 1191 struct iphdr *iph;
1191 1192 bool data = false;
1192 1193 bool v6 = false;
@@ -1204,9 +1205,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev)
1204 1205 case IGMP_HOST_MEMBERSHIP_REPORT:
1205 1206 report = true;
1206 1207 break;
1207 - case IGMP_HOST_MEMBERSHIP_QUERY:
1208 - query = true;
1209 - break;
1210 1208 default:
1211 1209 goto free;
1212 1210 }
@@ -1228,9 +1226,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev)
1228 1226 case ICMPV6_MLD2_REPORT:
1229 1227 report = true;
1230 1228 break;
1231 - case ICMPV6_MGM_QUERY:
1232 - query = true;
1233 - break;
1234 1229 default:
1235 1230 goto free;
1236 1231 }
@@ -1261,19 +1256,6 @@ static netdev_tx_t amt_dev_xmit(struct sk_buff *skb, struct net_device *dev)
1261 1256 goto free;
1262 1257 goto unlock;
1263 1258 } else if (amt->mode == AMT_MODE_RELAY) {
1264 - if (query) {
1265 - tunnel = amt_skb_cb(skb)->tunnel;
1266 - if (!tunnel) {
1267 - WARN_ON(1);
1268 - goto free;
1269 - }
1270 -
1271 - /* Do not forward unexpected query */
1272 - if (amt_send_membership_query(amt, skb, tunnel, v6))
1273 - goto free;
1274 - goto unlock;
1275 - }
1276 -
1277 1259 if (!data)
1278 1260 goto free;
1279 1261 list_for_each_entry_rcu(tunnel, &amt->tunnel_list, list) {
modified drivers/net/bareudp.c
@@ -356,7 +356,7 @@ static int bareudp_xmit_skb(struct sk_buff *skb, struct net_device *dev,
356 356 if (err)
357 357 goto free_dst;
358 358
359 - skb_set_inner_protocol(skb, bareudp->ethertype);
359 + skb_set_inner_protocol(skb, skb->protocol);
360 360 udp_tunnel_xmit_skb(rt, sk, skb, saddr, info->key.u.ipv4.dst,
361 361 tos, ttl, df, sport, bareudp->port,
362 362 !net_eq(bareudp->net, dev_net(bareudp->dev)),
@@ -424,6 +424,7 @@ static int bareudp6_xmit_skb(struct sk_buff *skb, struct net_device *dev,
424 424 if (err)
425 425 goto free_dst;
426 426
427 + skb_set_inner_protocol(skb, skb->protocol);
427 428 daddr = info->key.u.ipv6.dst;
428 429 udp_tunnel6_xmit_skb(dst, sk, skb, dev,
429 430 &saddr, &daddr, prio, ttl,
modified drivers/net/bonding/bond_main.c
@@ -5732,12 +5732,12 @@ static int bond_xdp_set(struct net_device *dev, struct bpf_prog *prog,
5732 5732 bpf_prog_inc(prog);
5733 5733 }
5734 5734
5735 - if (prog) {
5735 + if (prog && !old_prog)
5736 5736 static_branch_inc(&bpf_master_redirect_enabled_key);
5737 - } else if (old_prog) {
5738 - bpf_prog_put(old_prog);
5737 + else if (!prog && old_prog)
5739 5738 static_branch_dec(&bpf_master_redirect_enabled_key);
5740 - }
5739 + if (old_prog)
5740 + bpf_prog_put(old_prog);
5741 5741
5742 5742 return 0;
5743 5743
modified drivers/net/can/dev/skb.c
@@ -210,6 +210,10 @@ static void init_can_skb(struct sk_buff *skb)
210 210 {
211 211 skb->pkt_type = PACKET_BROADCAST;
212 212 skb->ip_summed = CHECKSUM_UNNECESSARY;
213 +
214 + skb_reset_mac_header(skb);
215 + skb_reset_network_header(skb);
216 + skb_reset_transport_header(skb);
213 217 }
214 218
215 219 struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf)
modified drivers/net/can/usb/f81604.c
@@ -169,7 +169,7 @@ struct f81604_int_data {
169 169 u8 rxerr;
170 170 u8 txerr;
171 171 u8 val;
172 - } __packed __aligned(4);
172 + } __packed;
173 173
174 174 struct f81604_sff {
175 175 __be16 id;
modified drivers/net/can/vxcan.c
@@ -79,6 +79,9 @@ static netdev_tx_t vxcan_xmit(struct sk_buff *oskb, struct net_device *dev)
79 79
80 80 /* reset CAN GW hop counter */
81 81 csx->can_gw_hops = 0;
82 + /* start with new CAN skb UID in the other namespace */
83 + csx->can_skb_uid = 0;
84 +
82 85 skb->pkt_type = PACKET_BROADCAST;
83 86 skb->dev = peer;
84 87 skb->ip_summed = CHECKSUM_UNNECESSARY;
modified drivers/net/dsa/microchip/ksz_common.h
@@ -853,7 +853,7 @@ static inline bool ksz_is_sgmii_port(struct ksz_device *dev, int port)
853 853 #define KSZ88_FAMILY_ID 0x88
854 854 #define KSZ8895_FAMILY_ID 0x95
855 855
856 - #define KSZ8_PORT_STATUS_0 0x08
856 + #define KSZ8_PORT_STATUS_0 0x18
857 857 #define KSZ8_PORT_FIBER_MODE BIT(7)
858 858
859 859 #define SW_CHIP_ID_M GENMASK(7, 4)
modified drivers/net/ethernet/actions/owl-emac.c
@@ -1552,6 +1552,8 @@ static int owl_emac_probe(struct platform_device *pdev)
1552 1552 return ret;
1553 1553 }
1554 1554
1555 + netdev->netdev_ops = &owl_emac_netdev_ops;
1556 +
1555 1557 ret = owl_emac_phy_init(netdev);
1556 1558 if (ret) {
1557 1559 dev_err(dev, "failed to initialize PHY\n");
@@ -1563,7 +1565,6 @@ static int owl_emac_probe(struct platform_device *pdev)
1563 1565 netdev->min_mtu = OWL_EMAC_MTU_MIN;
1564 1566 netdev->max_mtu = OWL_EMAC_MTU_MAX;
1565 1567 netdev->watchdog_timeo = OWL_EMAC_TX_TIMEOUT;
1566 - netdev->netdev_ops = &owl_emac_netdev_ops;
1567 1568 netdev->ethtool_ops = &owl_emac_ethtool_ops;
1568 1569 netif_napi_add(netdev, &priv->napi, owl_emac_poll);
1569 1570
modified drivers/net/ethernet/adi/adin1140.c
@@ -733,6 +733,8 @@ static int adin1140_probe(struct spi_device *spi)
733 733 if (ret)
734 734 return ret;
735 735
736 + netdev->netdev_ops = &adin1140_netdev_ops;
737 +
736 738 ret = adin1140_phy_init(priv, spi);
737 739 if (ret)
738 740 return ret;
@@ -748,7 +750,6 @@ static int adin1140_probe(struct spi_device *spi)
748 750
749 751 netdev->if_port = IF_PORT_10BASET;
750 752 netdev->irq = spi->irq;
751 - netdev->netdev_ops = &adin1140_netdev_ops;
752 753 netdev->ethtool_ops = &adin1140_ethtool_ops;
753 754 netdev->netns_immutable = true;
754 755 netdev->priv_flags |= IFF_LIVE_ADDR_CHANGE |
modified drivers/net/ethernet/aeroflex/greth.c
@@ -1421,6 +1421,8 @@ static int greth_of_probe(struct platform_device *ofdev)
1421 1421 /* Check if MAC can handle MDIO interrupts */
1422 1422 greth->mdio_int_en = (tmp >> 26) & 1;
1423 1423
1424 + dev->netdev_ops = &greth_netdev_ops;
1425 +
1424 1426 err = greth_mdio_init(greth);
1425 1427 if (err) {
1426 1428 if (netif_msg_probe(greth))
@@ -1498,7 +1500,6 @@ static int greth_of_probe(struct platform_device *ofdev)
1498 1500 dev->flags &= ~IFF_MULTICAST;
1499 1501 }
1500 1502
1501 - dev->netdev_ops = &greth_netdev_ops;
1502 1503 dev->ethtool_ops = &greth_ethtool_ops;
1503 1504
1504 1505 err = register_netdev(dev);
modified drivers/net/ethernet/airoha/airoha_eth.c
@@ -2800,14 +2800,34 @@ static int airoha_qdma_set_trtcm_param(struct airoha_qdma *qdma, int channel,
2800 2800 FIELD_PREP(TRTCM_METER_GROUP_MASK, group) |
2801 2801 FIELD_PREP(TRTCM_PARAM_INDEX_MASK, idx) |
2802 2802 FIELD_PREP(TRTCM_PARAM_RATE_TYPE_MASK, mode);
2803 + int i;
2803 2804
2804 - airoha_qdma_wr(qdma, REG_TRTCM_DATA_LOW(addr), val);
2805 - airoha_qdma_wr(qdma, REG_TRTCM_CFG_PARAM(addr), config);
2805 + /*
2806 + * HW might be in the middle of bucket handling and might
2807 + * require an additional try to actually apply the new TRTCM
2808 + * config.
2809 + */
2810 + for (i = 0; i < TRTCM_CONFIG_RETRY_MAX; i++) {
2811 + u32 data = 0;
2806 2812
2807 - return read_poll_timeout(airoha_qdma_rr, val,
2808 - val & TRTCM_PARAM_RW_DONE_MASK,
2809 - USEC_PER_MSEC, 10 * USEC_PER_MSEC, true,
2810 - qdma, REG_TRTCM_CFG_PARAM(addr));
2813 + airoha_qdma_wr(qdma, REG_TRTCM_DATA_LOW(addr), val);
2814 + airoha_qdma_wr(qdma, REG_TRTCM_CFG_PARAM(addr), config);
2815 +
2816 + if (read_poll_timeout(airoha_qdma_rr, data,
2817 + data & TRTCM_PARAM_RW_DONE_MASK,
2818 + USEC_PER_MSEC, 10 * USEC_PER_MSEC,
2819 + true, qdma, REG_TRTCM_CFG_PARAM(addr)))
2820 + continue;
2821 +
2822 + if (airoha_qdma_get_trtcm_param(qdma, channel, addr, param,
2823 + mode, &data, NULL))
2824 + continue;
2825 +
2826 + if (data == val)
2827 + return 0;
2828 + }
2829 +
2830 + return -EBUSY;
2811 2831 }
2812 2832
2813 2833 static int airoha_qdma_set_trtcm_config(struct airoha_qdma *qdma, int channel,
modified drivers/net/ethernet/airoha/airoha_eth.h
@@ -171,6 +171,8 @@ enum trtcm_param {
171 171 #define TRTCM_TOKEN_RATE_MASK GENMASK(23, 6)
172 172 #define TRTCM_TOKEN_RATE_FRACTION_MASK GENMASK(5, 0)
173 173
174 + #define TRTCM_CONFIG_RETRY_MAX 2
175 +
174 176 enum airoha_dma_map_type {
175 177 AIROHA_DMA_UNMAPPED,
176 178 AIROHA_DMA_MAP_SINGLE,
modified drivers/net/ethernet/allwinner/sun4i-emac.c
@@ -300,7 +300,7 @@ static int emac_dma_inblk_32bit(struct emac_board_info *db,
300 300 if (!req) {
301 301 dev_err(db->dev, "alloc emac dma req error.\n");
302 302 ret = -ENOMEM;
303 - goto alloc_req_err;
303 + goto prepare_err;
304 304 }
305 305
306 306 desc->callback_param = req;
@@ -319,9 +319,6 @@ static int emac_dma_inblk_32bit(struct emac_board_info *db,
319 319 submit_err:
320 320 emac_free_dma_req(req);
321 321
322 - alloc_req_err:
323 - dmaengine_desc_free(desc);
324 -
325 322 prepare_err:
326 323 dma_unmap_single(db->dev, rxbuf, count, DMA_FROM_DEVICE);
327 324 return ret;
modified drivers/net/ethernet/amd/au1000_eth.c
@@ -1225,6 +1225,8 @@ static int au1000_probe(struct platform_device *pdev)
1225 1225 goto err_mdiobus_reg;
1226 1226 }
1227 1227
1228 + dev->netdev_ops = &au1000_netdev_ops;
1229 +
1228 1230 err = au1000_mii_probe(dev);
1229 1231 if (err != 0)
1230 1232 goto err_out;
@@ -1263,7 +1265,6 @@ static int au1000_probe(struct platform_device *pdev)
1263 1265
1264 1266 dev->base_addr = base->start;
1265 1267 dev->irq = irq;
1266 - dev->netdev_ops = &au1000_netdev_ops;
1267 1268 dev->ethtool_ops = &au1000_ethtool_ops;
1268 1269 dev->watchdog_timeo = ETH_TX_TIMEOUT;
1269 1270
modified drivers/net/ethernet/broadcom/bnxt/bnxt.c
@@ -486,7 +486,7 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev)
486 486 struct netdev_queue *txq;
487 487 int i;
488 488 dma_addr_t mapping;
489 - unsigned int length, pad = 0;
489 + unsigned int length;
490 490 u32 len, free_size, vlan_tag_flags, cfa_action, flags;
491 491 struct bnxt_ptp_cfg *ptp = bp->ptp_cfg;
492 492 struct pci_dev *pdev = bp->pdev;
@@ -536,6 +536,16 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev)
536 536 return rc < 0 ? NETDEV_TX_BUSY : NETDEV_TX_OK;
537 537 }
538 538
539 + /* Pad after the SW USO branch: bnxt_sw_udp_gso_xmit() would
540 + * otherwise account the padding as UDP payload.
541 + * Must be done before skb_shinfo(skb)->nr_frags is sampled,
542 + * because skb_put_padto() might linearize the skb.
543 + */
544 + if (skb_put_padto(skb, BNXT_MIN_PKT_SIZE)) {
545 + /* SKB already freed. */
546 + goto tx_kick_pending;
547 + }
548 +
539 549 free_size = bnxt_tx_avail(bp, txr);
540 550 if (unlikely(free_size < skb_shinfo(skb)->nr_frags + 2)) {
541 551 /* We must have raced with NAPI cleanup */
@@ -672,14 +682,6 @@ static netdev_tx_t bnxt_start_xmit(struct sk_buff *skb, struct net_device *dev)
672 682 }
673 683
674 684 normal_tx:
675 - if (length < BNXT_MIN_PKT_SIZE) {
676 - pad = BNXT_MIN_PKT_SIZE - length;
677 - if (skb_pad(skb, pad))
678 - /* SKB already freed. */
679 - goto tx_kick_pending;
680 - length = BNXT_MIN_PKT_SIZE;
681 - }
682 -
683 685 mapping = dma_map_single(&pdev->dev, skb->data, len, DMA_TO_DEVICE);
684 686
685 687 if (unlikely(dma_mapping_error(&pdev->dev, mapping)))
@@ -759,10 +761,7 @@ normal_tx:
759 761 txbd->tx_bd_len_flags_type = cpu_to_le32(flags);
760 762 }
761 763
762 - flags &= ~TX_BD_LEN;
763 - txbd->tx_bd_len_flags_type =
764 - cpu_to_le32(((len + pad) << TX_BD_LEN_SHIFT) | flags |
765 - TX_BD_FLAGS_PACKET_END);
764 + txbd->tx_bd_len_flags_type |= cpu_to_le32(TX_BD_FLAGS_PACKET_END);
766 765
767 766 netdev_tx_sent_queue(txq, skb->len);
768 767
@@ -15547,7 +15546,7 @@ static void bnxt_fw_reset_task(struct work_struct *work)
15547 15546 if (test_and_clear_bit(BNXT_STATE_FW_ACTIVATE_RESET, &bp->state) &&
15548 15547 !test_bit(BNXT_STATE_FW_ACTIVATE, &bp->state))
15549 15548 bnxt_dl_remote_reload(bp);
15550 - if (pci_enable_device(bp->pdev)) {
15549 + if (!pci_is_enabled(bp->pdev) && pci_enable_device(bp->pdev)) {
15551 15550 netdev_err(bp->dev, "Cannot re-enable PCI device\n");
15552 15551 rc = -ENODEV;
15553 15552 goto fw_reset_abort;
@@ -17111,6 +17110,51 @@ void bnxt_print_device_info(struct bnxt *bp)
17111 17110 pcie_print_link_status(bp->pdev);
17112 17111 }
17113 17112
17113 + static void bnxt_clear_bars(struct pci_dev *pdev)
17114 + {
17115 + int off;
17116 +
17117 + for (off = PCI_BASE_ADDRESS_0; off <= PCI_BASE_ADDRESS_5; off += 4)
17118 + pci_write_config_dword(pdev, off, 0);
17119 + }
17120 +
17121 + /* Clear any pending DMA transactions from crash kernel while loading driver in
17122 + * capture kernel.
17123 + */
17124 + static int bnxt_kdump_reset(struct pci_dev *pdev)
17125 + {
17126 + int rc, i;
17127 + u16 cmd;
17128 +
17129 + pci_read_config_word(pdev, PCI_COMMAND, &cmd);
17130 + cmd &= ~(PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY);
17131 + pci_write_config_word(pdev, PCI_COMMAND, cmd);
17132 +
17133 + if (pci_save_state(pdev))
17134 + dev_warn(&pdev->dev, "Failed to save PCI state, PCI restore may be incomplete\n");
17135 +
17136 + rc = pcie_flr(pdev);
17137 + if (rc)
17138 + dev_warn(&pdev->dev, "pcie_flr() failed (rc: %d), trying to continue\n",
17139 + rc);
17140 +
17141 + /* In case device is not returning CRS, wait 5 seconds longer */
17142 + for (i = 0; i < 50; i++) {
17143 + pci_read_config_word(pdev, PCI_COMMAND, &cmd);
17144 + if (!PCI_POSSIBLE_ERROR(cmd))
17145 + break;
17146 + msleep(100);
17147 + }
17148 + if (PCI_POSSIBLE_ERROR(cmd)) {
17149 + dev_err(&pdev->dev, "PCI config space inaccessible after FLR, aborting\n");
17150 + return -ENODEV;
17151 + }
17152 +
17153 + bnxt_clear_bars(pdev);
17154 + pci_restore_state(pdev);
17155 + return 0;
17156 + }
17157 +
17114 17158 static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
17115 17159 {
17116 17160 struct bnxt_hw_resc *hw_resc;
@@ -17126,12 +17170,10 @@ static int bnxt_init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
17126 17170 return -ENODEV;
17127 17171 }
17128 17172
17129 - /* Clear any pending DMA transactions from crash kernel
17130 - * while loading driver in capture kernel.
17131 - */
17132 17173 if (is_kdump_kernel()) {
17133 - pci_clear_master(pdev);
17134 - pcie_flr(pdev);
17174 + rc = bnxt_kdump_reset(pdev);
17175 + if (rc)
17176 + return rc;
17135 17177 }
17136 17178
17137 17179 max_irqs = bnxt_get_max_irq(pdev);
@@ -17565,10 +17607,8 @@ static pci_ers_result_t bnxt_io_error_detected(struct pci_dev *pdev,
17565 17607 * so we disable bus master to prevent any potential bad DMAs before
17566 17608 * freeing kernel memory.
17567 17609 */
17568 - if (state == pci_channel_io_frozen) {
17569 - set_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN, &bp->state);
17610 + if (state == pci_channel_io_frozen)
17570 17611 bnxt_fw_fatal_close(bp);
17571 - }
17572 17612
17573 17613 if (netif_running(netdev))
17574 17614 __bnxt_close_nic(bp, true, true);
@@ -17598,69 +17638,80 @@ static pci_ers_result_t bnxt_io_slot_reset(struct pci_dev *pdev)
17598 17638 struct bnxt *bp = netdev_priv(netdev);
17599 17639 int retry = 0;
17600 17640 int err = 0;
17601 - int off;
17641 + u16 cmd;
17602 17642
17603 17643 netdev_info(bp->dev, "PCI Slot Reset\n");
17604 17644
17605 - if (test_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN, &bp->state)) {
17606 - /* After DPC, the chip should return CRS when the vendor ID
17607 - * config register is read until it is ready. On all chips,
17608 - * this is not happening reliably so add a 5-second delay as a
17609 - * workaround.
17610 - */
17611 - msleep(5000);
17612 - }
17645 + /* After a PCIe hot reset, the chip should return CRS when the
17646 + * vendor ID config register is read until it is ready. On all
17647 + * chips, this is not happening reliably so add a 5-second delay
17648 + * as a workaround.
17649 + */
17650 + msleep(5000);
17613 17651
17614 17652 netdev_lock(netdev);
17615 17653
17616 - if (pci_enable_device(pdev)) {
17654 + pci_read_config_word(pdev, PCI_COMMAND, &cmd);
17655 + if (PCI_POSSIBLE_ERROR(cmd)) {
17617 17656 dev_err(&pdev->dev,
17618 - "Cannot re-enable PCI device after reset.\n");
17619 - } else {
17620 - pci_set_master(pdev);
17621 - /* Upon fatal error, our device internal logic that latches to
17622 - * BAR value is getting reset and will restore only upon
17623 - * rewriting the BARs.
17624 - *
17625 - * As pci_restore_state() does not re-write the BARs if the
17626 - * value is same as saved value earlier, driver needs to
17627 - * write the BARs to 0 to force restore, in case of fatal error.
17628 - */
17629 - if (test_and_clear_bit(BNXT_STATE_PCI_CHANNEL_IO_FROZEN,
17630 - &bp->state)) {
17631 - for (off = PCI_BASE_ADDRESS_0;
17632 - off <= PCI_BASE_ADDRESS_5; off += 4)
17633 - pci_write_config_dword(bp->pdev, off, 0);
17634 - }
17635 - pci_restore_state(pdev);
17657 + "PCI config space inaccessible after reset\n");
17658 + goto reset_exit;
17659 + }
17636 17660
17637 - bnxt_inv_fw_health_reg(bp);
17638 - bnxt_try_map_fw_health_reg(bp);
17661 + /* Upon PCIe error, our device internal logic that latches to
17662 + * BAR value is getting reset and will restore only upon
17663 + * rewriting the BARs.
17664 + *
17665 + * As pci_restore_state() does not re-write the BARs if the
17666 + * value is same as saved value earlier, driver needs to
17667 + * write the BARs to 0 to force restore.
17668 + */
17669 + pci_clear_master(pdev);
17670 + pci_read_config_word(pdev, PCI_COMMAND, &cmd);
17671 + cmd &= ~PCI_COMMAND_MEMORY;
17672 + pci_write_config_word(pdev, PCI_COMMAND, cmd);
17639 17673
17640 - /* In some PCIe AER scenarios, firmware may take up to
17641 - * 10 seconds to become ready in the worst case.
17642 - */
17643 - do {
17644 - err = bnxt_try_recover_fw(bp);
17645 - if (!err)
17646 - break;
17647 - retry++;
17648 - } while (retry < BNXT_FW_SLOT_RESET_RETRY);
17674 + bnxt_clear_bars(pdev);
17675 + pci_restore_state(pdev);
17649 17676
17650 - if (err) {
17651 - dev_err(&pdev->dev, "Firmware not ready\n");
17652 - goto reset_exit;
17677 + if (!pci_is_enabled(pdev) && pci_enable_device(pdev)) {
17678 + dev_err(&pdev->dev,
17679 + "Cannot re-enable PCI device after reset.\n");
17680 + pci_read_config_word(pdev, PCI_COMMAND, &cmd);
17681 + if (!PCI_POSSIBLE_ERROR(cmd)) {
17682 + cmd &= ~(PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY);
17683 + pci_write_config_word(pdev, PCI_COMMAND, cmd);
17653 17684 }
17685 + goto reset_exit;
17686 + }
17687 + pci_set_master(pdev);
17654 17688
17655 - err = bnxt_hwrm_func_reset(bp);
17689 + bnxt_inv_fw_health_reg(bp);
17690 + bnxt_try_map_fw_health_reg(bp);
17691 +
17692 + /* In some PCIe AER scenarios, firmware may take up to
17693 + * 10 seconds to become ready in the worst case.
17694 + */
17695 + do {
17696 + err = bnxt_try_recover_fw(bp);
17656 17697 if (!err)
17657 - result = PCI_ERS_RESULT_RECOVERED;
17698 + break;
17699 + retry++;
17700 + } while (retry < BNXT_FW_SLOT_RESET_RETRY);
17658 17701
17659 - /* IRQ will be initialized later in bnxt_io_resume */
17660 - bnxt_ulp_irq_stop(bp);
17661 - bnxt_clear_int_mode(bp);
17702 + if (err) {
17703 + dev_err(&pdev->dev, "Firmware not ready\n");
17704 + goto reset_exit;
17662 17705 }
17663 17706
17707 + err = bnxt_hwrm_func_reset(bp);
17708 + if (!err)
17709 + result = PCI_ERS_RESULT_RECOVERED;
17710 +
17711 + /* IRQ will be initialized later in bnxt_io_resume */
17712 + bnxt_ulp_irq_stop(bp);
17713 + bnxt_clear_int_mode(bp);
17714 +
17664 17715 reset_exit:
17665 17716 clear_bit(BNXT_STATE_IN_FW_RESET, &bp->state);
17666 17717 bnxt_clear_reservations(bp, true);
modified drivers/net/ethernet/broadcom/bnxt/bnxt.h
@@ -2468,7 +2468,6 @@ struct bnxt {
2468 2468 #define BNXT_STATE_ABORT_ERR 5
2469 2469 #define BNXT_STATE_FW_FATAL_COND 6
2470 2470 #define BNXT_STATE_DRV_REGISTERED 7
2471 - #define BNXT_STATE_PCI_CHANNEL_IO_FROZEN 8
2472 2471 #define BNXT_STATE_NAPI_DISABLED 9
2473 2472 #define BNXT_STATE_FW_ACTIVATE 11
2474 2473 #define BNXT_STATE_RECOVER 12
modified drivers/net/ethernet/broadcom/genet/bcmgenet.c
@@ -2153,6 +2153,16 @@ static netdev_tx_t bcmgenet_xmit(struct sk_buff *skb, struct net_device *dev)
2153 2153 goto out;
2154 2154 }
2155 2155
2156 + /* We store Tx state in the control block, so the skb must not be
2157 + * shared, but ether_setup() leaves IFF_TX_SKB_SHARING set.
2158 + */
2159 + skb = skb_share_check(skb, GFP_ATOMIC);
2160 + if (!skb) {
2161 + BCMGENET_STATS64_INC((&ring->stats64), dropped);
2162 + ret = NETDEV_TX_OK;
2163 + goto out;
2164 + }
2165 +
2156 2166 /* Retain how many bytes will be sent on the wire, without TSB inserted
2157 2167 * by transmit checksum offload
2158 2168 */
modified drivers/net/ethernet/broadcom/genet/bcmgenet_wol.c
@@ -253,6 +253,17 @@ int bcmgenet_wol_power_up_cfg(struct bcmgenet_priv *priv,
253 253 reg = bcmgenet_umac_readl(priv, UMAC_CMD);
254 254 reg &= ~CMD_CRC_FWD;
255 255 bcmgenet_umac_writel(priv, reg, UMAC_CMD);
256 +
257 + /*
258 + * Mirror wol_power_down_cfg(). If only UMAC_RX
259 + * is enabled, then we must place the UMAC back
260 + * into SW_RESET.
261 + */
262 + reg = bcmgenet_umac_readl(priv, UMAC_CMD);
263 + if ((reg & CMD_RX_EN) && !(reg & CMD_TX_EN)) {
264 + reg |= CMD_SW_RESET;
265 + bcmgenet_umac_writel(priv, reg, UMAC_CMD);
266 + }
256 267 spin_unlock_bh(&priv->reg_lock);
257 268
258 269 /* Resume link status tracking */
modified drivers/net/ethernet/cadence/macb_main.c
@@ -2421,34 +2421,40 @@ static inline int macb_clear_csum(struct sk_buff *skb)
2421 2421 return 0;
2422 2422 }
2423 2423
2424 + static bool macb_needs_sw_fcs(struct sk_buff *skb, struct net_device *netdev)
2425 + {
2426 + return netdev->features & NETIF_F_HW_CSUM &&
2427 + skb->ip_summed != CHECKSUM_PARTIAL &&
2428 + !skb_shinfo(skb)->gso_size && !ptp_one_step_sync(skb);
2429 + }
2430 +
2424 2431 /* Returns a negative errno, or the FCS bytes appended (0 or ETH_FCS_LEN). */
2425 - static int macb_pad_and_fcs(struct sk_buff **skb, struct net_device *netdev)
2432 + static int macb_pad_and_fcs(struct sk_buff **skb, bool add_fcs)
2426 2433 {
2427 2434 bool cloned = skb_cloned(*skb) || skb_header_cloned(*skb) ||
2428 2435 skb_is_nonlinear(*skb);
2429 2436 int padlen = ETH_ZLEN - (*skb)->len;
2430 2437 int tailroom = skb_tailroom(*skb);
2438 + bool shared = skb_shared(*skb);
2431 2439 struct sk_buff *nskb;
2432 2440 u32 fcs;
2433 2441
2434 - if (!(netdev->features & NETIF_F_HW_CSUM) ||
2435 - !((*skb)->ip_summed != CHECKSUM_PARTIAL) ||
2436 - skb_shinfo(*skb)->gso_size || ptp_one_step_sync(*skb))
2442 + if (!add_fcs)
2437 2443 return 0;
2438 2444
2439 2445 if (padlen <= 0) {
2440 - /* FCS could be appeded to tailroom. */
2441 - if (tailroom >= ETH_FCS_LEN)
2446 + /* FCS could be appended to tailroom. */
2447 + if (!shared && !skb_is_nonlinear(*skb) &&
2448 + tailroom >= ETH_FCS_LEN)
2442 2449 goto add_fcs;
2443 - /* No room for FCS, need to reallocate skb. */
2444 - else
2445 - padlen = ETH_FCS_LEN;
2450 + /* Reallocate with room for the FCS. */
2451 + padlen = ETH_FCS_LEN;
2446 2452 } else {
2447 2453 /* Add room for FCS. */
2448 2454 padlen += ETH_FCS_LEN;
2449 2455 }
2450 2456
2451 - if (cloned || tailroom < padlen) {
2457 + if (shared || cloned || tailroom < padlen) {
2452 2458 nskb = skb_copy_expand(*skb, 0, padlen, GFP_ATOMIC);
2453 2459 if (!nskb)
2454 2460 return -ENOMEM;
@@ -2481,27 +2487,15 @@ static netdev_tx_t macb_start_xmit(struct sk_buff *skb,
2481 2487 unsigned int desc_cnt, nr_frags, frag_size, f;
2482 2488 struct macb_queue *queue = &bp->queues[q];
2483 2489 netdev_tx_t ret = NETDEV_TX_OK;
2484 - unsigned int hdrlen;
2490 + unsigned int hdrlen, tx_len;
2491 + bool add_fcs, is_lso;
2485 2492 unsigned long flags;
2486 2493 int fcs_len;
2487 - bool is_lso;
2488 -
2489 - if (macb_clear_csum(skb)) {
2490 - dev_kfree_skb_any(skb);
2491 - return ret;
2492 - }
2493 -
2494 - fcs_len = macb_pad_and_fcs(&skb, netdev);
2495 - if (fcs_len < 0) {
2496 - dev_kfree_skb_any(skb);
2497 - return ret;
2498 - }
2499 -
2500 - if (macb_dma_ptp(bp) &&
2501 - (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP))
2502 - skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
2503 2494
2495 + add_fcs = macb_needs_sw_fcs(skb, netdev);
2504 2496 is_lso = (skb_shinfo(skb)->gso_size != 0);
2497 + tx_len = add_fcs ? max_t(unsigned int, skb->len, ETH_ZLEN) +
2498 + ETH_FCS_LEN : skb->len;
2505 2499
2506 2500 if (is_lso) {
2507 2501 /* length of headers */
@@ -2515,8 +2509,11 @@ static netdev_tx_t macb_start_xmit(struct sk_buff *skb,
2515 2509 /* if this is required, would need to copy to single buffer */
2516 2510 return NETDEV_TX_BUSY;
2517 2511 }
2518 - } else
2512 + } else if (add_fcs) {
2513 + hdrlen = umin(tx_len, bp->max_tx_length);
2514 + } else {
2519 2515 hdrlen = umin(skb_headlen(skb), bp->max_tx_length);
2516 + }
2520 2517
2521 2518 #if defined(DEBUG) && defined(VERBOSE_DEBUG)
2522 2519 netdev_vdbg(bp->netdev,
@@ -2531,12 +2528,18 @@ static netdev_tx_t macb_start_xmit(struct sk_buff *skb,
2531 2528 * socket buffer: skb fragments of jumbo frames may need to be
2532 2529 * split into many buffer descriptors.
2533 2530 */
2534 - if (is_lso && (skb_headlen(skb) > hdrlen))
2531 + if (add_fcs) {
2532 + /* macb_pad_and_fcs() linearizes the skb before adding the FCS. */
2533 + desc_cnt = DIV_ROUND_UP(tx_len, bp->max_tx_length);
2534 + nr_frags = 0;
2535 + } else if (is_lso && (skb_headlen(skb) > hdrlen)) {
2535 2536 /* extra header descriptor if also payload in first buffer */
2536 2537 desc_cnt = DIV_ROUND_UP((skb_headlen(skb) - hdrlen), bp->max_tx_length) + 1;
2537 - else
2538 + nr_frags = skb_shinfo(skb)->nr_frags;
2539 + } else {
2538 2540 desc_cnt = DIV_ROUND_UP(skb_headlen(skb), bp->max_tx_length);
2539 - nr_frags = skb_shinfo(skb)->nr_frags;
2541 + nr_frags = skb_shinfo(skb)->nr_frags;
2542 + }
2540 2543 for (f = 0; f < nr_frags; f++) {
2541 2544 frag_size = skb_frag_size(&skb_shinfo(skb)->frags[f]);
2542 2545 desc_cnt += DIV_ROUND_UP(frag_size, bp->max_tx_length);
@@ -2554,6 +2557,21 @@ static netdev_tx_t macb_start_xmit(struct sk_buff *skb,
2554 2557 goto unlock;
2555 2558 }
2556 2559
2560 + if (macb_clear_csum(skb)) {
2561 + dev_kfree_skb_any(skb);
2562 + goto unlock;
2563 + }
2564 +
2565 + fcs_len = macb_pad_and_fcs(&skb, add_fcs);
2566 + if (fcs_len < 0) {
2567 + dev_kfree_skb_any(skb);
2568 + goto unlock;
2569 + }
2570 +
2571 + if (macb_dma_ptp(bp) &&
2572 + (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP))
2573 + skb_shinfo(skb)->tx_flags |= SKBTX_IN_PROGRESS;
2574 +
2557 2575 /* Map socket buffer for DMA transfer */
2558 2576 if (macb_tx_map(bp, queue, skb, hdrlen, fcs_len)) {
2559 2577 dev_kfree_skb_any(skb);
modified drivers/net/ethernet/chelsio/inline_crypto/ch_ktls/chcr_ktls.c
@@ -389,7 +389,7 @@ static void chcr_ktls_dev_del(struct net_device *netdev,
389 389 cxgb4_remove_tid(&tx_info->adap->tids, tx_info->tx_chan,
390 390 tx_info->tid, tx_info->ip_family);
391 391
392 - xa_erase(&u_ctx->tid_list, tx_info->tid);
392 + xa_erase_bh(&u_ctx->tid_list, tx_info->tid);
393 393 }
394 394
395 395 port_stats = &tx_info->adap->ch_ktls_stats.ktls_port[tx_info->port_id];
@@ -577,7 +577,7 @@ free_tid:
577 577 cxgb4_remove_tid(&tx_info->adap->tids, tx_info->tx_chan,
578 578 tx_info->tid, tx_info->ip_family);
579 579
580 - xa_erase(&u_ctx->tid_list, tx_info->tid);
580 + xa_erase_bh(&u_ctx->tid_list, tx_info->tid);
581 581
582 582 put_module:
583 583 /* release module refcount */
modified drivers/net/ethernet/ethoc.c
@@ -1211,6 +1211,8 @@ static int ethoc_probe(struct platform_device *pdev)
1211 1211 goto free3;
1212 1212 }
1213 1213
1214 + netdev->netdev_ops = &ethoc_netdev_ops;
1215 +
1214 1216 ret = ethoc_mdio_probe(netdev);
1215 1217 if (ret) {
1216 1218 dev_err(&netdev->dev, "failed to probe MDIO bus\n");
@@ -1218,7 +1220,6 @@ static int ethoc_probe(struct platform_device *pdev)
1218 1220 }
1219 1221
1220 1222 /* setup the net_device structure */
1221 - netdev->netdev_ops = &ethoc_netdev_ops;
1222 1223 netdev->watchdog_timeo = ETHOC_TIMEOUT;
1223 1224 netdev->features |= 0;
1224 1225 netdev->ethtool_ops = &ethoc_ethtool_ops;
modified drivers/net/ethernet/google/gve/gve_main.c
@@ -1708,17 +1708,17 @@ static int gve_xsk_pool_disable(struct net_device *dev,
1708 1708 }
1709 1709
1710 1710 napi_rx = &priv->ntfy_blocks[priv->rx[qid].ntfy_id].napi;
1711 - napi_disable(napi_rx); /* make sure current rx poll is done */
1711 + napi_disable_locked(napi_rx); /* make sure current rx poll is done */
1712 1712
1713 1713 tx_qid = gve_xdp_tx_queue_id(priv, qid);
1714 1714 napi_tx = &priv->ntfy_blocks[priv->tx[tx_qid].ntfy_id].napi;
1715 - napi_disable(napi_tx); /* make sure current tx poll is done */
1715 + napi_disable_locked(napi_tx); /* make sure current tx poll is done */
1716 1716
1717 1717 gve_unreg_xsk_pool(priv, qid);
1718 1718 smp_mb(); /* Make sure it is visible to the workers on datapath */
1719 1719
1720 - napi_enable(napi_rx);
1721 - napi_enable(napi_tx);
1720 + napi_enable_locked(napi_rx);
1721 + napi_enable_locked(napi_tx);
1722 1722 if (gve_is_gqi(priv)) {
1723 1723 if (gve_rx_work_pending(&priv->rx[qid]))
1724 1724 napi_schedule(napi_rx);
modified drivers/net/ethernet/google/gve/gve_rx_dqo.c
@@ -113,6 +113,12 @@ static void gve_rx_reset_ring_dqo(struct gve_priv *priv, int idx)
113 113 gve_free_to_page_pool(rx, bs, false);
114 114 else
115 115 gve_free_qpl_page_dqo(bs);
116 +
117 + if (gve_buf_state_is_allocated(rx, bs) &&
118 + bs->xsk_buff) {
119 + xsk_buff_free(bs->xsk_buff);
120 + bs->xsk_buff = NULL;
121 + }
116 122 }
117 123 }
118 124
@@ -836,7 +842,12 @@ static int gve_rx_dqo(struct napi_struct *napi, struct gve_rx_ring *rx,
836 842 }
837 843
838 844 if (unlikely(compl_desc->rx_error)) {
839 - gve_free_buffer(rx, buf_state);
845 + if (buf_state->xsk_buff) {
846 + xsk_buff_free(buf_state->xsk_buff);
847 + gve_free_buf_state(rx, buf_state);
848 + } else {
849 + gve_free_buffer(rx, buf_state);
850 + }
840 851 return -EINVAL;
841 852 }
842 853
modified drivers/net/ethernet/hisilicon/hip04_eth.c
@@ -976,6 +976,8 @@ static int hip04_mac_probe(struct platform_device *pdev)
976 976 goto init_fail;
977 977 }
978 978
979 + ndev->netdev_ops = &hip04_netdev_ops;
980 +
979 981 priv->phy_node = of_parse_phandle(node, "phy-handle", 0);
980 982 if (priv->phy_node) {
981 983 priv->phy = of_phy_connect(ndev, priv->phy_node,
@@ -989,7 +991,6 @@ static int hip04_mac_probe(struct platform_device *pdev)
989 991
990 992 INIT_WORK(&priv->tx_timeout_task, hip04_tx_timeout_task);
991 993
992 - ndev->netdev_ops = &hip04_netdev_ops;
993 994 ndev->ethtool_ops = &hip04_ethtool_ops;
994 995 ndev->watchdog_timeo = TX_TIMEOUT;
995 996 ndev->priv_flags |= IFF_UNICAST_FLT;
modified drivers/net/ethernet/hisilicon/hisi_femac.c
@@ -830,6 +830,8 @@ static int hisi_femac_drv_probe(struct platform_device *pdev)
830 830 hisi_femac_phy_reset(priv);
831 831 }
832 832
833 + ndev->netdev_ops = &hisi_femac_netdev_ops;
834 +
833 835 phy = of_phy_get_and_connect(ndev, node, hisi_femac_adjust_link);
834 836 if (!phy) {
835 837 dev_err(dev, "connect to PHY failed!\n");
@@ -850,7 +852,6 @@ static int hisi_femac_drv_probe(struct platform_device *pdev)
850 852
851 853 ndev->watchdog_timeo = 6 * HZ;
852 854 ndev->priv_flags |= IFF_UNICAST_FLT;
853 - ndev->netdev_ops = &hisi_femac_netdev_ops;
854 855 ndev->ethtool_ops = &hisi_femac_ethtools_ops;
855 856 netif_napi_add_weight(ndev, &priv->napi, hisi_femac_poll,
856 857 FEMAC_POLL_WEIGHT);
modified drivers/net/ethernet/ibm/ibmveth.c
@@ -553,10 +553,15 @@ static int ibmveth_rxq_harvest_buffer(struct ibmveth_adapter *adapter,
553 553
554 554 static void ibmveth_free_tx_ltb(struct ibmveth_adapter *adapter, int idx)
555 555 {
556 + void *ptr = adapter->tx_ltb_ptr[idx];
557 +
558 + if (!ptr)
559 + return;
560 +
561 + adapter->tx_ltb_ptr[idx] = NULL;
556 562 dma_unmap_single(&adapter->vdev->dev, adapter->tx_ltb_dma[idx],
557 563 adapter->tx_ltb_size, DMA_TO_DEVICE);
558 - kfree(adapter->tx_ltb_ptr[idx]);
559 - adapter->tx_ltb_ptr[idx] = NULL;
564 + kfree(ptr);
560 565 }
561 566
562 567 static int ibmveth_allocate_tx_ltb(struct ibmveth_adapter *adapter, int idx)
@@ -667,7 +672,7 @@ static int ibmveth_open(struct net_device *netdev)
667 672
668 673 for (i = 0; i < netdev->real_num_tx_queues; i++) {
669 674 if (ibmveth_allocate_tx_ltb(adapter, i))
670 - goto out_free_tx_ltb;
675 + goto out_unmap_filter_list;
671 676 }
672 677
673 678 adapter->rx_queue.index = 0;
@@ -718,10 +723,6 @@ static int ibmveth_open(struct net_device *netdev)
718 723 if (rc != 0) {
719 724 netdev_err(netdev, "unable to request irq 0x%x, rc %d\n",
720 725 netdev->irq, rc);
721 - do {
722 - lpar_rc = h_free_logical_lan(adapter->vdev->unit_address);
723 - } while (H_IS_LONG_BUSY(lpar_rc) || (lpar_rc == H_BUSY));
724 -
725 726 goto out_free_buffer_pools;
726 727 }
727 728
@@ -737,6 +738,9 @@ static int ibmveth_open(struct net_device *netdev)
737 738 return 0;
738 739
739 740 out_free_buffer_pools:
741 + do {
742 + lpar_rc = h_free_logical_lan(adapter->vdev->unit_address);
743 + } while (H_IS_LONG_BUSY(lpar_rc) || (lpar_rc == H_BUSY));
740 744 while (--i >= 0) {
741 745 if (adapter->rx_buff_pool[i].active)
742 746 ibmveth_free_buffer_pool(adapter,
@@ -746,10 +750,8 @@ out_unmap_filter_list:
746 750 dma_unmap_single(dev, adapter->filter_list_dma, 4096,
747 751 DMA_BIDIRECTIONAL);
748 752
749 - out_free_tx_ltb:
750 - while (--i >= 0) {
753 + for (i = netdev->real_num_tx_queues - 1; i >= 0; i--)
751 754 ibmveth_free_tx_ltb(adapter, i);
752 - }
753 755
754 756 out_unmap_buffer_list:
755 757 dma_unmap_single(dev, adapter->buffer_list_dma, 4096,
modified drivers/net/ethernet/intel/e1000e/netdev.c
@@ -67,6 +67,13 @@ static const struct dmi_system_id disable_k1_list[] = {
67 67 DMI_MATCH(DMI_PRODUCT_NAME, "Dell Pro 16 Plus PB16250"),
68 68 },
69 69 },
70 + {
71 + .ident = "Lenovo ThinkPad P14s Gen 5",
72 + .matches = {
73 + DMI_MATCH(DMI_SYS_VENDOR, "LENOVO"),
74 + DMI_MATCH(DMI_PRODUCT_VERSION, "ThinkPad P14s Gen 5"),
75 + },
76 + },
70 77 {}
71 78 };
72 79
modified drivers/net/ethernet/intel/i40e/i40e_virtchnl_pf.c
@@ -4943,6 +4943,20 @@ out:
4943 4943 return ret;
4944 4944 }
4945 4945
4946 + /**
4947 + * i40e_setup_vf_trust - Enable/disable VF trust mode without reset
4948 + * @vf: VF to configure
4949 + * @setting: trust setting
4950 + *
4951 + * Update VF flags when changing trust without performing a VF reset.
4952 + * This is only called when it's safe to skip the reset (VF has no advanced
4953 + * features configured that need cleanup).
4954 + */
4955 + static void i40e_setup_vf_trust(struct i40e_vf *vf, bool setting)
4956 + {
4957 + assign_bit(I40E_VIRTCHNL_VF_CAP_PRIVILEGE, &vf->vf_caps, setting);
4958 + }
4959 +
4946 4960 /**
4947 4961 * i40e_ndo_set_vf_trust
4948 4962 * @netdev: network interface device structure of the pf
@@ -4987,19 +5001,20 @@ int i40e_ndo_set_vf_trust(struct net_device *netdev, int vf_id, bool setting)
4987 5001 set_bit(__I40E_MACVLAN_SYNC_PENDING, pf->state);
4988 5002 pf->vsi[vf->lan_vsi_idx]->flags |= I40E_VSI_FLAG_FILTER_CHANGED;
4989 5003
4990 - i40e_vc_reset_vf(vf, true);
5004 + /* Reset only if revoking trust and VF has advanced features configured */
5005 + if (!setting &&
5006 + (vf->adq_enabled || vf->num_cloud_filters > 0 ||
5007 + test_bit(I40E_VF_STATE_UC_PROMISC, &vf->vf_states) ||
5008 + test_bit(I40E_VF_STATE_MC_PROMISC, &vf->vf_states))) {
5009 + i40e_vc_reset_vf(vf, true);
5010 + i40e_del_all_cloud_filters(vf);
5011 + } else {
5012 + i40e_setup_vf_trust(vf, setting);
5013 + }
5014 +
4991 5015 dev_info(&pf->pdev->dev, "VF %u is now %strusted\n",
4992 5016 vf_id, setting ? "" : "un");
4993 5017
4994 - if (vf->adq_enabled) {
4995 - if (!vf->trusted) {
4996 - dev_info(&pf->pdev->dev,
4997 - "VF %u no longer Trusted, deleting all cloud filters\n",
4998 - vf_id);
4999 - i40e_del_all_cloud_filters(vf);
5000 - }
5001 - }
5002 -
5003 5018 out:
5004 5019 clear_bit(__I40E_VIRTCHNL_OP_PENDING, pf->state);
5005 5020 return ret;
modified drivers/net/ethernet/intel/iavf/iavf.h
@@ -259,7 +259,6 @@ struct iavf_adapter {
259 259 struct work_struct adminq_task;
260 260 struct work_struct finish_config;
261 261 wait_queue_head_t down_waitqueue;
262 - wait_queue_head_t vc_waitqueue;
263 262 struct iavf_q_vector *q_vectors;
264 263 struct list_head vlan_filter_list;
265 264 int num_vlan_filters;
@@ -588,8 +587,9 @@ void iavf_configure_queues(struct iavf_adapter *adapter);
588 587 void iavf_enable_queues(struct iavf_adapter *adapter);
589 588 void iavf_disable_queues(struct iavf_adapter *adapter);
590 589 void iavf_map_queues(struct iavf_adapter *adapter);
591 - void iavf_add_ether_addrs(struct iavf_adapter *adapter);
590 + int iavf_add_ether_addrs(struct iavf_adapter *adapter);
592 591 void iavf_del_ether_addrs(struct iavf_adapter *adapter);
592 + void iavf_mac_add_reject(struct iavf_adapter *adapter);
593 593 void iavf_add_vlans(struct iavf_adapter *adapter);
594 594 void iavf_del_vlans(struct iavf_adapter *adapter);
595 595 void iavf_set_promiscuous(struct iavf_adapter *adapter);
@@ -606,6 +606,13 @@ void iavf_disable_vlan_stripping(struct iavf_adapter *adapter);
606 606 void iavf_virtchnl_completion(struct iavf_adapter *adapter,
607 607 enum virtchnl_ops v_opcode,
608 608 enum iavf_status v_retval, u8 *msg, u16 msglen);
609 + int iavf_poll_virtchnl_response(struct iavf_adapter *adapter,
610 + struct iavf_arq_event_info *event,
611 + bool (*condition)(struct iavf_adapter *adapter,
612 + const void *data,
613 + enum virtchnl_ops v_op),
614 + const void *cond_data,
615 + unsigned int timeout_ms);
609 616 int iavf_config_rss(struct iavf_adapter *adapter);
610 617 void iavf_cfg_queues_bw(struct iavf_adapter *adapter);
611 618 void iavf_cfg_queues_quanta_size(struct iavf_adapter *adapter);
modified drivers/net/ethernet/intel/iavf/iavf_main.c
@@ -1029,6 +1029,60 @@ static bool iavf_is_mac_set_handled(struct net_device *netdev,
1029 1029 return ret;
1030 1030 }
1031 1031
1032 + /**
1033 + * iavf_mac_change_done - Check if MAC change completed
1034 + * @adapter: board private structure
1035 + * @data: MAC address being checked (as const void *)
1036 + * @v_op: virtchnl opcode from processed message
1037 + *
1038 + * Callback for iavf_poll_virtchnl_response() to check if MAC change completed.
1039 + *
1040 + * Return: true if MAC change completed, false otherwise
1041 + */
1042 + static bool iavf_mac_change_done(struct iavf_adapter *adapter,
1043 + const void *data, enum virtchnl_ops v_op)
1044 + {
1045 + const u8 *addr = data;
1046 +
1047 + return iavf_is_mac_set_handled(adapter->netdev, addr);
1048 + }
1049 +
1050 + /**
1051 + * iavf_set_mac_sync - Synchronously change MAC address
1052 + * @adapter: board private structure
1053 + * @addr: MAC address to set
1054 + *
1055 + * Send MAC change request to PF and poll admin queue for response.
1056 + * Caller must hold netdev_lock. This can sleep for up to 2.5 seconds.
1057 + * Event buffer is allocated before sending to avoid state mismatch if
1058 + * allocation fails after message is sent to PF.
1059 + *
1060 + * Return: 0 on success, negative on failure
1061 + */
1062 + static int iavf_set_mac_sync(struct iavf_adapter *adapter, const u8 *addr)
1063 + {
1064 + struct iavf_arq_event_info event;
1065 + int ret;
1066 +
1067 + netdev_assert_locked(adapter->netdev);
1068 +
1069 + event.buf_len = IAVF_MAX_AQ_BUF_SIZE;
1070 + event.msg_buf = kzalloc(event.buf_len, GFP_KERNEL);
1071 + if (!event.msg_buf)
1072 + return -ENOMEM;
1073 +
1074 + ret = iavf_add_ether_addrs(adapter);
1075 + if (ret)
1076 + goto out;
1077 +
1078 + ret = iavf_poll_virtchnl_response(adapter, &event,
1079 + iavf_mac_change_done, addr, 2500);
1080 +
1081 + out:
1082 + kfree(event.msg_buf);
1083 + return ret;
1084 + }
1085 +
1032 1086 /**
1033 1087 * iavf_set_mac - NDO callback to set port MAC address
1034 1088 * @netdev: network interface device structure
@@ -1046,25 +1100,23 @@ static int iavf_set_mac(struct net_device *netdev, void *p)
1046 1100 return -EADDRNOTAVAIL;
1047 1101
1048 1102 ret = iavf_replace_primary_mac(adapter, addr->sa_data);
1049 -
1050 1103 if (ret)
1051 1104 return ret;
1052 1105
1053 - ret = wait_event_interruptible_timeout(adapter->vc_waitqueue,
1054 - iavf_is_mac_set_handled(netdev, addr->sa_data),
1055 - msecs_to_jiffies(2500));
1056 -
1057 - /* If ret < 0 then it means wait was interrupted.
1058 - * If ret == 0 then it means we got a timeout.
1059 - * else it means we got response for set MAC from PF,
1060 - * check if netdev MAC was updated to requested MAC,
1061 - * if yes then set MAC succeeded otherwise it failed return -EACCES
1062 - */
1063 - if (ret < 0)
1106 + ret = iavf_set_mac_sync(adapter, addr->sa_data);
1107 + if (ret) {
1108 + /* Rollback only if send failed (message never reached PF).
1109 + * Don't rollback on timeout (-EAGAIN) because the message was
1110 + * sent and PF will eventually respond. When the response arrives,
1111 + * iavf_virtchnl_completion() will handle rollback (on PF error)
1112 + * or acceptance (on PF success) automatically.
1113 + */
1114 + if (ret != -EAGAIN) {
1115 + iavf_mac_add_reject(adapter);
1116 + ether_addr_copy(adapter->hw.mac.addr, netdev->dev_addr);
1117 + }
1064 1118 return ret;
1065 -
1066 - if (!ret)
1067 - return -EAGAIN;
1119 + }
1068 1120
1069 1121 if (!ether_addr_equal(netdev->dev_addr, addr->sa_data))
1070 1122 return -EACCES;
@@ -5394,9 +5446,6 @@ static int iavf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
5394 5446 /* Setup the wait queue for indicating transition to down status */
5395 5447 init_waitqueue_head(&adapter->down_waitqueue);
5396 5448
5397 - /* Setup the wait queue for indicating virtchannel events */
5398 - init_waitqueue_head(&adapter->vc_waitqueue);
5399 -
5400 5449 INIT_LIST_HEAD(&adapter->ptp.aq_cmds);
5401 5450 init_waitqueue_head(&adapter->ptp.phc_time_waitqueue);
5402 5451 mutex_init(&adapter->ptp.aq_cmd_lock);
modified drivers/net/ethernet/intel/iavf/iavf_virtchnl.c
@@ -2,6 +2,7 @@
2 2 /* Copyright(c) 2013 - 2018 Intel Corporation. */
3 3
4 4 #include <linux/net/intel/libie/rx.h>
5 + #include <net/netdev_lock.h>
5 6
6 7 #include "iavf.h"
7 8 #include "iavf_ptp.h"
@@ -555,20 +556,23 @@ iavf_set_mac_addr_type(struct virtchnl_ether_addr *virtchnl_ether_addr,
555 556 * @adapter: adapter structure
556 557 *
557 558 * Request that the PF add one or more addresses to our filters.
558 - **/
559 - void iavf_add_ether_addrs(struct iavf_adapter *adapter)
559 + *
560 + * Return: 0 on success, negative on failure
561 + */
562 + int iavf_add_ether_addrs(struct iavf_adapter *adapter)
560 563 {
561 564 struct virtchnl_ether_addr_list *veal;
562 565 struct iavf_mac_filter *f;
563 566 int i = 0, count = 0;
564 567 bool more = false;
565 568 size_t len;
569 + int ret;
566 570
567 571 if (adapter->current_op != VIRTCHNL_OP_UNKNOWN) {
568 572 /* bail because we already have a command pending */
569 573 dev_err(&adapter->pdev->dev, "Cannot add filters, command %d pending\n",
570 574 adapter->current_op);
571 - return;
575 + return -EBUSY;
572 576 }
573 577
574 578 spin_lock_bh(&adapter->mac_vlan_list_lock);
@@ -580,7 +584,7 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter)
580 584 if (!count) {
581 585 adapter->aq_required &= ~IAVF_FLAG_AQ_ADD_MAC_FILTER;
582 586 spin_unlock_bh(&adapter->mac_vlan_list_lock);
583 - return;
587 + return 0;
584 588 }
585 589 adapter->current_op = VIRTCHNL_OP_ADD_ETH_ADDR;
586 590
@@ -594,8 +598,9 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter)
594 598
595 599 veal = kzalloc(len, GFP_ATOMIC);
596 600 if (!veal) {
601 + adapter->current_op = VIRTCHNL_OP_UNKNOWN;
597 602 spin_unlock_bh(&adapter->mac_vlan_list_lock);
598 - return;
603 + return -ENOMEM;
599 604 }
600 605
601 606 veal->vsi_id = adapter->vsi_res->vsi_id;
@@ -615,8 +620,15 @@ void iavf_add_ether_addrs(struct iavf_adapter *adapter)
615 620
616 621 spin_unlock_bh(&adapter->mac_vlan_list_lock);
617 622
618 - iavf_send_pf_msg(adapter, VIRTCHNL_OP_ADD_ETH_ADDR, (u8 *)veal, len);
623 + ret = iavf_send_pf_msg(adapter, VIRTCHNL_OP_ADD_ETH_ADDR, (u8 *)veal, len);
619 624 kfree(veal);
625 + if (ret) {
626 + dev_err(&adapter->pdev->dev,
627 + "Unable to send ADD_ETH_ADDR message to PF, error %d\n", ret);
628 + adapter->current_op = VIRTCHNL_OP_UNKNOWN;
629 + }
630 +
631 + return ret;
620 632 }
621 633
622 634 /**
@@ -712,8 +724,8 @@ static void iavf_mac_add_ok(struct iavf_adapter *adapter)
712 724 * @adapter: adapter structure
713 725 *
714 726 * Remove filters from list based on PF response.
715 - **/
716 - static void iavf_mac_add_reject(struct iavf_adapter *adapter)
727 + */
728 + void iavf_mac_add_reject(struct iavf_adapter *adapter)
717 729 {
718 730 struct net_device *netdev = adapter->netdev;
719 731 struct iavf_mac_filter *f, *ftmp;
@@ -2364,7 +2376,6 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter,
2364 2376 iavf_mac_add_reject(adapter);
2365 2377 /* restore administratively set MAC address */
2366 2378 ether_addr_copy(adapter->hw.mac.addr, netdev->dev_addr);
2367 - wake_up(&adapter->vc_waitqueue);
2368 2379 break;
2369 2380 case VIRTCHNL_OP_DEL_ETH_ADDR:
2370 2381 dev_err(&adapter->pdev->dev, "Failed to delete MAC filter, error %s\n",
@@ -2555,7 +2566,6 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter,
2555 2566 eth_hw_addr_set(netdev, adapter->hw.mac.addr);
2556 2567 netif_addr_unlock_bh(netdev);
2557 2568 }
2558 - wake_up(&adapter->vc_waitqueue);
2559 2569 break;
2560 2570 case VIRTCHNL_OP_GET_STATS: {
2561 2571 struct iavf_eth_stats *stats =
@@ -2950,3 +2960,72 @@ void iavf_virtchnl_completion(struct iavf_adapter *adapter,
2950 2960 } /* switch v_opcode */
2951 2961 adapter->current_op = VIRTCHNL_OP_UNKNOWN;
2952 2962 }
2963 +
2964 + /**
2965 + * iavf_poll_virtchnl_response - Poll admin queue for virtchnl response
2966 + * @adapter: adapter structure
2967 + * @event: pre-allocated event buffer to use for polling
2968 + * @condition: callback to check if desired response received
2969 + * @cond_data: context data passed to condition callback
2970 + * @timeout_ms: maximum time to wait in milliseconds
2971 + *
2972 + * Polls the admin queue and processes all incoming virtchnl messages.
2973 + * After processing each valid message, calls the condition callback to check
2974 + * if the expected response has been received. The callback receives the opcode
2975 + * of the processed message to identify which response was received. Continues
2976 + * polling until the callback returns true or timeout expires.
2977 + *
2978 + * Caller must allocate event buffer before sending any messages to PF to avoid
2979 + * state mismatch if allocation fails after message is sent.
2980 + *
2981 + * Caller must hold netdev_lock. This can sleep for up to timeout_ms while
2982 + * polling hardware.
2983 + *
2984 + * Return: 0 on success (condition met), -EAGAIN on timeout, or error code
2985 + */
2986 + int iavf_poll_virtchnl_response(struct iavf_adapter *adapter,
2987 + struct iavf_arq_event_info *event,
2988 + bool (*condition)(struct iavf_adapter *adapter,
2989 + const void *data,
2990 + enum virtchnl_ops v_op),
2991 + const void *cond_data,
2992 + unsigned int timeout_ms)
2993 + {
2994 + struct iavf_hw *hw = &adapter->hw;
2995 + enum virtchnl_ops received_op;
2996 + unsigned long timeout;
2997 + int ret = -EAGAIN;
2998 + u16 pending = 0;
2999 + u32 v_retval;
3000 +
3001 + netdev_assert_locked(adapter->netdev);
3002 +
3003 + timeout = jiffies + msecs_to_jiffies(timeout_ms);
3004 + do {
3005 + if (!pending)
3006 + usleep_range(50, 75);
3007 +
3008 + if (iavf_clean_arq_element(hw, event, &pending) == IAVF_SUCCESS) {
3009 + received_op = (enum virtchnl_ops)le32_to_cpu(event->desc.cookie_high);
3010 + if (received_op != VIRTCHNL_OP_UNKNOWN) {
3011 + v_retval = le32_to_cpu(event->desc.cookie_low);
3012 +
3013 + iavf_virtchnl_completion(adapter, received_op,
3014 + (enum iavf_status)v_retval,
3015 + event->msg_buf, event->msg_len);
3016 +
3017 + if (condition(adapter, cond_data, received_op)) {
3018 + ret = 0;
3019 + break;
3020 + }
3021 + }
3022 +
3023 + memset(event->msg_buf, 0, IAVF_MAX_AQ_BUF_SIZE);
3024 +
3025 + if (pending)
3026 + continue;
3027 + }
3028 + } while (time_before(jiffies, timeout));
3029 +
3030 + return ret;
3031 + }
modified drivers/net/ethernet/intel/ice/devlink/port.c
@@ -590,8 +590,8 @@ static void ice_dealloc_dynamic_port(struct ice_dynamic_port *dyn_port)
590 590
591 591 xa_erase(&pf->sf_nums, devlink_port->attrs.pci_sf.sf);
592 592 ice_eswitch_detach_sf(pf, dyn_port);
593 - ice_vsi_free(dyn_port->vsi);
594 593 xa_erase(&pf->dyn_ports, dyn_port->vsi->idx);
594 + ice_vsi_free(dyn_port->vsi);
595 595 kfree(dyn_port);
596 596 }
597 597
modified drivers/net/ethernet/intel/ice/ice_eswitch.c
@@ -95,7 +95,7 @@ ice_eswitch_release_repr(struct ice_pf *pf, struct ice_repr *repr)
95 95 return;
96 96
97 97 ice_vsi_update_security(vsi, ice_vsi_ctx_set_antispoof);
98 - metadata_dst_free(repr->dst);
98 + dst_release(&repr->dst->dst);
99 99 repr->dst = NULL;
100 100 ice_fltr_add_mac_and_broadcast(vsi, repr->parent_mac,
101 101 ICE_FWD_TO_VSI);
modified drivers/net/ethernet/intel/ice/ice_sriov.c
@@ -1366,6 +1366,20 @@ int ice_set_vf_mac(struct net_device *netdev, int vf_id, u8 *mac)
1366 1366 return __ice_set_vf_mac(ice_netdev_to_pf(netdev), vf_id, mac);
1367 1367 }
1368 1368
1369 + /**
1370 + * ice_setup_vf_trust - Enable/disable VF trust mode without reset
1371 + * @vf: VF to configure
1372 + * @setting: trust setting
1373 + *
1374 + * Update VF flags when changing trust without performing a VF reset.
1375 + * This is only called when it's safe to skip the reset (VF has no advanced
1376 + * features configured that need cleanup).
1377 + */
1378 + static void ice_setup_vf_trust(struct ice_vf *vf, bool setting)
1379 + {
1380 + assign_bit(ICE_VIRTCHNL_VF_CAP_PRIVILEGE, &vf->vf_caps, setting);
1381 + }
1382 +
1369 1383 /**
1370 1384 * ice_set_vf_trust
1371 1385 * @netdev: network interface device structure
@@ -1401,11 +1415,19 @@ int ice_set_vf_trust(struct net_device *netdev, int vf_id, bool trusted)
1401 1415
1402 1416 mutex_lock(&vf->cfg_lock);
1403 1417
1404 - while (!trusted && vf->num_mac_lldp)
1405 - ice_vf_update_mac_lldp_num(vf, ice_get_vf_vsi(vf), false);
1406 -
1407 - vf->trusted = trusted;
1408 - ice_reset_vf(vf, ICE_VF_RESET_NOTIFY);
1418 + /* Reset only if revoking trust and VF has advanced features configured */
1419 + if (!trusted &&
1420 + (vf->num_mac_lldp > 0 ||
1421 + test_bit(ICE_VF_STATE_UC_PROMISC, vf->vf_states) ||
1422 + test_bit(ICE_VF_STATE_MC_PROMISC, vf->vf_states))) {
1423 + while (vf->num_mac_lldp)
1424 + ice_vf_update_mac_lldp_num(vf, ice_get_vf_vsi(vf), false);
1425 + vf->trusted = trusted;
1426 + ice_reset_vf(vf, ICE_VF_RESET_NOTIFY);
1427 + } else {
1428 + vf->trusted = trusted;
1429 + ice_setup_vf_trust(vf, trusted);
1430 + }
1409 1431 dev_info(ice_pf_to_dev(pf), "VF %u is now %strusted\n",
1410 1432 vf_id, trusted ? "" : "un");
1411 1433
modified drivers/net/ethernet/intel/ice/ice_txrx.c
@@ -1561,10 +1561,10 @@ ice_tx_map(struct ice_tx_ring *tx_ring, struct ice_tx_buf *first,
1561 1561 }
1562 1562 }
1563 1563 tstamp_ring->next_to_use = j;
1564 - writel_relaxed(j, tstamp_ring->tail);
1564 + writel(j, tstamp_ring->tail);
1565 1565 } else {
1566 1566 ring_kick:
1567 - writel_relaxed(i, tx_ring->tail);
1567 + writel(i, tx_ring->tail);
1568 1568 }
1569 1569 return;
1570 1570
modified drivers/net/ethernet/marvell/mv643xx_eth.c
@@ -3171,6 +3171,8 @@ static int mv643xx_eth_probe(struct platform_device *pdev)
3171 3171 netif_set_real_num_tx_queues(dev, mp->txq_count);
3172 3172 netif_set_real_num_rx_queues(dev, mp->rxq_count);
3173 3173
3174 + dev->netdev_ops = &mv643xx_eth_netdev_ops;
3175 +
3174 3176 err = 0;
3175 3177 if (pd->phy_node) {
3176 3178 phydev = of_phy_connect(mp->dev, pd->phy_node,
@@ -3221,8 +3223,6 @@ static int mv643xx_eth_probe(struct platform_device *pdev)
3221 3223 }
3222 3224 dev->irq = irq;
3223 3225
3224 - dev->netdev_ops = &mv643xx_eth_netdev_ops;
3225 -
3226 3226 dev->watchdog_timeo = 2 * HZ;
3227 3227 dev->base_addr = 0;
3228 3228
modified drivers/net/ethernet/mellanox/mlx5/core/en_rx.c
@@ -908,10 +908,12 @@ int mlx5e_poll_ico_cq(struct mlx5e_cq *cq)
908 908 } while (!last_wqe);
909 909 } while ((++i < MLX5E_TX_CQ_POLL_BUDGET) && (cqe = mlx5_cqwq_get_cqe(&cq->wq)));
910 910
911 - sq->cc = sqcc;
912 -
913 911 mlx5_cqwq_update_db_record(&cq->wq);
914 912
913 + /* ensure cq space is freed before enabling more cqes */
914 + dma_wmb();
915 +
916 + sq->cc = sqcc;
915 917 return i;
916 918 }
917 919
modified drivers/net/ethernet/mellanox/mlx5/core/esw/adj_vport.c
@@ -11,26 +11,6 @@ int mlx5_esw_adj_vport_modify(struct mlx5_core_dev *dev, u16 vport,
11 11
12 12 lockdep_assert_held(&dev->priv.eswitch->state_lock);
13 13
14 - if (MLX5_CAP_ESW(dev, esw_vport_state_max_tx_speed)) {
15 - u8 op_mod = MLX5_VPORT_STATE_OP_MOD_ESW_VPORT;
16 - struct mlx5_vport *esw_vport;
17 - u32 speed = 0;
18 - int err;
19 -
20 - err = mlx5_query_vport_max_tx_speed(dev, op_mod, vport,
21 - true, &speed, NULL);
22 - if (err) {
23 - esw_vport = mlx5_eswitch_get_vport(dev->priv.eswitch,
24 - vport);
25 - speed = IS_ERR(esw_vport) ? 0 :
26 - esw_vport->agg_max_tx_speed;
27 - mlx5_core_dbg(dev,
28 - "Failed to query vport %d max tx speed, err=%d, using cached %u\n",
29 - vport, err, speed);
30 - }
31 - MLX5_SET(modify_vport_state_in, in, max_tx_speed, speed);
32 - }
33 -
34 14 MLX5_SET(modify_vport_state_in, in, opcode,
35 15 MLX5_CMD_OP_MODIFY_VPORT_STATE);
36 16 MLX5_SET(modify_vport_state_in, in, op_mod,
modified drivers/net/ethernet/mellanox/mlx5/core/lag/lag.c
@@ -1432,30 +1432,40 @@ static bool mlx5_lag_should_disable_lag(struct mlx5_lag *ldev, bool do_bond)
1432 1432 }
1433 1433
1434 1434 #ifdef CONFIG_MLX5_ESWITCH
1435 - static int
1436 - mlx5_lag_sum_devices_speed(struct mlx5_lag *ldev, u32 *sum_speed,
1437 - int (*get_speed)(struct mlx5_core_dev *, u32 *))
1435 + static int mlx5_lag_get_devices_oper_speed(struct mlx5_lag *ldev,
1436 + u32 *sum_speed)
1438 1437 {
1439 - struct mlx5_core_dev *pf_mdev;
1440 - struct lag_func *pf;
1441 1438 int pf_idx;
1442 - u32 speed;
1443 - int ret;
1444 1439
1445 1440 *sum_speed = 0;
1446 1441 mlx5_ldev_for_each(pf_idx, 0, ldev) {
1442 + u8 opmod = MLX5_VPORT_STATE_OP_MOD_VNIC_VPORT;
1443 + struct mlx5_core_dev *pf_mdev;
1444 + struct lag_func *pf;
1445 + u32 speed;
1446 + u8 state;
1447 + int ret;
1448 +
1447 1449 pf = mlx5_lag_pf(ldev, pf_idx);
1448 1450 if (!pf)
1449 1451 continue;
1450 1452 pf_mdev = pf->dev;
1451 1453 if (!pf_mdev)
1452 1454 continue;
1455 + ret = mlx5_query_vport_max_tx_speed(pf_mdev, opmod, 0, 0,
1456 + &speed, &state);
1457 + if (ret) {
1458 + mlx5_core_dbg(pf_mdev, "State query failed (err=%d)\n",
1459 + ret);
1460 + return ret;
1461 + }
1462 + if (state != VPORT_STATE_UP)
1463 + continue;
1453 1464
1454 - ret = get_speed(pf_mdev, &speed);
1465 + ret = mlx5_port_oper_linkspeed(pf_mdev, &speed);
1455 1466 if (ret) {
1456 1467 mlx5_core_dbg(pf_mdev,
1457 - "Failed to get device speed using %ps. Device %s speed is not available (err=%d)\n",
1458 - get_speed, dev_name(pf_mdev->device),
1468 + "Failed to get oper speed (err=%d)\n",
1459 1469 ret);
1460 1470 return ret;
1461 1471 }
@@ -1466,17 +1476,42 @@ mlx5_lag_sum_devices_speed(struct mlx5_lag *ldev, u32 *sum_speed,
1466 1476 return 0;
1467 1477 }
1468 1478
1469 - static int mlx5_lag_sum_devices_max_speed(struct mlx5_lag *ldev, u32 *max_speed)
1479 + static int mlx5_lag_get_devices_max_speed(struct mlx5_lag *ldev, u32 *max_speed)
1470 1480 {
1471 - return mlx5_lag_sum_devices_speed(ldev, max_speed,
1472 - mlx5_port_max_linkspeed);
1473 - }
1481 + bool take_max;
1482 + int pf_idx;
1474 1483
1475 - static int mlx5_lag_sum_devices_oper_speed(struct mlx5_lag *ldev,
1476 - u32 *oper_speed)
1477 - {
1478 - return mlx5_lag_sum_devices_speed(ldev, oper_speed,
1479 - mlx5_port_oper_linkspeed);
1484 + take_max = ldev->tracker.tx_type == NETDEV_LAG_TX_TYPE_ACTIVEBACKUP;
1485 + if (ldev->mode == MLX5_LAG_MODE_MPESW)
1486 + take_max = false;
1487 +
1488 + *max_speed = 0;
1489 + mlx5_ldev_for_each(pf_idx, 0, ldev) {
1490 + struct mlx5_core_dev *pf_mdev;
1491 + struct lag_func *pf;
1492 + u32 speed;
1493 + int ret;
1494 +
1495 + pf = mlx5_lag_pf(ldev, pf_idx);
1496 + if (!pf)
1497 + continue;
1498 + pf_mdev = pf->dev;
1499 + if (!pf_mdev)
1500 + continue;
1501 +
1502 + ret = mlx5_port_max_linkspeed(pf_mdev, &speed);
1503 + if (ret) {
1504 + mlx5_core_dbg(pf_mdev,
1505 + "Failed to get max speed (err=%d)\n",
1506 + ret);
1507 + return ret;
1508 + }
1509 +
1510 + *max_speed = take_max ?
1511 + max(*max_speed, speed) : *max_speed + speed;
1512 + }
1513 +
1514 + return 0;
1480 1515 }
1481 1516
1482 1517 static void mlx5_lag_modify_device_vports_speed(struct mlx5_core_dev *mdev,
@@ -1525,7 +1560,7 @@ void mlx5_lag_set_vports_agg_speed(struct mlx5_lag *ldev)
1525 1560 int pf_idx;
1526 1561
1527 1562 if (ldev->mode == MLX5_LAG_MODE_MPESW) {
1528 - if (mlx5_lag_sum_devices_oper_speed(ldev, &speed))
1563 + if (mlx5_lag_get_devices_oper_speed(ldev, &speed))
1529 1564 return;
1530 1565 } else {
1531 1566 speed = ldev->tracker.bond_speed_mbps;
@@ -1533,8 +1568,8 @@ void mlx5_lag_set_vports_agg_speed(struct mlx5_lag *ldev)
1533 1568 return;
1534 1569 }
1535 1570
1536 - /* If speed is not set, use the sum of max speeds of all PFs */
1537 - if (!speed && mlx5_lag_sum_devices_max_speed(ldev, &speed))
1571 + /* If speed is not set, fall back to the max achievable speed */
1572 + if (!speed && mlx5_lag_get_devices_max_speed(ldev, &speed))
1538 1573 return;
1539 1574
1540 1575 speed = speed / MLX5_MAX_TX_SPEED_UNIT;
modified drivers/net/ethernet/mellanox/mlx5/core/steering/hws/fs_hws.c
@@ -928,6 +928,7 @@ static int mlx5_fs_fte_get_hws_actions(struct mlx5_flow_root_namespace *ns,
928 928 goto free_actions;
929 929 }
930 930 (*ractions)[num_actions].aso_meter.offset =
931 + (fte_action->exe_aso.object_id - fte_action->exe_aso.base_id) * 2 +
931 932 fte_action->exe_aso.flow_meter.meter_idx;
932 933 (*ractions)[num_actions].aso_meter.init_color =
933 934 fte_action->exe_aso.flow_meter.init_color;
@@ -1398,8 +1399,8 @@ static void mlx5_cmd_hws_packet_reformat_dealloc(struct mlx5_flow_root_namespace
1398 1399 pr_data->data_size);
1399 1400 break;
1400 1401 case MLX5_REFORMAT_TYPE_L2_TO_L3_TUNNEL:
1401 - pr_pool = mlx5_fs_get_pr_encap_pool(dev, &hws_pool->el2tol2tnl_pools,
1402 - MLX5HWS_ACTION_TYP_REFORMAT_L2_TO_TNL_L2,
1402 + pr_pool = mlx5_fs_get_pr_encap_pool(dev, &hws_pool->el2tol3tnl_pools,
1403 + MLX5HWS_ACTION_TYP_REFORMAT_L2_TO_TNL_L3,
1403 1404 pr_data->data_size);
1404 1405 break;
1405 1406 case MLX5_REFORMAT_TYPE_L3_TUNNEL_TO_L2:
modified drivers/net/ethernet/mellanox/mlx5/core/vport.c
@@ -93,30 +93,6 @@ int mlx5_modify_vport_admin_state(struct mlx5_core_dev *mdev, u8 opmod,
93 93 lockdep_assert_held(&mdev->priv.eswitch->state_lock);
94 94 #endif
95 95
96 - if (MLX5_CAP_ESW(mdev, esw_vport_state_max_tx_speed) &&
97 - opmod == MLX5_VPORT_STATE_OP_MOD_ESW_VPORT &&
98 - vport != MLX5_VPORT_UPLINK) {
99 - u32 speed = 0;
100 - int err;
101 -
102 - err = mlx5_query_vport_max_tx_speed(mdev, opmod, vport,
103 - other_vport, &speed, NULL);
104 - if (err) {
105 - #ifdef CONFIG_MLX5_ESWITCH
106 - struct mlx5_vport *esw_vport;
107 -
108 - esw_vport = mlx5_eswitch_get_vport(mdev->priv.eswitch,
109 - vport);
110 - speed = IS_ERR(esw_vport) ? 0 :
111 - esw_vport->agg_max_tx_speed;
112 - #endif
113 - mlx5_core_dbg(mdev,
114 - "Failed to query vport %d max tx speed, err=%d, using cached %u\n",
115 - vport, err, speed);
116 - }
117 - MLX5_SET(modify_vport_state_in, in, max_tx_speed, speed);
118 - }
119 -
120 96 MLX5_SET(modify_vport_state_in, in, opcode,
121 97 MLX5_CMD_OP_MODIFY_VPORT_STATE);
122 98 MLX5_SET(modify_vport_state_in, in, op_mod, opmod);
modified drivers/net/ethernet/mellanox/mlxsw/spectrum.h
@@ -989,6 +989,8 @@ void mlxsw_sp_acl_ruleset_prio_get(struct mlxsw_sp_acl_ruleset *ruleset,
989 989 struct mlxsw_sp_acl_rule_info *
990 990 mlxsw_sp_acl_rulei_create(struct mlxsw_sp_acl *acl,
991 991 struct mlxsw_afa_block *afa_block);
992 + void mlxsw_sp_acl_rulei_free(struct mlxsw_sp *mlxsw_sp,
993 + const struct mlxsw_sp_acl_rule_info *rulei);
992 994 void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp,
993 995 struct mlxsw_sp_acl_rule_info *rulei);
994 996 int mlxsw_sp_acl_rulei_commit(struct mlxsw_sp_acl_rule_info *rulei);
modified drivers/net/ethernet/mellanox/mlxsw/spectrum_acl.c
@@ -340,8 +340,8 @@ err_afa_block_create:
340 340 return ERR_PTR(err);
341 341 }
342 342
343 - void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp,
344 - struct mlxsw_sp_acl_rule_info *rulei)
343 + void mlxsw_sp_acl_rulei_free(struct mlxsw_sp *mlxsw_sp,
344 + const struct mlxsw_sp_acl_rule_info *rulei)
345 345 {
346 346 if (rulei->action_created)
347 347 mlxsw_afa_block_destroy(rulei->act_block);
@@ -351,6 +351,12 @@ void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp,
351 351 if (rulei->dst_port_range_reg_valid)
352 352 mlxsw_sp_port_range_reg_put(mlxsw_sp,
353 353 rulei->dst_port_range_reg_index);
354 + }
355 +
356 + void mlxsw_sp_acl_rulei_destroy(struct mlxsw_sp *mlxsw_sp,
357 + struct mlxsw_sp_acl_rule_info *rulei)
358 + {
359 + mlxsw_sp_acl_rulei_free(mlxsw_sp, rulei);
354 360 kfree(rulei);
355 361 }
356 362
modified drivers/net/ethernet/mellanox/mlxsw/spectrum_flower.c
@@ -862,14 +862,19 @@ int mlxsw_sp_flower_tmplt_create(struct mlxsw_sp *mlxsw_sp,
862 862 memset(&rulei, 0, sizeof(rulei));
863 863 err = mlxsw_sp_flower_parse(mlxsw_sp, block, &rulei, f);
864 864 if (err)
865 - return err;
865 + goto out;
866 +
866 867 ruleset = mlxsw_sp_acl_ruleset_get(mlxsw_sp, block,
867 868 f->common.chain_index,
868 869 MLXSW_SP_ACL_PROFILE_FLOWER,
869 870 &rulei.values.elusage);
871 + err = PTR_ERR_OR_ZERO(ruleset);
872 +
873 + out:
874 + mlxsw_sp_acl_rulei_free(mlxsw_sp, &rulei);
870 875
871 876 /* keep the reference to the ruleset */
872 - return PTR_ERR_OR_ZERO(ruleset);
877 + return err;
873 878 }
874 879
875 880 void mlxsw_sp_flower_tmplt_destroy(struct mlxsw_sp *mlxsw_sp,
modified drivers/net/ethernet/microchip/lan865x/lan865x.c
@@ -346,6 +346,8 @@ static int lan865x_probe(struct spi_device *spi)
346 346 spi_set_drvdata(spi, priv);
347 347 INIT_WORK(&priv->multicast_work, lan865x_multicast_work_handler);
348 348
349 + netdev->netdev_ops = &lan865x_netdev_ops;
350 +
349 351 priv->tc6 = oa_tc6_init(spi, netdev, NULL);
350 352 if (!priv->tc6) {
351 353 ret = -ENODEV;
@@ -397,7 +399,6 @@ static int lan865x_probe(struct spi_device *spi)
397 399
398 400 netdev->if_port = IF_PORT_10BASET;
399 401 netdev->irq = spi->irq;
400 - netdev->netdev_ops = &lan865x_netdev_ops;
401 402 netdev->ethtool_ops = &lan865x_ethtool_ops;
402 403
403 404 ret = register_netdev(netdev);
modified drivers/net/ethernet/microchip/sparx5/sparx5_ptp.c
@@ -622,18 +622,9 @@ int sparx5_ptp_init(struct sparx5 *sparx5)
622 622 sparx5->ptp = 1;
623 623 }
624 624
625 - if (!sparx5->ptp)
626 - return 0;
627 -
628 - for (i = 0; i < SPARX5_PHC_COUNT; ++i) {
629 - err = sparx5_ptp_phc_init(sparx5, i, &sparx5_ptp_clock_info);
630 - if (err)
631 - return err;
632 - }
633 -
634 - spin_lock_init(&sparx5->ptp_clock_lock);
635 - spin_lock_init(&sparx5->ptp_ts_id_lock);
636 - mutex_init(&sparx5->ptp_lock);
625 + /* The base, non-PTP-capable lan969x variants need the
626 + * first TOD counter running to forward frames.
627 + */
637 628
638 629 /* Disable master counters */
639 630 spx5_wr(PTP_PTP_DOM_CFG_PTP_ENA_SET(0), sparx5, PTP_PTP_DOM_CFG);
@@ -657,6 +648,19 @@ int sparx5_ptp_init(struct sparx5 *sparx5)
657 648 /* Enable master counters */
658 649 spx5_wr(PTP_PTP_DOM_CFG_PTP_ENA_SET(0x7), sparx5, PTP_PTP_DOM_CFG);
659 650
651 + if (!sparx5->ptp)
652 + return 0;
653 +
654 + for (i = 0; i < SPARX5_PHC_COUNT; ++i) {
655 + err = sparx5_ptp_phc_init(sparx5, i, &sparx5_ptp_clock_info);
656 + if (err)
657 + return err;
658 + }
659 +
660 + spin_lock_init(&sparx5->ptp_clock_lock);
661 + spin_lock_init(&sparx5->ptp_ts_id_lock);
662 + mutex_init(&sparx5->ptp_lock);
663 +
660 664 for (i = 0; i < sparx5->data->consts->n_ports; i++) {
661 665 port = sparx5->ports[i];
662 666 if (!port)
modified drivers/net/ethernet/microchip/sparx5/sparx5_tc_matchall.c
@@ -160,6 +160,7 @@ static int sparx5_tc_matchall_destroy(struct net_device *ndev,
160 160 }
161 161
162 162 list_del(&entry->list);
163 + kfree(entry);
163 164
164 165 return err;
165 166 }
modified drivers/net/ethernet/microsoft/mana/mana_bpf.c
@@ -91,7 +91,7 @@ u32 mana_run_xdp(struct net_device *ndev, struct mana_rxq *rxq,
91 91 goto out;
92 92
93 93 xdp_init_buff(xdp, PAGE_SIZE, &rxq->xdp_rxq);
94 - xdp_prepare_buff(xdp, buf_va, XDP_PACKET_HEADROOM, pkt_len, true);
94 + xdp_prepare_buff(xdp, buf_va, rxq->headroom, pkt_len, true);
95 95
96 96 act = bpf_prog_run_xdp(prog, xdp);
97 97
@@ -183,9 +183,9 @@ static int mana_xdp_set(struct net_device *ndev, struct bpf_prog *prog,
183 183 if (!old_prog && !prog)
184 184 return 0;
185 185
186 - if (prog && ndev->mtu > MANA_XDP_MTU_MAX) {
186 + if (prog && ndev->mtu > MANA_XDP_MTU_MAX(ndev)) {
187 187 netdev_err(ndev, "XDP: mtu:%u too large, mtu_max:%lu\n",
188 - ndev->mtu, MANA_XDP_MTU_MAX);
188 + ndev->mtu, MANA_XDP_MTU_MAX(ndev));
189 189 NL_SET_ERR_MSG_MOD(extack, "XDP: mtu too large");
190 190
191 191 return -EOPNOTSUPP;
@@ -238,7 +238,7 @@ static int mana_xdp_set(struct net_device *ndev, struct bpf_prog *prog,
238 238 bpf_prog_put(old_prog);
239 239
240 240 if (prog)
241 - ndev->max_mtu = min_t(unsigned int, MANA_XDP_MTU_MAX,
241 + ndev->max_mtu = min_t(unsigned int, MANA_XDP_MTU_MAX(ndev),
242 242 gc->adapter_mtu - ETH_HLEN);
243 243 else
244 244 ndev->max_mtu = gc->adapter_mtu - ETH_HLEN;
modified drivers/net/ethernet/microsoft/mana/mana_en.c
@@ -758,6 +758,44 @@ static void *mana_get_rxbuf_pre(struct mana_rxq *rxq, dma_addr_t *da)
758 758 return va;
759 759 }
760 760
761 + /* Reserve enough headroom to satisfy the skb_cow() in ip_forward() and avoid
762 + * reallocation: the TX path keeps the SGE DMA mappings in struct mana_skb_head
763 + * at skb->head, so the port advertises ndev->needed_headroom = MANA_HEADROOM.
764 + */
765 + static u32 mana_get_rxbuf_headroom(struct mana_port_context *apc)
766 + {
767 + if (mana_xdp_get(apc))
768 + return mana_xdp_headroom(apc->ndev);
769 +
770 + return LL_RESERVED_SPACE(apc->ndev);
771 + }
772 +
773 + static u32 mana_get_rxbuf_size(struct mana_port_context *apc, u32 mtu)
774 + {
775 + u32 len = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD +
776 + mana_get_rxbuf_headroom(apc));
777 +
778 + return ALIGN(len, MANA_RX_FRAG_ALIGNMENT);
779 + }
780 +
781 + /* Returns true when one RX buffer per page is already required by XDP or by
782 + * the buffer size implied by the MTU, i.e. regardless of the
783 + * MANA_PRIV_FLAG_USE_FULL_PAGE_RXBUF private flag.
784 + */
785 + bool mana_single_rxbuf_per_page_forced(struct mana_port_context *apc, u32 mtu)
786 + {
787 + /* For xdp make sure only one packet fits per page. */
788 + if (mana_xdp_get(apc))
789 + return true;
790 +
791 + /* Only use the page_pool fragment path when at least two buffers,
792 + * including the headroom each of them has to reserve, actually fit
793 + * into one page. Otherwise the fragment path degenerates into one
794 + * buffer per page while still paying the fragment accounting cost.
795 + */
796 + return PAGE_SIZE / mana_get_rxbuf_size(apc, mtu) < 2;
797 + }
798 +
761 799 static bool
762 800 mana_use_single_rxbuf_per_page(struct mana_port_context *apc, u32 mtu)
763 801 {
@@ -770,32 +808,27 @@ mana_use_single_rxbuf_per_page(struct mana_port_context *apc, u32 mtu)
770 808 if (apc->priv_flags & BIT(MANA_PRIV_FLAG_USE_FULL_PAGE_RXBUF))
771 809 return true;
772 810
773 - /* For xdp and jumbo frames make sure only one packet fits per page. */
774 - if (mtu + MANA_RXBUF_PAD > PAGE_SIZE / 2 || mana_xdp_get(apc))
775 - return true;
776 -
777 - return false;
811 + return mana_single_rxbuf_per_page_forced(apc, mtu);
778 812 }
779 813
780 - /* Get RX buffer's data size, alloc size, XDP headroom based on MTU */
814 + /* Get RX buffer's data size, alloc size, headroom and frag count based on MTU */
781 815 static void mana_get_rxbuf_cfg(struct mana_port_context *apc,
782 816 int mtu, u32 *datasize, u32 *alloc_size,
783 817 u32 *headroom, u32 *frag_count)
784 818 {
785 - u32 len, buf_size;
819 + u32 buf_size;
786 820
787 821 /* Calculate datasize first (consistent across all cases) */
788 822 *datasize = mtu + ETH_HLEN;
789 823
824 + *headroom = mana_get_rxbuf_headroom(apc);
825 +
790 826 if (mana_use_single_rxbuf_per_page(apc, mtu)) {
791 - if (mana_xdp_get(apc)) {
792 - *headroom = XDP_PACKET_HEADROOM;
827 + if (mana_xdp_get(apc))
793 828 *alloc_size = PAGE_SIZE;
794 - } else {
795 - *headroom = 0; /* no support for XDP */
829 + else
796 830 *alloc_size = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD +
797 831 *headroom);
798 - }
799 832
800 833 *frag_count = 1;
801 834
@@ -809,11 +842,7 @@ static void mana_get_rxbuf_cfg(struct mana_port_context *apc,
809 842 }
810 843
811 844 /* Standard MTU case - optimize for multiple packets per page */
812 - *headroom = 0;
813 -
814 - /* Calculate base buffer size needed */
815 - len = SKB_DATA_ALIGN(mtu + MANA_RXBUF_PAD + *headroom);
816 - buf_size = ALIGN(len, MANA_RX_FRAG_ALIGNMENT);
845 + buf_size = mana_get_rxbuf_size(apc, mtu);
817 846
818 847 /* Calculate how many packets can fit in a page */
819 848 *frag_count = PAGE_SIZE / buf_size;
modified drivers/net/ethernet/microsoft/mana/mana_ethtool.c
@@ -815,12 +815,12 @@ static int mana_set_priv_flags(struct net_device *ndev, u32 priv_flags)
815 815 if (!apc->port_is_up)
816 816 return 0;
817 817
818 - /* If XDP is attached or MTU is jumbo, single-buffer-per-page
819 - * is already forced regardless of this flag. Skip the
820 - * expensive detach/attach cycle since nothing changes.
818 + /* If XDP is attached or the MTU already forces one buffer per
819 + * page, single-buffer-per-page is used regardless of this
820 + * flag. Skip the expensive detach/attach cycle since nothing
821 + * changes.
821 822 */
822 - if (ndev->mtu + MANA_RXBUF_PAD > PAGE_SIZE / 2 ||
823 - mana_xdp_get(apc))
823 + if (mana_single_rxbuf_per_page_forced(apc, ndev->mtu))
824 824 return 0;
825 825
826 826 /* Block RDMA from grabbing the vport during detach/attach */
modified drivers/net/ethernet/stmicro/stmmac/dwmac1000_core.c
@@ -312,6 +312,12 @@ static int dwmac1000_irq_status(struct stmmac_priv *priv,
312 312 if (intr_status & (PCS_ANE_IRQ | PCS_LINK_IRQ))
313 313 stmmac_integrated_pcs_irq(priv, intr_status, x);
314 314
315 + /* Reading RGSMIIIS clears the interrupt the MAC reset unmasks. */
316 + if (intr_status & PCS_RGSMIIIS_IRQ) {
317 + readl(ioaddr + GMAC_RGSMIIIS);
318 + x->irq_rgmii_n++;
319 + }
320 +
315 321 return ret;
316 322 }
317 323
modified drivers/net/ethernet/stmicro/stmmac/hwif.h
@@ -633,7 +633,7 @@ struct stmmac_est_ops {
633 633 struct stmmac_vlan_ops {
634 634 /* VLAN */
635 635 void (*update_vlan_hash)(struct mac_device_info *hw, u32 hash,
636 - u16 perfect_match, bool is_double);
636 + bool is_svlan);
637 637 void (*enable_vlan)(struct mac_device_info *hw, u32 type);
638 638 void (*rx_hw_vlan)(struct mac_device_info *hw, struct dma_desc *rx_desc,
639 639 struct sk_buff *skb);
modified drivers/net/ethernet/stmicro/stmmac/stmmac.h
@@ -344,7 +344,7 @@ struct stmmac_priv {
344 344 void __iomem *ptpaddr;
345 345 void __iomem *estaddr;
346 346 unsigned long active_vlans[BITS_TO_LONGS(VLAN_N_VID)];
347 - unsigned int num_double_vlans;
347 + unsigned int num_svlans;
348 348 int sfty_irq;
349 349 struct stmmac_msi *msi;
350 350
modified drivers/net/ethernet/stmicro/stmmac/stmmac_main.c
@@ -6226,6 +6226,13 @@ static netdev_features_t stmmac_fix_features(struct net_device *dev,
6226 6226 if (priv->plat->bugged_jumbo && (dev->mtu > ETH_DATA_LEN))
6227 6227 features &= ~NETIF_F_CSUM_MASK;
6228 6228
6229 + if (priv->plat->core_type == DWMAC_CORE_XGMAC) {
6230 + if (features & NETIF_F_HW_VLAN_CTAG_RX)
6231 + features |= NETIF_F_HW_VLAN_STAG_RX;
6232 + else
6233 + features &= ~NETIF_F_HW_VLAN_STAG_RX;
6234 + }
6235 +
6229 6236 return features;
6230 6237 }
6231 6238
@@ -6850,32 +6857,21 @@ static u32 stmmac_vid_crc32_le(__le16 vid_le)
6850 6857 return crc;
6851 6858 }
6852 6859
6853 - static int stmmac_vlan_update(struct stmmac_priv *priv, bool is_double)
6860 + static int stmmac_vlan_update(struct stmmac_priv *priv, bool is_svlan)
6854 6861 {
6855 6862 u32 crc, hash = 0;
6856 - u16 pmatch = 0;
6857 - int count = 0;
6858 6863 u16 vid = 0;
6859 6864
6860 6865 for_each_set_bit(vid, priv->active_vlans, VLAN_N_VID) {
6861 6866 __le16 vid_le = cpu_to_le16(vid);
6862 6867 crc = bitrev32(~stmmac_vid_crc32_le(vid_le)) >> 28;
6863 6868 hash |= (1 << crc);
6864 - count++;
6865 - }
6866 -
6867 - if (!priv->dma_cap.vlhash) {
6868 - if (count > 2) /* VID = 0 always passes filter */
6869 - return -EOPNOTSUPP;
6870 -
6871 - pmatch = vid;
6872 - hash = 0;
6873 6869 }
6874 6870
6875 6871 if (!netif_running(priv->dev))
6876 6872 return 0;
6877 6873
6878 - return stmmac_update_vlan_hash(priv, priv->hw, hash, pmatch, is_double);
6874 + return stmmac_update_vlan_hash(priv, priv->hw, hash, is_svlan);
6879 6875 }
6880 6876
6881 6877 /* FIXME: This may need RXC to be running, but it may be called with BH
@@ -6884,8 +6880,8 @@ static int stmmac_vlan_update(struct stmmac_priv *priv, bool is_double)
6884 6880 static int stmmac_vlan_rx_add_vid(struct net_device *ndev, __be16 proto, u16 vid)
6885 6881 {
6886 6882 struct stmmac_priv *priv = netdev_priv(ndev);
6887 - unsigned int num_double_vlans;
6888 - bool is_double = false;
6883 + unsigned int num_svlans;
6884 + bool is_svlan = false;
6889 6885 int ret;
6890 6886
6891 6887 ret = pm_runtime_resume_and_get(priv->device);
@@ -6893,11 +6889,11 @@ static int stmmac_vlan_rx_add_vid(struct net_device *ndev, __be16 proto, u16 vid
6893 6889 return ret;
6894 6890
6895 6891 if (be16_to_cpu(proto) == ETH_P_8021AD)
6896 - is_double = true;
6892 + is_svlan = true;
6897 6893
6898 6894 set_bit(vid, priv->active_vlans);
6899 - num_double_vlans = priv->num_double_vlans + is_double;
6900 - ret = stmmac_vlan_update(priv, num_double_vlans);
6895 + num_svlans = priv->num_svlans + is_svlan;
6896 + ret = stmmac_vlan_update(priv, num_svlans);
6901 6897 if (ret) {
6902 6898 clear_bit(vid, priv->active_vlans);
6903 6899 goto err_pm_put;
@@ -6907,12 +6903,12 @@ static int stmmac_vlan_rx_add_vid(struct net_device *ndev, __be16 proto, u16 vid
6907 6903 ret = stmmac_add_hw_vlan_rx_fltr(priv, ndev, priv->hw, proto, vid);
6908 6904 if (ret) {
6909 6905 clear_bit(vid, priv->active_vlans);
6910 - stmmac_vlan_update(priv, priv->num_double_vlans);
6906 + stmmac_vlan_update(priv, priv->num_svlans);
6911 6907 goto err_pm_put;
6912 6908 }
6913 6909 }
6914 6910
6915 - priv->num_double_vlans = num_double_vlans;
6911 + priv->num_svlans = num_svlans;
6916 6912
6917 6913 err_pm_put:
6918 6914 pm_runtime_put(priv->device);
@@ -6926,8 +6922,8 @@ err_pm_put:
6926 6922 static int stmmac_vlan_rx_kill_vid(struct net_device *ndev, __be16 proto, u16 vid)
6927 6923 {
6928 6924 struct stmmac_priv *priv = netdev_priv(ndev);
6929 - unsigned int num_double_vlans;
6930 - bool is_double = false;
6925 + unsigned int num_svlans;
6926 + bool is_svlan = false;
6931 6927 int ret;
6932 6928
6933 6929 ret = pm_runtime_resume_and_get(priv->device);
@@ -6935,11 +6931,11 @@ static int stmmac_vlan_rx_kill_vid(struct net_device *ndev, __be16 proto, u16 vi
6935 6931 return ret;
6936 6932
6937 6933 if (be16_to_cpu(proto) == ETH_P_8021AD)
6938 - is_double = true;
6934 + is_svlan = true;
6939 6935
6940 6936 clear_bit(vid, priv->active_vlans);
6941 - num_double_vlans = priv->num_double_vlans - is_double;
6942 - ret = stmmac_vlan_update(priv, num_double_vlans);
6937 + num_svlans = priv->num_svlans - is_svlan;
6938 + ret = stmmac_vlan_update(priv, num_svlans);
6943 6939 if (ret) {
6944 6940 set_bit(vid, priv->active_vlans);
6945 6941 goto del_vlan_error;
@@ -6949,12 +6945,12 @@ static int stmmac_vlan_rx_kill_vid(struct net_device *ndev, __be16 proto, u16 vi
6949 6945 ret = stmmac_del_hw_vlan_rx_fltr(priv, ndev, priv->hw, proto, vid);
6950 6946 if (ret) {
6951 6947 set_bit(vid, priv->active_vlans);
6952 - stmmac_vlan_update(priv, priv->num_double_vlans);
6948 + stmmac_vlan_update(priv, priv->num_svlans);
6953 6949 goto del_vlan_error;
6954 6950 }
6955 6951 }
6956 6952
6957 - priv->num_double_vlans = num_double_vlans;
6953 + priv->num_svlans = num_svlans;
6958 6954
6959 6955 del_vlan_error:
6960 6956 pm_runtime_put(priv->device);
@@ -6970,7 +6966,7 @@ static void stmmac_vlan_restore(struct stmmac_priv *priv)
6970 6966 if (priv->hw->num_vlan)
6971 6967 stmmac_restore_hw_vlan_rx_fltr(priv, priv->dev, priv->hw);
6972 6968
6973 - stmmac_vlan_update(priv, priv->num_double_vlans);
6969 + stmmac_vlan_update(priv, priv->num_svlans);
6974 6970 }
6975 6971
6976 6972 static int stmmac_bpf(struct net_device *dev, struct netdev_bpf *bpf)
@@ -8009,14 +8005,18 @@ static int __stmmac_dvr_probe(struct device *device,
8009 8005 ndev->watchdog_timeo = msecs_to_jiffies(watchdog);
8010 8006 #ifdef STMMAC_VLAN_TAG_USED
8011 8007 /* Both mac100 and gmac support receive VLAN tag detection */
8012 - ndev->features |= NETIF_F_HW_VLAN_CTAG_RX | NETIF_F_HW_VLAN_STAG_RX;
8008 + ndev->features |= NETIF_F_HW_VLAN_CTAG_RX;
8009 + if (priv->plat->core_type == DWMAC_CORE_XGMAC)
8010 + ndev->features |= NETIF_F_HW_VLAN_STAG_RX;
8011 +
8013 8012 if (dwmac_is_xmac(priv->plat->core_type)) {
8014 8013 ndev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX;
8015 8014 priv->hw->hw_vlan_en = true;
8016 8015 }
8017 8016 if (priv->dma_cap.vlhash) {
8018 8017 ndev->features |= NETIF_F_HW_VLAN_CTAG_FILTER;
8019 - ndev->features |= NETIF_F_HW_VLAN_STAG_FILTER;
8018 + if (priv->plat->core_type == DWMAC_CORE_XGMAC)
8019 + ndev->features |= NETIF_F_HW_VLAN_STAG_FILTER;
8020 8020 }
8021 8021 if (priv->dma_cap.vlins)
8022 8022 ndev->features |= NETIF_F_HW_VLAN_CTAG_TX;
modified drivers/net/ethernet/stmicro/stmmac/stmmac_selftests.c
@@ -243,7 +243,7 @@ struct stmmac_test_priv {
243 243 int (*func)(struct sk_buff *skb, struct net_device *ndev,
244 244 struct packet_type *pt, struct net_device *orig_ndev);
245 245 bool capture_all;
246 - int double_vlan;
246 + int svlan;
247 247 int vlan_id;
248 248 int ok;
249 249 };
@@ -285,7 +285,7 @@ static int stmmac_test_loopback_validate(struct sk_buff *skb,
285 285 }
286 286
287 287 ihdr = ip_hdr(skb);
288 - if (tpriv->double_vlan)
288 + if (tpriv->svlan)
289 289 ihdr = (struct iphdr *)(skb_network_header(skb) + 4);
290 290
291 291 if (tpriv->packet->tcp) {
@@ -936,7 +936,7 @@ static int stmmac_test_vlan_validate(struct sk_buff *skb,
936 936 struct iphdr *ihdr;
937 937 u16 proto;
938 938
939 - proto = tpriv->double_vlan ? ETH_P_8021AD : ETH_P_8021Q;
939 + proto = tpriv->svlan ? ETH_P_8021AD : ETH_P_8021Q;
940 940
941 941 skb = skb_unshare(skb, GFP_ATOMIC);
942 942 if (!skb)
@@ -963,7 +963,7 @@ static int stmmac_test_vlan_validate(struct sk_buff *skb,
963 963 }
964 964
965 965 ihdr = ip_hdr(skb);
966 - if (tpriv->double_vlan)
966 + if (tpriv->svlan)
967 967 ihdr = (struct iphdr *)(skb_network_header(skb) + 4);
968 968 if (ihdr->protocol != IPPROTO_UDP)
969 969 goto out;
@@ -1080,7 +1080,7 @@ static int stmmac_test_vlanfilt_perfect(struct stmmac_priv *priv)
1080 1080 return ret;
1081 1081 }
1082 1082
1083 - static int __stmmac_test_dvlanfilt(struct stmmac_priv *priv)
1083 + static int __stmmac_test_svlanfilt(struct stmmac_priv *priv)
1084 1084 {
1085 1085 struct stmmac_packet_attrs attr = { };
1086 1086 struct stmmac_test_priv *tpriv;
@@ -1092,7 +1092,7 @@ static int __stmmac_test_dvlanfilt(struct stmmac_priv *priv)
1092 1092 return -ENOMEM;
1093 1093
1094 1094 tpriv->ok = false;
1095 - tpriv->double_vlan = true;
1095 + tpriv->svlan = true;
1096 1096 init_completion(&tpriv->comp);
1097 1097
1098 1098 tpriv->pt.type = htons(ETH_P_8021Q);
@@ -1155,15 +1155,15 @@ cleanup:
1155 1155 return ret;
1156 1156 }
1157 1157
1158 - static int stmmac_test_dvlanfilt(struct stmmac_priv *priv)
1158 + static int stmmac_test_svlanfilt(struct stmmac_priv *priv)
1159 1159 {
1160 1160 if (!priv->dma_cap.vlhash)
1161 1161 return -EOPNOTSUPP;
1162 1162
1163 - return __stmmac_test_dvlanfilt(priv);
1163 + return __stmmac_test_svlanfilt(priv);
1164 1164 }
1165 1165
1166 - static int stmmac_test_dvlanfilt_perfect(struct stmmac_priv *priv)
1166 + static int stmmac_test_svlanfilt_perfect(struct stmmac_priv *priv)
1167 1167 {
1168 1168 int ret, prev_cap = priv->dma_cap.vlhash;
1169 1169
@@ -1171,7 +1171,7 @@ static int stmmac_test_dvlanfilt_perfect(struct stmmac_priv *priv)
1171 1171 return -EOPNOTSUPP;
1172 1172
1173 1173 priv->dma_cap.vlhash = 0;
1174 - ret = __stmmac_test_dvlanfilt(priv);
1174 + ret = __stmmac_test_svlanfilt(priv);
1175 1175 priv->dma_cap.vlhash = prev_cap;
1176 1176
1177 1177 return ret;
@@ -1372,7 +1372,7 @@ static int stmmac_test_vlanoff_common(struct stmmac_priv *priv, bool svlan)
1372 1372 proto = svlan ? ETH_P_8021AD : ETH_P_8021Q;
1373 1373
1374 1374 tpriv->ok = false;
1375 - tpriv->double_vlan = svlan;
1375 + tpriv->svlan = svlan;
1376 1376 init_completion(&tpriv->comp);
1377 1377
1378 1378 tpriv->pt.type = svlan ? htons(ETH_P_8021Q) : htons(ETH_P_IP);
@@ -1960,11 +1960,11 @@ static const struct stmmac_test {
1960 1960 .name = "VLAN Filtering (perf) ",
1961 1961 .fn = stmmac_test_vlanfilt_perfect,
1962 1962 }, {
1963 - .name = "Double VLAN Filter ",
1964 - .fn = stmmac_test_dvlanfilt,
1963 + .name = "SVLAN Filtering ",
1964 + .fn = stmmac_test_svlanfilt,
1965 1965 }, {
1966 - .name = "Double VLAN Filter (perf) ",
1967 - .fn = stmmac_test_dvlanfilt_perfect,
1966 + .name = "SVLAN Filtering (perf) ",
1967 + .fn = stmmac_test_svlanfilt_perfect,
1968 1968 }, {
1969 1969 .name = "Flexible RX Parser ",
1970 1970 .fn = stmmac_test_rxp,
modified drivers/net/ethernet/stmicro/stmmac/stmmac_vlan.c
@@ -162,7 +162,7 @@ static void vlan_restore_hw_rx_fltr(struct net_device *dev,
162 162 }
163 163
164 164 static void vlan_update_hash(struct mac_device_info *hw, u32 hash,
165 - u16 perfect_match, bool is_double)
165 + bool is_svlan)
166 166 {
167 167 void __iomem *ioaddr = hw->pcsr;
168 168 u32 value;
@@ -173,34 +173,17 @@ static void vlan_update_hash(struct mac_device_info *hw, u32 hash,
173 173
174 174 if (hash) {
175 175 value |= VLAN_VTHM | VLAN_ETV;
176 - if (is_double) {
177 - value |= VLAN_EDVLP;
176 + if (is_svlan) {
178 177 value |= VLAN_ESVL;
179 178 value |= VLAN_DOVLTC;
180 179 } else {
181 - value &= ~VLAN_EDVLP;
182 180 value &= ~VLAN_ESVL;
183 181 value &= ~VLAN_DOVLTC;
184 182 }
185 183
186 184 writel(value, ioaddr + VLAN_TAG);
187 - } else if (perfect_match) {
188 - u32 value = VLAN_ETV;
189 -
190 - if (is_double) {
191 - value |= VLAN_EDVLP;
192 - value |= VLAN_ESVL;
193 - value |= VLAN_DOVLTC;
194 - } else {
195 - value &= ~VLAN_EDVLP;
196 - value &= ~VLAN_ESVL;
197 - value &= ~VLAN_DOVLTC;
198 - }
199 -
200 - writel(value | perfect_match, ioaddr + VLAN_TAG);
201 185 } else {
202 - value &= ~(VLAN_VTHM | VLAN_ETV);
203 - value &= ~(VLAN_EDVLP | VLAN_ESVL);
186 + value &= ~(VLAN_VTHM | VLAN_ETV | VLAN_ESVL);
204 187 value &= ~VLAN_DOVLTC;
205 188 value &= ~VLAN_VID;
206 189
@@ -236,6 +219,7 @@ static void vlan_set_hw_mode(struct mac_device_info *hw)
236 219 void __iomem *ioaddr = hw->pcsr;
237 220 u32 value = readl(ioaddr + VLAN_TAG);
238 221
222 + value |= VLAN_EDVLP;
239 223 value &= ~VLAN_TAG_CTRL_EVLS_MASK;
240 224
241 225 if (hw->hw_vlan_en)
@@ -251,7 +235,7 @@ static void vlan_set_hw_mode(struct mac_device_info *hw)
251 235 }
252 236
253 237 static void dwxgmac2_update_vlan_hash(struct mac_device_info *hw, u32 hash,
254 - u16 perfect_match, bool is_double)
238 + bool is_svlan)
255 239 {
256 240 void __iomem *ioaddr = hw->pcsr;
257 241
@@ -267,41 +251,16 @@ static void dwxgmac2_update_vlan_hash(struct mac_device_info *hw, u32 hash,
267 251 value = readl(ioaddr + VLAN_TAG);
268 252
269 253 value |= VLAN_VTHM | VLAN_ETV;
270 - if (is_double) {
271 - value |= VLAN_EDVLP;
254 + if (is_svlan) {
272 255 value |= VLAN_ESVL;
273 256 value |= VLAN_DOVLTC;
274 257 } else {
275 - value &= ~VLAN_EDVLP;
276 258 value &= ~VLAN_ESVL;
277 259 value &= ~VLAN_DOVLTC;
278 260 }
279 261
280 262 value &= ~VLAN_VID;
281 263 writel(value, ioaddr + VLAN_TAG);
282 - } else if (perfect_match) {
283 - u32 value = readl(ioaddr + XGMAC_PACKET_FILTER);
284 -
285 - value |= XGMAC_FILTER_VTFE;
286 -
287 - writel(value, ioaddr + XGMAC_PACKET_FILTER);
288 -
289 - value = readl(ioaddr + VLAN_TAG);
290 -
291 - value &= ~VLAN_VTHM;
292 - value |= VLAN_ETV;
293 - if (is_double) {
294 - value |= VLAN_EDVLP;
295 - value |= VLAN_ESVL;
296 - value |= VLAN_DOVLTC;
297 - } else {
298 - value &= ~VLAN_EDVLP;
299 - value &= ~VLAN_ESVL;
300 - value &= ~VLAN_DOVLTC;
301 - }
302 -
303 - value &= ~VLAN_VID;
304 - writel(value | perfect_match, ioaddr + VLAN_TAG);
305 264 } else {
306 265 u32 value = readl(ioaddr + XGMAC_PACKET_FILTER);
307 266
@@ -311,8 +270,7 @@ static void dwxgmac2_update_vlan_hash(struct mac_device_info *hw, u32 hash,
311 270
312 271 value = readl(ioaddr + VLAN_TAG);
313 272
314 - value &= ~(VLAN_VTHM | VLAN_ETV);
315 - value &= ~(VLAN_EDVLP | VLAN_ESVL);
273 + value &= ~(VLAN_VTHM | VLAN_ETV | VLAN_ESVL);
316 274 value &= ~VLAN_DOVLTC;
317 275 value &= ~VLAN_VID;
318 276
@@ -320,6 +278,14 @@ static void dwxgmac2_update_vlan_hash(struct mac_device_info *hw, u32 hash,
320 278 }
321 279 }
322 280
281 + static void dwxlgmac2_set_hw_vlan_mode(struct mac_device_info *hw)
282 + {
283 + void __iomem *ioaddr = hw->pcsr;
284 + u32 value = readl(ioaddr + VLAN_TAG);
285 +
286 + writel(value | VLAN_EDVLP, ioaddr + VLAN_TAG);
287 + }
288 +
323 289 const struct stmmac_vlan_ops dwmac_vlan_ops = {
324 290 .update_vlan_hash = vlan_update_hash,
325 291 .enable_vlan = vlan_enable,
@@ -333,6 +299,7 @@ const struct stmmac_vlan_ops dwmac_vlan_ops = {
333 299 const struct stmmac_vlan_ops dwxlgmac2_vlan_ops = {
334 300 .update_vlan_hash = dwxgmac2_update_vlan_hash,
335 301 .enable_vlan = vlan_enable,
302 + .set_hw_vlan_mode = dwxlgmac2_set_hw_vlan_mode,
336 303 };
337 304
338 305 const struct stmmac_vlan_ops dwxgmac210_vlan_ops = {
modified drivers/net/ethernet/ti/icssm/icssm_prueth.c
@@ -1563,6 +1563,8 @@ static int icssm_prueth_netdev_init(struct prueth *prueth,
1563 1563 }
1564 1564 ether_addr_copy(emac->mac_addr, ndev->dev_addr);
1565 1565
1566 + ndev->netdev_ops = &emac_netdev_ops;
1567 +
1566 1568 /* connect PHY */
1567 1569 emac->phydev = of_phy_get_and_connect(ndev, eth_node,
1568 1570 icssm_emac_adjust_link);
@@ -1590,7 +1592,6 @@ static int icssm_prueth_netdev_init(struct prueth *prueth,
1590 1592 }
1591 1593
1592 1594 ndev->dev.of_node = eth_node;
1593 - ndev->netdev_ops = &emac_netdev_ops;
1594 1595
1595 1596 netif_napi_add(ndev, &emac->napi, icssm_emac_napi_poll);
1596 1597
modified drivers/net/ethernet/xilinx/xilinx_axienet.h
@@ -523,8 +523,9 @@ struct skbuf_dma_descriptor {
523 523 * @stats_work: Work for reading the hardware statistics counters often enough
524 524 * to catch overflows.
525 525 * @dma_err_task: Work structure to process Axi DMA errors
526 - * @stopping: Set when @dma_err_task shouldn't do anything because we are
527 - * about to stop the device.
526 + * @stopping: Set when we are about to stop the device: makes @dma_err_task
527 + * a no-op (legacy DMA path) and fences RX descriptor
528 + * resubmission in axienet_dma_rx_cb() (dmaengine path).
528 529 * @tx_irq: Axidma TX IRQ number
529 530 * @rx_irq: Axidma RX IRQ number
530 531 * @eth_irq: Ethernet core IRQ number
@@ -545,6 +546,7 @@ struct skbuf_dma_descriptor {
545 546 * @tx_ring_tail: TX skb ring buffer tail index.
546 547 * @rx_ring_head: RX skb ring buffer head index.
547 548 * @rx_ring_tail: RX skb ring buffer tail index.
549 + * @rx_submit_lock: Protects RX ring resubmission vs teardown in dmaengine path.
548 550 */
549 551 struct axienet_local {
550 552 struct net_device *ndev;
@@ -626,6 +628,7 @@ struct axienet_local {
626 628 int tx_ring_tail;
627 629 int rx_ring_head;
628 630 int rx_ring_tail;
631 + spinlock_t rx_submit_lock;
629 632 };
630 633
631 634 /**
modified drivers/net/ethernet/xilinx/xilinx_axienet_main.c
@@ -881,6 +881,7 @@ static void axienet_dma_tx_cb(void *data, const struct dmaengine_result *result)
881 881 u64_stats_update_end(&lp->tx_stat_sync);
882 882 dma_unmap_sg(lp->dev, skbuf_dma->sgl, skbuf_dma->sg_len, DMA_TO_DEVICE);
883 883 dev_consume_skb_any(skbuf_dma->skb);
884 + skbuf_dma->skb = NULL;
884 885 netif_txq_completed_wake(txq, 1, len,
885 886 CIRC_SPACE(lp->tx_ring_head, lp->tx_ring_tail, TX_BD_NUM_MAX),
886 887 2);
@@ -1171,6 +1172,7 @@ static void axienet_dma_rx_cb(void *data, const struct dmaengine_result *result)
1171 1172 &meta_max_len);
1172 1173 dma_unmap_single(lp->dev, skbuf_dma->dma_address, lp->max_frm_size,
1173 1174 DMA_FROM_DEVICE);
1175 + skbuf_dma->skb = NULL;
1174 1176
1175 1177 if (IS_ERR(app_metadata)) {
1176 1178 if (net_ratelimit())
@@ -1193,10 +1195,17 @@ static void axienet_dma_rx_cb(void *data, const struct dmaengine_result *result)
1193 1195 u64_stats_update_end(&lp->rx_stat_sync);
1194 1196
1195 1197 rx_submit:
1198 + spin_lock(&lp->rx_submit_lock);
1199 + if (lp->stopping) {
1200 + spin_unlock(&lp->rx_submit_lock);
1201 + return;
1202 + }
1203 +
1196 1204 for (i = 0; i < CIRC_SPACE(lp->rx_ring_head, lp->rx_ring_tail,
1197 1205 RX_BUF_NUM_DEFAULT); i++)
1198 1206 axienet_rx_submit_desc(lp->ndev);
1199 1207 dma_async_issue_pending(lp->rx_chan);
1208 + spin_unlock(&lp->rx_submit_lock);
1200 1209 }
1201 1210
1202 1211 /**
@@ -1541,6 +1550,7 @@ static int axienet_init_dmaengine(struct net_device *ndev)
1541 1550 lp->tx_ring_head = 0;
1542 1551 lp->rx_ring_tail = 0;
1543 1552 lp->rx_ring_head = 0;
1553 + lp->stopping = false;
1544 1554 lp->tx_skb_ring = kzalloc_objs(*lp->tx_skb_ring, TX_BD_NUM_MAX);
1545 1555 if (!lp->tx_skb_ring) {
1546 1556 ret = -ENOMEM;
@@ -1752,20 +1762,42 @@ static int axienet_stop(struct net_device *ndev)
1752 1762 free_irq(lp->rx_irq, ndev);
1753 1763 axienet_dma_bd_release(ndev);
1754 1764 } else {
1765 + struct skbuf_dma_descriptor *skbuf_dma;
1766 +
1767 + spin_lock_bh(&lp->rx_submit_lock);
1768 + lp->stopping = true;
1769 + spin_unlock_bh(&lp->rx_submit_lock);
1770 +
1755 1771 dmaengine_terminate_sync(lp->tx_chan);
1756 - dmaengine_synchronize(lp->tx_chan);
1757 1772 dmaengine_terminate_sync(lp->rx_chan);
1758 - dmaengine_synchronize(lp->rx_chan);
1759 -
1760 - for (i = 0; i < TX_BD_NUM_MAX; i++)
1761 - kfree(lp->tx_skb_ring[i]);
1762 - kfree(lp->tx_skb_ring);
1763 - for (i = 0; i < RX_BUF_NUM_DEFAULT; i++)
1764 - kfree(lp->rx_skb_ring[i]);
1765 - kfree(lp->rx_skb_ring);
1766 1773
1767 1774 dma_release_channel(lp->rx_chan);
1768 1775 dma_release_channel(lp->tx_chan);
1776 +
1777 + /* Unmap and free any buffer the terminate did not reclaim, so it
1778 + * is not leaked; a non-NULL skb marks such a slot.
1779 + */
1780 + for (i = 0; i < TX_BD_NUM_MAX; i++) {
1781 + skbuf_dma = lp->tx_skb_ring[i];
1782 + if (skbuf_dma && skbuf_dma->skb) {
1783 + dma_unmap_sg(lp->dev, skbuf_dma->sgl,
1784 + skbuf_dma->sg_len, DMA_TO_DEVICE);
1785 + dev_kfree_skb_any(skbuf_dma->skb);
1786 + }
1787 + kfree(skbuf_dma);
1788 + }
1789 + kfree(lp->tx_skb_ring);
1790 +
1791 + for (i = 0; i < RX_BUF_NUM_DEFAULT; i++) {
1792 + skbuf_dma = lp->rx_skb_ring[i];
1793 + if (skbuf_dma && skbuf_dma->skb) {
1794 + dma_unmap_single(lp->dev, skbuf_dma->dma_address,
1795 + lp->max_frm_size, DMA_FROM_DEVICE);
1796 + dev_kfree_skb_any(skbuf_dma->skb);
1797 + }
1798 + kfree(skbuf_dma);
1799 + }
1800 + kfree(lp->rx_skb_ring);
1769 1801 }
1770 1802
1771 1803 netdev_reset_queue(ndev);
@@ -3065,6 +3097,7 @@ static int axienet_probe(struct platform_device *pdev)
3065 3097
3066 3098 spin_lock_init(&lp->rx_cr_lock);
3067 3099 spin_lock_init(&lp->tx_cr_lock);
3100 + spin_lock_init(&lp->rx_submit_lock);
3068 3101 INIT_WORK(&lp->rx_dim.work, axienet_rx_dim_work);
3069 3102 lp->rx_dim_enabled = true;
3070 3103 lp->rx_dim.profile_ix = 1;
modified drivers/net/pfcp.c
@@ -65,6 +65,13 @@ static int pfcp_encap_recv(struct sock *sk, struct sk_buff *skb)
65 65 goto drop;
66 66
67 67 unparsed = pfcp_hdr(skb);
68 + if (unparsed->flags & PFCP_SEID_FLAG) {
69 + if (unlikely(!pskb_may_pull(skb, PFCP_HLEN +
70 + offsetofend(struct pfcphdr_session,
71 + seid))))
72 + goto drop;
73 + unparsed = pfcp_hdr(skb);
74 + }
68 75
69 76 ip_tunnel_flags_zero(flags);
70 77 tun_dst = udp_tun_rx_dst(skb, sk->sk_family, flags, 0,
modified drivers/net/team/team_core.c
@@ -820,7 +820,8 @@ static struct list_head *__team_get_qom_list(struct team *team, u16 queue_id)
820 820 /*
821 821 * note: already called with rcu_read_lock
822 822 */
823 - static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb)
823 + static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb,
824 + bool *tx_success)
824 825 {
825 826 struct list_head *qom_list;
826 827 struct team_port *port;
@@ -828,11 +829,11 @@ static bool team_queue_override_transmit(struct team *team, struct sk_buff *skb)
828 829 if (!team->queue_override_enabled || !skb->queue_mapping)
829 830 return false;
830 831 qom_list = __team_get_qom_list(team, skb->queue_mapping);
831 - list_for_each_entry_rcu(port, qom_list, qom_list) {
832 - if (!team_dev_queue_xmit(team, port, skb))
833 - return true;
834 - }
835 - return false;
832 + port = list_first_or_null_rcu(qom_list, struct team_port, qom_list);
833 + if (!port)
834 + return false;
835 + *tx_success = !team_dev_queue_xmit(team, port, skb);
836 + return true;
836 837 }
837 838
838 839 static void __team_queue_override_port_del(struct team *team,
@@ -1864,8 +1865,7 @@ static netdev_tx_t team_xmit(struct sk_buff *skb, struct net_device *dev)
1864 1865 bool tx_success;
1865 1866 unsigned int len = skb->len;
1866 1867
1867 - tx_success = team_queue_override_transmit(team, skb);
1868 - if (!tx_success)
1868 + if (!team_queue_override_transmit(team, skb, &tx_success))
1869 1869 tx_success = READ_ONCE(team->ops.transmit)(team, skb);
1870 1870 if (tx_success) {
1871 1871 struct team_pcpu_stats *pcpu_stats;
modified drivers/net/team/team_mode_broadcast.c
@@ -37,6 +37,8 @@ static bool bc_transmit(struct team *team, struct sk_buff *skb)
37 37 ret = !team_dev_queue_xmit(team, last, skb);
38 38 if (!sum_ret)
39 39 sum_ret = ret;
40 + } else {
41 + dev_kfree_skb_any(skb);
40 42 }
41 43 return sum_ret;
42 44 }
modified drivers/net/tun.c
@@ -1897,12 +1897,7 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1897 1897 }
1898 1898 }
1899 1899
1900 - if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) {
1901 - atomic_long_inc(&tun->rx_frame_errors);
1902 - err = -EINVAL;
1903 - goto free_skb;
1904 - }
1905 -
1900 + skb->dev = tun->dev;
1906 1901 switch (tun->flags & TUN_TYPE_MASK) {
1907 1902 case IFF_TUN:
1908 1903 if (tun->flags & IFF_NO_PI) {
@@ -1927,9 +1922,8 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1927 1922 }
1928 1923 }
1929 1924
1930 - skb_reset_mac_header(skb);
1925 + skb_reset_network_header(skb);
1931 1926 skb->protocol = pi.proto;
1932 - skb->dev = tun->dev;
1933 1927 break;
1934 1928 case IFF_TAP:
1935 1929 if (!pskb_may_pull(skb, ETH_HLEN)) {
@@ -1937,10 +1931,19 @@ static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
1937 1931 drop_reason = SKB_DROP_REASON_HDR_TRUNC;
1938 1932 goto drop;
1939 1933 }
1940 - skb->protocol = eth_type_trans(skb, tun->dev);
1934 + skb_set_network_header(skb, ETH_HLEN);
1941 1935 break;
1942 1936 }
1943 1937
1938 + if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, &hdr)) {
1939 + atomic_long_inc(&tun->rx_frame_errors);
1940 + err = -EINVAL;
1941 + goto free_skb;
1942 + }
1943 +
1944 + if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP)
1945 + skb->protocol = eth_type_trans(skb, tun->dev);
1946 +
1944 1947 /* copy skb_ubuf_info for callback when skb has no error */
1945 1948 if (zerocopy) {
1946 1949 skb_zcopy_init(skb, msg_control);
@@ -2600,6 +2603,8 @@ build:
2600 2603
2601 2604 features = tun_vnet_hdr_guest_features(READ_ONCE(tun->vnet_hdr_sz));
2602 2605 tnl_hdr = (struct virtio_net_hdr_v1_hash_tunnel *)gso;
2606 + skb->dev = tun->dev;
2607 + skb_set_network_header(skb, ETH_HLEN);
2603 2608 if (tun_vnet_hdr_tnl_to_skb(tun->flags, features, skb, tnl_hdr)) {
2604 2609 atomic_long_inc(&tun->rx_frame_errors);
2605 2610 kfree_skb(skb);
modified drivers/net/usb/ax88179_178a.c
@@ -1457,11 +1457,11 @@ static int ax88179_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
1457 1457 return 1;
1458 1458 }
1459 1459
1460 - ax_skb = netdev_alloc_skb_ip_align(dev->net, pkt_len);
1460 + ax_skb = netdev_alloc_skb_ip_align(dev->net, pkt_len - 2);
1461 1461 if (!ax_skb)
1462 1462 return 0;
1463 - skb_put(ax_skb, pkt_len);
1464 - memcpy(ax_skb->data, skb->data + 2, pkt_len);
1463 + skb_put(ax_skb, pkt_len - 2);
1464 + memcpy(ax_skb->data, skb->data + 2, pkt_len - 2);
1465 1465
1466 1466 ax88179_rx_checksum(ax_skb, pkt_hdr);
1467 1467 usbnet_skb_return(dev, ax_skb);
modified drivers/net/veth.c
@@ -1415,6 +1415,7 @@ static int veth_open(struct net_device *dev)
1415 1415 }
1416 1416
1417 1417 veth_set_xdp_features(dev);
1418 + veth_set_xdp_features(peer);
1418 1419
1419 1420 return 0;
1420 1421 }
modified drivers/net/virtio_net.c
@@ -2515,6 +2515,8 @@ static void virtnet_receive_done(struct virtnet_info *vi, struct receive_queue *
2515 2515 goto frame_err;
2516 2516 }
2517 2517
2518 + skb->dev = dev;
2519 + skb_set_network_header(skb, ETH_HLEN);
2518 2520 if (virtio_net_hdr_tnl_to_skb(skb, &hdr->tnl_hdr, vi->rx_tnl,
2519 2521 vi->rx_tnl_csum,
2520 2522 virtio_is_little_endian(vi->vdev))) {
modified drivers/net/wireguard/noise.c
@@ -784,10 +784,11 @@ wg_noise_handshake_consume_response(struct message_handshake_response *src,
784 784
785 785 /* Success! Copy everything to peer */
786 786 down_write(&handshake->lock);
787 - /* It's important to check that the state is still the same, while we
788 - * have an exclusive lock.
787 + /* Check that the state is the same and that this is still the
788 + * initiation we started with, while we have an exclusive lock.
789 789 */
790 - if (handshake->state != state) {
790 + if (handshake->state != state ||
791 + crypto_memneq(handshake->ephemeral_private, ephemeral_private, NOISE_PUBLIC_KEY_LEN)) {
791 792 up_write(&handshake->lock);
792 793 goto fail;
793 794 }
modified drivers/net/wireguard/queueing.h
@@ -78,12 +78,14 @@ static inline void wg_reset_packet(struct sk_buff *skb, bool encapsulating)
78 78 u8 l4_hash = skb->l4_hash;
79 79 u8 sw_hash = skb->sw_hash;
80 80 u32 hash = skb->hash;
81 + u8 tstamp_type = skb->tstamp_type;
81 82 skb_scrub_packet(skb, true);
82 83 memset(&skb->headers, 0, sizeof(skb->headers));
83 84 if (encapsulating) {
84 85 skb->l4_hash = l4_hash;
85 86 skb->sw_hash = sw_hash;
86 87 skb->hash = hash;
88 + skb->tstamp_type = tstamp_type;
87 89 }
88 90 skb->queue_mapping = 0;
89 91 skb->nohdr = 0;
modified drivers/net/wireless/ath/ath12k/core.c
@@ -1776,29 +1776,6 @@ int ath12k_core_pre_init(struct ath12k_base *ab)
1776 1776 return 0;
1777 1777 }
1778 1778
1779 - static int ath12k_core_panic_handler(struct notifier_block *nb,
1780 - unsigned long action, void *data)
1781 - {
1782 - struct ath12k_base *ab = container_of(nb, struct ath12k_base,
1783 - panic_nb);
1784 -
1785 - return ath12k_hif_panic_handler(ab);
1786 - }
1787 -
1788 - static int ath12k_core_panic_notifier_register(struct ath12k_base *ab)
1789 - {
1790 - ab->panic_nb.notifier_call = ath12k_core_panic_handler;
1791 -
1792 - return atomic_notifier_chain_register(&panic_notifier_list,
1793 - &ab->panic_nb);
1794 - }
1795 -
1796 - static void ath12k_core_panic_notifier_unregister(struct ath12k_base *ab)
1797 - {
1798 - atomic_notifier_chain_unregister(&panic_notifier_list,
1799 - &ab->panic_nb);
1800 - }
1801 -
1802 1779 static inline
1803 1780 bool ath12k_core_hw_group_create_ready(struct ath12k_hw_group *ag)
1804 1781 {
@@ -2214,18 +2191,13 @@ int ath12k_core_init(struct ath12k_base *ab)
2214 2191 struct ath12k_hw_group *ag;
2215 2192 int ret;
2216 2193
2217 - ret = ath12k_core_panic_notifier_register(ab);
2218 - if (ret)
2219 - ath12k_warn(ab, "failed to register panic handler: %d\n", ret);
2220 -
2221 2194 mutex_lock(&ath12k_hw_group_mutex);
2222 2195
2223 2196 ag = ath12k_core_hw_group_assign(ab);
2224 2197 if (!ag) {
2225 2198 mutex_unlock(&ath12k_hw_group_mutex);
2226 2199 ath12k_warn(ab, "unable to get hw group\n");
2227 - ret = -ENODEV;
2228 - goto err_unregister_notifier;
2200 + return -ENODEV;
2229 2201 }
2230 2202
2231 2203 mutex_unlock(&ath12k_hw_group_mutex);
@@ -2250,8 +2222,6 @@ int ath12k_core_init(struct ath12k_base *ab)
2250 2222
2251 2223 err_unassign_hw_group:
2252 2224 ath12k_core_hw_group_unassign(ab);
2253 - err_unregister_notifier:
2254 - ath12k_core_panic_notifier_unregister(ab);
2255 2225
2256 2226 return ret;
2257 2227 }
@@ -2260,7 +2230,6 @@ void ath12k_core_deinit(struct ath12k_base *ab)
2260 2230 {
2261 2231 ath12k_core_hw_group_destroy(ab->ag);
2262 2232 ath12k_core_hw_group_unassign(ab);
2263 - ath12k_core_panic_notifier_unregister(ab);
2264 2233 }
2265 2234
2266 2235 void ath12k_core_free(struct ath12k_base *ab)
modified drivers/net/wireless/ath/ath12k/core.h
@@ -15,7 +15,6 @@
15 15 #include <linux/ctype.h>
16 16 #include <linux/firmware.h>
17 17 #include <linux/of_reserved_mem.h>
18 - #include <linux/panic_notifier.h>
19 18 #include <linux/average.h>
20 19 #include <linux/of.h>
21 20 #include <linux/rhashtable.h>
@@ -1139,8 +1138,6 @@ struct ath12k_base {
1139 1138
1140 1139 #endif /* CONFIG_ACPI */
1141 1140
1142 - struct notifier_block panic_nb;
1143 -
1144 1141 struct ath12k_hw_group *ag;
1145 1142 struct ath12k_wsi_info wsi_info;
1146 1143 enum ath12k_qmi_firmware_mode fw_mode;
modified drivers/net/wireless/ath/ath12k/hif.h
@@ -30,7 +30,6 @@ struct ath12k_hif_ops {
30 30 void (*ce_irq_enable)(struct ath12k_base *ab);
31 31 void (*ce_irq_disable)(struct ath12k_base *ab);
32 32 void (*get_ce_msi_idx)(struct ath12k_base *ab, u32 ce_id, u32 *msi_idx);
33 - int (*panic_handler)(struct ath12k_base *ab);
34 33 void (*coredump_download)(struct ath12k_base *ab);
35 34 };
36 35
@@ -149,14 +148,6 @@ static inline void ath12k_hif_power_down(struct ath12k_base *ab, bool is_suspend
149 148 ab->hif.ops->power_down(ab, is_suspend);
150 149 }
151 150
152 - static inline int ath12k_hif_panic_handler(struct ath12k_base *ab)
153 - {
154 - if (!ab->hif.ops->panic_handler)
155 - return NOTIFY_DONE;
156 -
157 - return ab->hif.ops->panic_handler(ab);
158 - }
159 -
160 151 static inline void ath12k_hif_coredump_download(struct ath12k_base *ab)
161 152 {
162 153 if (ab->hif.ops->coredump_download)
modified drivers/net/wireless/ath/ath12k/pci.c
@@ -1484,13 +1484,6 @@ void ath12k_pci_power_down(struct ath12k_base *ab, bool is_suspend)
1484 1484 ath12k_pci_sw_reset(ab_pci->ab, false);
1485 1485 }
1486 1486
1487 - static int ath12k_pci_panic_handler(struct ath12k_base *ab)
1488 - {
1489 - ath12k_pci_sw_reset(ab, false);
1490 -
1491 - return NOTIFY_OK;
1492 - }
1493 -
1494 1487 static const struct ath12k_hif_ops ath12k_pci_hif_ops = {
1495 1488 .start = ath12k_pci_start,
1496 1489 .stop = ath12k_pci_stop,
@@ -1508,7 +1501,6 @@ static const struct ath12k_hif_ops ath12k_pci_hif_ops = {
1508 1501 .ce_irq_enable = ath12k_pci_hif_ce_irq_enable,
1509 1502 .ce_irq_disable = ath12k_pci_hif_ce_irq_disable,
1510 1503 .get_ce_msi_idx = ath12k_pci_get_ce_msi_idx,
1511 - .panic_handler = ath12k_pci_panic_handler,
1512 1504 #ifdef CONFIG_ATH12K_COREDUMP
1513 1505 .coredump_download = ath12k_pci_coredump_download,
1514 1506 #endif
modified drivers/net/wireless/ath/ath9k/wmi.c
@@ -206,16 +206,9 @@ static void ath9k_wmi_rsp_callback(struct wmi *wmi, struct sk_buff *skb)
206 206 {
207 207 skb_pull(skb, sizeof(struct wmi_cmd_hdr));
208 208
209 - if (wmi->cmd_rsp_buf && wmi->cmd_rsp_len) {
210 - if (skb->len < wmi->cmd_rsp_len) {
211 - wmi->cmd_rsp_status = -EMSGSIZE;
212 - goto complete;
213 - }
209 + if (wmi->cmd_rsp_buf != NULL && wmi->cmd_rsp_len != 0)
214 210 memcpy(wmi->cmd_rsp_buf, skb->data, wmi->cmd_rsp_len);
215 - }
216 - wmi->cmd_rsp_status = 0;
217 211
218 - complete:
219 212 complete(&wmi->cmd_wait);
220 213 }
221 214
@@ -307,7 +300,6 @@ static int ath9k_wmi_cmd_issue(struct wmi *wmi,
307 300 /* record the rsp buffer and length */
308 301 wmi->cmd_rsp_buf = rsp_buf;
309 302 wmi->cmd_rsp_len = rsp_len;
310 - wmi->cmd_rsp_status = 0;
311 303
312 304 wmi->last_seq_id = wmi->tx_seq_id;
313 305 spin_unlock_irqrestore(&wmi->wmi_lock, flags);
@@ -364,13 +356,9 @@ int ath9k_wmi_cmd(struct wmi *wmi, enum wmi_cmd_id cmd_id,
364 356 return -ETIMEDOUT;
365 357 }
366 358
367 - spin_lock_irqsave(&wmi->wmi_lock, flags);
368 - ret = wmi->cmd_rsp_status;
369 - spin_unlock_irqrestore(&wmi->wmi_lock, flags);
370 -
371 359 mutex_unlock(&wmi->op_mutex);
372 360
373 - return ret;
361 + return 0;
374 362
375 363 out:
376 364 ath_dbg(common, WMI, "WMI failure for: %s\n", wmi_cmd_to_name(cmd_id));
modified drivers/net/wireless/ath/ath9k/wmi.h
@@ -157,7 +157,6 @@ struct wmi {
157 157 u16 tx_seq_id;
158 158 u8 *cmd_rsp_buf;
159 159 u32 cmd_rsp_len;
160 - int cmd_rsp_status;
161 160 bool stopped;
162 161
163 162 struct list_head pending_tx_events;
modified drivers/net/wireless/broadcom/brcm80211/brcmfmac/core.c
@@ -1489,8 +1489,31 @@ void brcmf_detach(struct device *dev)
1489 1489 brcmf_bus_change_state(bus_if, BRCMF_BUS_DOWN);
1490 1490 /* make sure primary interface removed last */
1491 1491 for (i = BRCMF_MAX_IFS - 1; i > -1; i--) {
1492 - if (drvr->iflist[i])
1493 - brcmf_remove_interface(drvr->iflist[i], false);
1492 + struct brcmf_if *ifp = drvr->iflist[i];
1493 +
1494 + if (!ifp)
1495 + continue;
1496 +
1497 + if (ifp->ndev) {
1498 + brcmf_remove_interface(ifp, false);
1499 + continue;
1500 + }
1501 +
1502 + /* The P2P device interface has no netdev. Its removal can
1503 + * race with NL80211_CMD_DEL_INTERFACE issued by a user space
1504 + * process that is exiting (e.g. wpa_supplicant), which ends
1505 + * in brcmf_p2p_del_vif() under RTNL and the wiphy mutex. If
1506 + * both paths remove the interface, the wdev is unregistered
1507 + * twice and the vif is used after being freed. Take the same
1508 + * locks and re-read iflist, so only one path removes it.
1509 + */
1510 + rtnl_lock();
1511 + wiphy_lock(drvr->wiphy);
1512 + ifp = drvr->iflist[i];
1513 + if (ifp)
1514 + brcmf_remove_interface(ifp, true);
1515 + wiphy_unlock(drvr->wiphy);
1516 + rtnl_unlock();
1494 1517 }
1495 1518 brcmf_bus_stop(drvr->bus_if);
1496 1519
modified drivers/net/wireless/marvell/libertas/tx.c
@@ -117,13 +117,6 @@ netdev_tx_t lbs_hard_start_xmit(struct sk_buff *skb, struct net_device *dev)
117 117 if (priv->wdev->iftype == NL80211_IFTYPE_MONITOR) {
118 118 struct tx_radiotap_hdr *rtap_hdr = (void *)skb->data;
119 119
120 - if (skb->len < sizeof(*rtap_hdr) + 4 + ETH_ALEN) {
121 - lbs_deb_tx("tx err: short monitor frame %u\n", skb->len);
122 - dev->stats.tx_dropped++;
123 - dev->stats.tx_errors++;
124 - goto free;
125 - }
126 -
127 120 /* set txpd fields from the radiotap header */
128 121 txpd->tx_control = cpu_to_le32(convert_radiotap_rate_to_mv(rtap_hdr->rate));
129 122
modified drivers/net/wireless/mediatek/mt76/mt76.h
@@ -1426,6 +1426,13 @@ mtxq_to_txq(struct mt76_txq *mtxq)
1426 1426 return container_of(ptr, struct ieee80211_txq, drv_priv);
1427 1427 }
1428 1428
1429 + /* peer-wide state uses the wcid of the primary link */
1430 + static inline struct mt76_wcid *
1431 + mt76_wcid_primary(struct mt76_wcid *wcid)
1432 + {
1433 + return wcid->def_wcid ? wcid->def_wcid : wcid;
1434 + }
1435 +
1429 1436 static inline struct ieee80211_sta *
1430 1437 wcid_to_sta(struct mt76_wcid *wcid)
1431 1438 {
modified drivers/net/wireless/mediatek/mt76/mt7603/init.c
@@ -230,6 +230,7 @@ mt7603_mac_init(struct mt7603_dev *dev)
230 230
231 231 eth_broadcast_addr(bc_addr);
232 232 mt7603_wtbl_init(dev, MT7603_WTBL_RESERVED, -1, bc_addr);
233 + mt76_wcid_init(&dev->global_sta.wcid, 0);
233 234 dev->global_sta.wcid.idx = MT7603_WTBL_RESERVED;
234 235 rcu_assign_pointer(dev->mt76.wcid[MT7603_WTBL_RESERVED],
235 236 &dev->global_sta.wcid);
modified drivers/net/wireless/mediatek/mt76/mt7915/init.c
@@ -1238,6 +1238,12 @@ static void mt7915_unregister_ext_phy(struct mt7915_dev *dev)
1238 1238
1239 1239 static void mt7915_stop_hardware(struct mt7915_dev *dev)
1240 1240 {
1241 + int i;
1242 +
1243 + mt76_for_each_q_rx(&dev->mt76, i) {
1244 + if (!mt76_queue_is_wed_rro(&dev->mt76.q_rx[i]))
1245 + napi_disable(&dev->mt76.napi[i]);
1246 + }
1241 1247 mt7915_mcu_exit(dev);
1242 1248 mt76_connac2_tx_token_put(&dev->mt76);
1243 1249 mt7915_dma_cleanup(dev);
modified drivers/net/wireless/mediatek/mt76/mt7915/main.c
@@ -805,6 +805,7 @@ __mt7915_drop_sta(void *ptr, u8 *mac, struct ieee80211_vif *vif)
805 805
806 806 msta = (struct mt7915_sta *)sta->drv_priv;
807 807 mt7915_mcu_add_sta(data->dev, vif, sta, CONN_STATE_DISCONNECT, false);
808 + msta->wcid.tx_info &= ~MT_WCID_TX_INFO_SET;
808 809 msta->wcid.sta_disabled = 1;
809 810 msta->wcid.sta = 0;
810 811 }
@@ -871,6 +872,7 @@ int mt7915_mac_sta_event(struct mt76_dev *mdev, struct ieee80211_vif *vif,
871 872 mutex_unlock(&dev->mt76.mutex);
872 873
873 874 mt7915_mcu_add_sta(dev, vif, sta, CONN_STATE_DISCONNECT, false);
875 + msta->wcid.tx_info &= ~MT_WCID_TX_INFO_SET;
874 876 msta->wcid.sta_disabled = 1;
875 877 msta->wcid.sta = 0;
876 878 return 0;
modified drivers/net/wireless/mediatek/mt76/mt7925/mac.c
@@ -798,7 +798,8 @@ mt7925_mac_write_txwi(struct mt76_dev *dev, __le32 *txwi,
798 798 val = FIELD_PREP(MT_TXD1_WLAN_IDX, wcid->idx) |
799 799 FIELD_PREP(MT_TXD1_OWN_MAC, omac_idx);
800 800
801 - if (band_idx)
801 + /* 0xff means BAND_AUTO to the firmware, and TGID cannot encode it */
802 + if (band_idx && band_idx != 0xff)
802 803 val |= FIELD_PREP(MT_TXD1_TGID, band_idx);
803 804
804 805 txwi[1] = cpu_to_le32(val);
modified drivers/net/wireless/mediatek/mt76/mt7925/main.c
@@ -2294,6 +2294,18 @@ mt7925_change_vif_links(struct ieee80211_hw *hw, struct ieee80211_vif *vif,
2294 2294
2295 2295 mvif->valid_links = new_links;
2296 2296
2297 + /* Restore the legacy BSS after disabling MLO */
2298 + if (old_links && !new_links) {
2299 + mt792x_mac_link_bss_remove(dev, &mvif->bss_conf,
2300 + &mvif->sta.deflink);
2301 + err = mt7925_mac_link_bss_add(dev, &vif->bss_conf,
2302 + &mvif->sta.deflink);
2303 + if (err < 0) {
2304 + mt792x_mutex_release(dev);
2305 + return err;
2306 + }
2307 + }
2308 +
2297 2309 mt792x_mutex_release(dev);
2298 2310
2299 2311 return 0;
modified drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.c
@@ -108,68 +108,98 @@ mt792x_asar_acpi_read_mtcl(struct mt792x_dev *dev, u8 **table, u8 *version)
108 108 return ret;
109 109 }
110 110
111 + /* A table's layout is decided by the version byte in MTCL, but some firmware
112 + * labels a version 2 table as version 1. Accept whichever layout the table
113 + * actually has: for every accepted entry count the two do not overlap, since
114 + * one is 6 + 5n bytes and the other 7 + 7n.
115 + */
116 + static bool
117 + mt792x_asar_fits(u8 *table, int len, int prelen, int sarlen, int nr_off,
118 + int min, int max)
119 + {
120 + int tblcnt;
121 +
122 + if (len < prelen || (len - prelen) % sarlen)
123 + return false;
124 +
125 + tblcnt = (len - prelen) / sarlen;
126 + if (tblcnt < min || tblcnt > max)
127 + return false;
128 +
129 + return tblcnt == table[nr_off];
130 + }
131 +
111 132 /* MTDS : Dynamic SAR Power Table */
112 133 static int
113 - mt792x_asar_acpi_read_mtds(struct mt792x_dev *dev, u8 **table, u8 version)
134 + mt792x_asar_acpi_read_mtds(struct mt792x_dev *dev, u8 **table, u8 version,
135 + u8 *used)
114 136 {
115 - int len, ret, sarlen, prelen, tblcnt;
116 - bool enable;
137 + int len, ret;
138 + u8 *t;
117 139
118 140 ret = mt792x_acpi_read(dev, MT792x_ACPI_MTDS, table, &len);
119 141 if (ret)
120 142 return ret;
121 143
144 + t = *table;
145 +
122 146 /* Table content validation */
123 - switch (version) {
124 - case 1:
125 - enable = ((struct mt792x_asar_dyn *)*table)->enable;
126 - sarlen = sizeof(struct mt792x_asar_dyn_limit);
127 - prelen = sizeof(struct mt792x_asar_dyn);
128 - break;
129 - case 2:
130 - enable = ((struct mt792x_asar_dyn_v2 *)*table)->enable;
131 - sarlen = sizeof(struct mt792x_asar_dyn_limit_v2);
132 - prelen = sizeof(struct mt792x_asar_dyn_v2);
133 - break;
134 - default:
147 + if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_dyn),
148 + sizeof(struct mt792x_asar_dyn_limit),
149 + offsetof(struct mt792x_asar_dyn, nr_tbl),
150 + MT792x_ASAR_MIN_DYN, MT792x_ASAR_MAX_DYN))
151 + *used = 1;
152 + else if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_dyn_v2),
153 + sizeof(struct mt792x_asar_dyn_limit_v2),
154 + offsetof(struct mt792x_asar_dyn_v2, nr_tbl),
155 + MT792x_ASAR_MIN_DYN, MT792x_ASAR_MAX_DYN))
156 + *used = 2;
157 + else
135 158 return -EINVAL;
136 - }
137 159
138 - tblcnt = (len - prelen) / sarlen;
139 - if (!enable ||
140 - tblcnt > MT792x_ASAR_MAX_DYN || tblcnt < MT792x_ASAR_MIN_DYN)
160 + if (!t[offsetof(struct mt792x_asar_dyn, enable)])
141 161 return -EINVAL;
142 162
163 + if (version && *used != version)
164 + dev_info(dev->mt76.dev,
165 + "MTDS is v%u, MTCL says v%u; using v%u\n",
166 + *used, version, *used);
167 +
143 168 return 0;
144 169 }
145 170
146 171 /* MTGS : Geo SAR Power Table */
147 172 static int
148 - mt792x_asar_acpi_read_mtgs(struct mt792x_dev *dev, u8 **table, u8 version)
173 + mt792x_asar_acpi_read_mtgs(struct mt792x_dev *dev, u8 **table, u8 version,
174 + u8 *used)
149 175 {
150 - int len, ret, sarlen, prelen, tblcnt;
176 + int len, ret;
177 + u8 *t;
151 178
152 179 ret = mt792x_acpi_read(dev, MT792x_ACPI_MTGS, table, &len);
153 180 if (ret)
154 181 return ret;
155 182
183 + t = *table;
184 +
156 185 /* Table content validation */
157 - switch (version) {
158 - case 1:
159 - sarlen = sizeof(struct mt792x_asar_geo_limit);
160 - prelen = sizeof(struct mt792x_asar_geo);
161 - break;
162 - case 2:
163 - sarlen = sizeof(struct mt792x_asar_geo_limit_v2);
164 - prelen = sizeof(struct mt792x_asar_geo_v2);
165 - break;
166 - default:
186 + if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_geo),
187 + sizeof(struct mt792x_asar_geo_limit),
188 + offsetof(struct mt792x_asar_geo, nr_tbl),
189 + MT792x_ASAR_MIN_GEO, MT792x_ASAR_MAX_GEO))
190 + *used = 1;
191 + else if (mt792x_asar_fits(t, len, sizeof(struct mt792x_asar_geo_v2),
192 + sizeof(struct mt792x_asar_geo_limit_v2),
193 + offsetof(struct mt792x_asar_geo_v2, nr_tbl),
194 + MT792x_ASAR_MIN_GEO, MT792x_ASAR_MAX_GEO))
195 + *used = 2;
196 + else
167 197 return -EINVAL;
168 - }
169 198
170 - tblcnt = (len - prelen) / sarlen;
171 - if (tblcnt > MT792x_ASAR_MAX_GEO || tblcnt < MT792x_ASAR_MIN_GEO)
172 - return -EINVAL;
199 + if (version && *used != version)
200 + dev_info(dev->mt76.dev,
201 + "MTGS is v%u, MTCL says v%u; using v%u\n",
202 + *used, version, *used);
173 203
174 204 return 0;
175 205 }
@@ -205,14 +235,16 @@ int mt792x_init_acpi_sar(struct mt792x_dev *dev)
205 235 asar->countrylist = NULL;
206 236 }
207 237
208 - ret = mt792x_asar_acpi_read_mtds(dev, (u8 **)&asar->dyn, asar->ver);
238 + ret = mt792x_asar_acpi_read_mtds(dev, (u8 **)&asar->dyn, asar->ver,
239 + &asar->dyn_ver);
209 240 if (ret) {
210 241 devm_kfree(dev->mt76.dev, asar->dyn);
211 242 asar->dyn = NULL;
212 243 }
213 244
214 245 /* MTGS is optional */
215 - ret = mt792x_asar_acpi_read_mtgs(dev, (u8 **)&asar->geo, asar->ver);
246 + ret = mt792x_asar_acpi_read_mtgs(dev, (u8 **)&asar->geo, asar->ver,
247 + &asar->geo_ver);
216 248 if (ret) {
217 249 devm_kfree(dev->mt76.dev, asar->geo);
218 250 asar->geo = NULL;
@@ -254,7 +286,7 @@ mt792x_asar_get_geo_pwr(struct mt792x_phy *phy,
254 286 break;
255 287 }
256 288
257 - if (asar->ver == 1) {
289 + if (asar->geo_ver == 1) {
258 290 band_pwr = &asar->geo->tbl[idx].band[0];
259 291 max = ARRAY_SIZE(asar->geo->tbl[idx].band);
260 292 } else {
@@ -279,10 +311,18 @@ mt792x_asar_get_geo_pwr(struct mt792x_phy *phy,
279 311 if (idx >= max)
280 312 return dyn_power;
281 313
282 - geo_power = (band_pwr + idx)->pwr;
283 - dyn_power += (band_pwr + idx)->offset;
314 + band_pwr += idx;
315 +
316 + /* Some OEM tables carry 0xff here; narrowed to s8 that is -1 and
317 + * wins the min() below. Take it as no limit.
318 + */
319 + if (band_pwr->pwr == 0xff)
320 + return dyn_power;
321 +
322 + geo_power = band_pwr->pwr;
284 323
285 - return min(geo_power, dyn_power);
324 + return min_t(int, geo_power,
325 + min_t(int, dyn_power + band_pwr->offset, 127));
286 326 }
287 327
288 328 static s8
@@ -297,7 +337,7 @@ mt792x_asar_range_pwr(struct mt792x_phy *phy,
297 337 if (!capa)
298 338 return 127;
299 339
300 - if (asar->ver == 1) {
340 + if (asar->dyn_ver == 1) {
301 341 limit = &asar->dyn->tbl[0].frp[0];
302 342 max = ARRAY_SIZE(asar->dyn->tbl[0].frp);
303 343 } else {
@@ -315,7 +355,9 @@ mt792x_asar_range_pwr(struct mt792x_phy *phy,
315 355 else
316 356 band = NL80211_BAND_2GHZ;
317 357
318 - return mt792x_asar_get_geo_pwr(phy, band, limit[idx]);
358 + /* 0xff: no dynamic limit, see mt792x_asar_get_geo_pwr() */
359 + return mt792x_asar_get_geo_pwr(phy, band,
360 + limit[idx] == 0xff ? 127 : limit[idx]);
319 361 }
320 362
321 363 int mt792x_init_acpi_sar_power(struct mt792x_phy *phy, bool set_default)
modified drivers/net/wireless/mediatek/mt76/mt792x_acpi_sar.h
@@ -105,6 +105,8 @@ struct mt792x_asar_fg {
105 105
106 106 struct mt792x_acpi_sar {
107 107 u8 ver;
108 + u8 dyn_ver;
109 + u8 geo_ver;
108 110 union {
109 111 struct mt792x_asar_dyn *dyn;
110 112 struct mt792x_asar_dyn_v2 *dyn_v2;
modified drivers/net/wireless/mediatek/mt76/mt7996/init.c
@@ -540,6 +540,7 @@ mt7996_init_wiphy(struct ieee80211_hw *hw, struct mtk_wed_device *wed)
540 540 ieee80211_hw_set(hw, NO_VIRTUAL_MONITOR);
541 541 ieee80211_hw_set(hw, SUPPORTS_MULTI_BSSID);
542 542 ieee80211_hw_set(hw, CHANCTX_STA_CSA);
543 + ieee80211_hw_set(hw, CONNECTION_MONITOR);
543 544
544 545 hw->max_tx_fragments = 4;
545 546 wiphy->txq_memory_limit = 32 << 20; /* 32 MiB */
@@ -1247,7 +1248,7 @@ static int mt7996_variant_fem_init(struct mt7996_dev *dev)
1247 1248 adie_ver = u32_get_bits(regval, MT_ADIE_VERSION_MASK);
1248 1249 idx = MT7976C_EFUSE_OFFSET % MT7996_EEPROM_BLOCK_SIZE;
1249 1250 is_7976c = adie_ver == 0x8a10 || adie_ver == 0x8b00 ||
1250 - adie_ver == 0x8c10 || buf[idx] == 0xc;
1251 + adie_ver == 0x8c10 || (!ret && buf[idx] == 0xc);
1251 1252
1252 1253 adie_id = u32_get_bits(regval, MT_ADIE_CHIP_ID_MASK);
1253 1254 if (adie_id == 0x7975 || adie_id == 0x7979 ||
modified drivers/net/wireless/mediatek/mt76/mt7996/main.c
@@ -310,7 +310,14 @@ int mt7996_vif_link_add(struct mt76_phy *mphy, struct ieee80211_vif *vif,
310 310 if (vif->type == NL80211_IFTYPE_AP)
311 311 return mt7996_mcu_mld_link_oper(dev, link_conf, link,
312 312 true);
313 - return 0;
313 +
314 + /* update the link address */
315 + ret = mt7996_mcu_add_dev_info(phy, vif, link_conf, mlink, true);
316 + if (ret)
317 + return ret;
318 +
319 + return mt7996_mcu_add_bss_info(phy, vif, link_conf, mlink,
320 + msta_link, true);
314 321 }
315 322
316 323 mlink->idx = __ffs64(~dev->mt76.vif_mask);
@@ -1426,6 +1433,7 @@ mt7996_mac_sta_event(struct mt7996_dev *dev, struct ieee80211_vif *vif,
1426 1433 else if (sta->mlo && links == BIT(link_id)) /* last link */
1427 1434 mt7996_mcu_teardown_mld_sta(dev, link,
1428 1435 msta_link);
1436 + msta_link->wcid.tx_info &= ~MT_WCID_TX_INFO_SET;
1429 1437 msta_link->wcid.sta_disabled = 1;
1430 1438 msta_link->wcid.sta = 0;
1431 1439 links = links & ~BIT(link_id);
modified drivers/net/wireless/mediatek/mt76/mt7996/mcu.h
@@ -284,6 +284,9 @@ struct mt7996_mcu_wed_rro_ba_delete_event {
284 284 __le16 len;
285 285
286 286 __le16 session_id;
287 + __le16 wlan_id;
288 + u8 tid;
289 + u8 __rsv1;
287 290 u8 __rsv2[2];
288 291 } __packed;
289 292
modified drivers/net/wireless/mediatek/mt76/tx.c
@@ -234,6 +234,8 @@ mt76_tx_check_non_aql(struct mt76_dev *dev, struct mt76_wcid *wcid,
234 234 if (!wcid || info->tx_time_est)
235 235 return;
236 236
237 + wcid = mt76_wcid_primary(wcid);
238 +
237 239 pending = atomic_dec_return(&wcid->non_aql_packets);
238 240 if (pending < 0)
239 241 atomic_cmpxchg(&wcid->non_aql_packets, pending, 0);
@@ -344,7 +346,8 @@ __mt76_tx_queue_skb(struct mt76_phy *phy, int qid, struct sk_buff *skb,
344 346 if (!non_aql)
345 347 return idx;
346 348
347 - pending = atomic_inc_return(&wcid->non_aql_packets);
349 + /* the hardware can report the completion on a different link */
350 + pending = atomic_inc_return(&mt76_wcid_primary(wcid)->non_aql_packets);
348 351 if (stop && pending >= MT_MAX_NON_AQL_PKT)
349 352 *stop = true;
350 353
@@ -506,7 +509,8 @@ mt76_txq_send_burst(struct mt76_phy *phy, struct mt76_queue *q,
506 509 return 0;
507 510 }
508 511
509 - if (atomic_read(&wcid->non_aql_packets) >= MT_MAX_NON_AQL_PKT)
512 + if (atomic_read(&mt76_wcid_primary(wcid)->non_aql_packets) >=
513 + MT_MAX_NON_AQL_PKT)
510 514 return 0;
511 515
512 516 skb = mt76_txq_dequeue(phy, mtxq);
@@ -603,7 +607,8 @@ mt76_txq_schedule_list(struct mt76_phy *phy, enum mt76_txq_id qid)
603 607 continue;
604 608 }
605 609
606 - if (atomic_read(&wcid->non_aql_packets) >= MT_MAX_NON_AQL_PKT)
610 + if (atomic_read(&mt76_wcid_primary(wcid)->non_aql_packets) >=
611 + MT_MAX_NON_AQL_PKT)
607 612 continue;
608 613 if (dev->queue_ops->tx_cleanup &&
609 614 q->queued + 2 * MT_TXQ_FREE_THR >= q->ndesc) {
@@ -675,7 +680,8 @@ mt76_txq_schedule_pending_wcid(struct mt76_phy *phy, struct mt76_wcid *wcid,
675 680 if ((dev->drv->drv_flags & MT_DRV_HW_MGMT_TXQ) &&
676 681 !(info->flags & IEEE80211_TX_CTL_HW_80211_ENCAP) &&
677 682 !ieee80211_is_data_present(hdr->frame_control) &&
678 - (!ieee80211_is_bufferable_mmpdu(skb) ||
683 + (!(wcid->tx_info & MT_WCID_TX_INFO_SET) ||
684 + !ieee80211_is_bufferable_mmpdu(skb) ||
679 685 ieee80211_is_deauth(hdr->frame_control) ||
680 686 ieee80211_is_disassoc(hdr->frame_control) ||
681 687 head == &wcid->tx_offchannel))
modified drivers/net/wireless/nxp/nxpwifi/11n.c
@@ -451,7 +451,7 @@ void
451 451 nxpwifi_11n_delete_tx_ba_stream_tbl_entry(struct nxpwifi_private *priv,
452 452 struct nxpwifi_tx_ba_stream_tbl *tbl)
453 453 {
454 - if (!tbl || nxpwifi_is_tx_ba_stream_ptr_valid(priv, tbl))
454 + if (!tbl || !nxpwifi_is_tx_ba_stream_ptr_valid(priv, tbl))
455 455 return;
456 456
457 457 nxpwifi_dbg(priv->adapter, INFO,
modified drivers/net/wireless/nxp/nxpwifi/11n_aggr.c
@@ -168,6 +168,7 @@ nxpwifi_11n_aggregate_pkt(struct nxpwifi_private *priv,
168 168
169 169 if (!nxpwifi_is_ralist_valid(priv, pra_list, ptrindex)) {
170 170 spin_unlock_bh(&priv->wmm.ra_list_spinlock);
171 + nxpwifi_write_data_complete(adapter, skb_aggr, 1, -1);
171 172 return -ENOENT;
172 173 }
173 174
modified drivers/net/wireless/nxp/nxpwifi/11n_rxreorder.c
@@ -205,11 +205,12 @@ void nxpwifi_11n_del_rx_reorder_tbl_by_ta(struct nxpwifi_private *priv, u8 *ta)
205 205 return;
206 206
207 207 for (i = 0; i < MAX_NUM_TID; i++) {
208 - guard(rcu)();
209 - list_for_each_entry_rcu(tbl, &priv->rx_reorder_tbl_ptr[i], list) {
210 - if (!memcmp(tbl->ta, ta, ETH_ALEN)) {
211 - INIT_LIST_HEAD(&tbl->tmp_list);
212 - list_add_tail(&tbl->tmp_list, &to_delete);
208 + scoped_guard(rcu) {
209 + list_for_each_entry_rcu(tbl, &priv->rx_reorder_tbl_ptr[i], list) {
210 + if (!memcmp(tbl->ta, ta, ETH_ALEN)) {
211 + INIT_LIST_HEAD(&tbl->tmp_list);
212 + list_add_tail(&tbl->tmp_list, &to_delete);
213 + }
213 214 }
214 215 }
215 216
modified drivers/net/wireless/nxp/nxpwifi/cfg80211.c
@@ -1539,9 +1539,11 @@ nxpwifi_cfg80211_del_station(struct wiphy *wiphy, struct wireless_dev *wdev,
1539 1539
1540 1540 eth_zero_addr(deauth_mac);
1541 1541
1542 + rcu_read_lock();
1542 1543 sta_node = nxpwifi_get_sta_entry(priv, params->mac);
1543 1544 if (sta_node)
1544 1545 ether_addr_copy(deauth_mac, params->mac);
1546 + rcu_read_unlock();
1545 1547
1546 1548 if (is_valid_ether_addr(deauth_mac)) {
1547 1549 ret = nxpwifi_uap_sta_deauth(priv, deauth_mac);
@@ -3323,6 +3325,7 @@ nxpwifi_cfg80211_authenticate(struct wiphy *wiphy,
3323 3325 struct nxpwifi_adapter *adapter = priv->adapter;
3324 3326 struct sk_buff *skb;
3325 3327 u16 pkt_len, auth_alg;
3328 + size_t frame_len;
3326 3329 int ret;
3327 3330 struct ieee80211_mgmt *mgmt;
3328 3331 struct nxpwifi_txinfo *tx_info;
@@ -3396,13 +3399,25 @@ nxpwifi_cfg80211_authenticate(struct wiphy *wiphy,
3396 3399
3397 3400 nxpwifi_cancel_scan(adapter);
3398 3401
3399 - pkt_len = (u16)req->ie_len + req->auth_data_len +
3400 - NXPWIFI_MGMT_HEADER_LEN + NXPWIFI_AUTH_BODY_LEN;
3402 + frame_len = req->ie_len + req->auth_data_len +
3403 + sizeof(struct ieee80211_hdr_3addr) + NXPWIFI_AUTH_BODY_LEN;
3401 3404
3402 3405 if (req->auth_data_len >= 4)
3403 - pkt_len -= 4;
3406 + frame_len -= 4;
3407 +
3408 + /* nxpwifi_form_mgmt_frame() inserts address4, so the frame handed to
3409 + * the firmware is ETH_ALEN longer than the one built here.
3410 + */
3411 + if (frame_len > U16_MAX - ETH_ALEN) {
3412 + nxpwifi_dbg(adapter, ERROR,
3413 + "auth frame too long: %zu bytes\n", frame_len);
3414 + return -EINVAL;
3415 + }
3416 + pkt_len = frame_len + ETH_ALEN;
3404 3417
3405 - mgmt = kzalloc(pkt_len, GFP_KERNEL);
3418 + mgmt = kzalloc(frame_len, GFP_KERNEL);
3419 + if (!mgmt)
3420 + return -ENOMEM;
3406 3421
3407 3422 skb = dev_alloc_skb(NXPWIFI_MIN_DATA_HEADER_LEN +
3408 3423 NXPWIFI_MGMT_FRAME_HEADER_SIZE +
@@ -3410,6 +3425,7 @@ nxpwifi_cfg80211_authenticate(struct wiphy *wiphy,
3410 3425 if (!skb) {
3411 3426 nxpwifi_dbg(adapter, ERROR,
3412 3427 "allocate skb failed for management frame\n");
3428 + kfree(mgmt);
3413 3429 return -ENOMEM;
3414 3430 }
3415 3431
@@ -3448,7 +3464,7 @@ nxpwifi_cfg80211_authenticate(struct wiphy *wiphy,
3448 3464 memcpy((u8 *)varptr, req->ie, req->ie_len);
3449 3465 }
3450 3466
3451 - nxpwifi_form_mgmt_frame(skb, (const u8 *)mgmt, pkt_len);
3467 + nxpwifi_form_mgmt_frame(skb, (const u8 *)mgmt, frame_len);
3452 3468 kfree(mgmt);
3453 3469 priv->auth_flag = HOST_MLME_AUTH_PENDING;
3454 3470 priv->auth_alg = auth_alg;
@@ -3729,8 +3745,9 @@ int nxpwifi_init_channel_scan_gap(struct nxpwifi_adapter *adapter)
3729 3745 * additional active scan request for hidden SSIDs on passive channels.
3730 3746 */
3731 3747 adapter->num_in_chan_stats = 2 * (n_channels_bg + n_channels_a);
3732 - adapter->chan_stats = vmalloc(array_size(sizeof(*adapter->chan_stats),
3733 - adapter->num_in_chan_stats));
3748 + adapter->chan_stats = kcalloc(adapter->num_in_chan_stats,
3749 + sizeof(*adapter->chan_stats),
3750 + GFP_KERNEL);
3734 3751
3735 3752 if (!adapter->chan_stats)
3736 3753 return -ENOMEM;
modified drivers/net/wireless/nxp/nxpwifi/init.c
@@ -328,7 +328,7 @@ static void nxpwifi_invalidate_lists(struct nxpwifi_adapter *adapter)
328 328 static void
329 329 nxpwifi_adapter_cleanup(struct nxpwifi_adapter *adapter)
330 330 {
331 - timer_delete(&adapter->wakeup_timer);
331 + timer_delete_sync(&adapter->wakeup_timer);
332 332 nxpwifi_cancel_all_pending_cmd(adapter);
333 333 wake_up_interruptible(&adapter->cmd_wait_q.wait);
334 334 wake_up_interruptible(&adapter->hs_activate_wait_q);
modified drivers/net/wireless/nxp/nxpwifi/main.c
@@ -644,7 +644,7 @@ static int _nxpwifi_fw_dpc(const struct firmware *firmware, void *context)
644 644 goto done;
645 645
646 646 err_add_intf:
647 - vfree(adapter->chan_stats);
647 + kfree(adapter->chan_stats);
648 648 err_init_chan_scan:
649 649 wiphy_unregister(adapter->wiphy);
650 650 wiphy_free(adapter->wiphy);
@@ -1384,7 +1384,7 @@ static void nxpwifi_uninit_sw(struct nxpwifi_adapter *adapter)
1384 1384 wiphy_free(adapter->wiphy);
1385 1385 adapter->wiphy = NULL;
1386 1386
1387 - vfree(adapter->chan_stats);
1387 + kfree(adapter->chan_stats);
1388 1388 nxpwifi_free_cmd_buffers(adapter);
1389 1389 }
1390 1390
modified drivers/net/wireless/nxp/nxpwifi/uap_event.c
@@ -75,6 +75,7 @@ nxpwifi_uap_event_sta_deauth(struct nxpwifi_private *priv)
75 75 nxpwifi_del_tx_ba_stream_tbl_by_ra(priv, deauth_mac);
76 76 }
77 77 nxpwifi_wmm_del_peer_ra_list(priv, deauth_mac);
78 + nxpwifi_del_sta_entry(priv, deauth_mac);
78 79
79 80 return 0;
80 81 }
modified drivers/net/wireless/nxp/nxpwifi/util.c
@@ -1041,19 +1041,23 @@ nxpwifi_set_sta_ht_cap(struct nxpwifi_private *priv, const u8 *ies,
1041 1041 }
1042 1042 }
1043 1043
1044 - /* Delete a station from list; called under cfg80211 mutex. */
1044 + /* Delete a station from list. */
1045 1045
1046 1046 void nxpwifi_del_sta_entry(struct nxpwifi_private *priv, const u8 *mac)
1047 1047 {
1048 1048 struct nxpwifi_sta_node *node;
1049 1049
1050 - list_for_each_entry_rcu(node, &priv->sta_list, list) {
1050 + spin_lock_bh(&priv->sta_list_spinlock);
1051 +
1052 + list_for_each_entry(node, &priv->sta_list, list) {
1051 1053 if (!memcmp(node->mac_addr, mac, ETH_ALEN)) {
1052 1054 list_del_rcu(&node->list);
1053 1055 kfree_rcu(node, rcu);
1054 1056 break;
1055 1057 }
1056 1058 }
1059 +
1060 + spin_unlock_bh(&priv->sta_list_spinlock);
1057 1061 }
1058 1062
1059 1063 /* Delete all stations from list. */
modified drivers/net/xen-netfront.c
@@ -1234,8 +1234,16 @@ static int handle_incoming_queue(struct netfront_queue *queue,
1234 1234 while ((skb = __skb_dequeue(rxq)) != NULL) {
1235 1235 int pull_to = NETFRONT_SKB_CB(skb)->pull_to;
1236 1236
1237 - if (pull_to > skb_headlen(skb))
1238 - __pskb_pull_tail(skb, pull_to - skb_headlen(skb));
1237 + /* pull_to comes from the first slot's length, which the
1238 + * backend controls. Make sure the head holds at least an
1239 + * Ethernet header for eth_type_trans().
1240 + */
1241 + if (!pskb_may_pull(skb, max(pull_to, ETH_HLEN))) {
1242 + kfree_skb(skb);
1243 + packets_dropped++;
1244 + queue->info->netdev->stats.rx_errors++;
1245 + continue;
1246 + }
1239 1247
1240 1248 /* Ethernet work: Delayed to here as it peeks the header. */
1241 1249 skb->protocol = eth_type_trans(skb, queue->info->netdev);
@@ -1338,8 +1346,10 @@ err:
1338 1346 skb->data_len = rx->status;
1339 1347 skb->len += rx->status;
1340 1348
1341 - if (unlikely(xennet_fill_frags(queue, skb, &tmpq)))
1349 + if (unlikely(xennet_fill_frags(queue, skb, &tmpq))) {
1350 + __skb_queue_head(&tmpq, skb);
1342 1351 goto err;
1352 + }
1343 1353
1344 1354 if (rx->flags & XEN_NETRXF_csum_blank)
1345 1355 skb->ip_summed = CHECKSUM_PARTIAL;
modified drivers/nvme/host/core.c
@@ -598,6 +598,7 @@ bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
598 598 break;
599 599 case NVME_CTRL_RESETTING:
600 600 switch (old_state) {
601 + case NVME_CTRL_NEW:
601 602 case NVME_CTRL_LIVE:
602 603 changed = true;
603 604 atomic_long_inc(&ctrl->nr_reset);
@@ -2616,10 +2617,19 @@ static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_ns_info *info)
2616 2617 set_capacity_and_notify(ns->head->disk, get_capacity(ns->disk));
2617 2618 set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info));
2618 2619 nvme_mpath_revalidate_paths(ns->head);
2619 - ret = nvme_mpath_revalidate_zones(ns->head);
2620 2620
2621 2621 unfreeze_head_queue:
2622 2622 blk_mq_unfreeze_queue(ns->head->disk->queue, memflags);
2623 +
2624 + /*
2625 + * Wait until the head queue is unfrozen before revalidating
2626 + * its zones. blk_revalidate_disk_zones() takes the queue limits
2627 + * lock and then freezes the queue on its own, so it must not be
2628 + * called with the queue already frozen. This is also what
2629 + * nvme_update_ns_info_block() does for ns->disk.
2630 + */
2631 + if (!ret)
2632 + ret = nvme_mpath_revalidate_zones(ns->head);
2623 2633 }
2624 2634
2625 2635 return ret;
modified drivers/nvme/target/core.c
@@ -1325,7 +1325,7 @@ static int nvmet_req_alloc_p2pmem_sgls(struct pci_dev *p2p_dev,
1325 1325
1326 1326 return 0;
1327 1327 out_free_sg:
1328 - pci_p2pmem_free_sgl(req->p2p_dev, req->sg);
1328 + pci_p2pmem_free_sgl(p2p_dev, req->sg);
1329 1329 out_err:
1330 1330 return -ENOMEM;
1331 1331 }
modified drivers/nvme/target/pr.c
@@ -51,6 +51,8 @@ u16 nvmet_set_feat_resv_notif_mask(struct nvmet_req *req, u32 mask)
51 51
52 52 if (nsid != U32_MAX) {
53 53 status = nvmet_req_find_ns(req);
54 + if (status == (NVME_SC_INVALID_NS | NVME_STATUS_DNR))
55 + return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
54 56 if (status)
55 57 return status;
56 58 if (!req->ns->pr.enable)
@@ -75,6 +77,8 @@ u16 nvmet_get_feat_resv_notif_mask(struct nvmet_req *req)
75 77 u16 status;
76 78
77 79 status = nvmet_req_find_ns(req);
80 + if (status == (NVME_SC_INVALID_NS | NVME_STATUS_DNR))
81 + return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
78 82 if (status)
79 83 return status;
80 84
modified drivers/pci/controller/dwc/pcie-dw-rockchip.c
@@ -421,23 +421,9 @@ static void rockchip_pcie_stop_link(struct dw_pcie *pci)
421 421 static int rockchip_pcie_host_init(struct dw_pcie_rp *pp)
422 422 {
423 423 struct dw_pcie *pci = to_dw_pcie_from_pp(pp);
424 - struct rockchip_pcie *rockchip = to_rockchip_pcie(pci);
425 - struct device *dev = rockchip->pci.dev;
426 - int irq, ret;
427 -
428 - irq = of_irq_get_byname(dev->of_node, "legacy");
429 - if (irq < 0)
430 - return irq;
431 424
432 425 pci->dbi_base2 = pci->dbi_base + PCIE_TYPE0_HDR_DBI2_OFFSET;
433 426
434 - ret = rockchip_pcie_init_irq_domain(rockchip);
435 - if (ret < 0)
436 - dev_err(dev, "failed to init irq domain\n");
437 -
438 - irq_set_chained_handler_and_data(irq, rockchip_pcie_intx_handler,
439 - rockchip);
440 -
441 427 rockchip_pcie_configure_l1ss(pci);
442 428 rockchip_pcie_enable_l0s(pci);
443 429 pp->bridge->reset_root_port = rockchip_pcie_rc_reset_root_port;
@@ -730,6 +716,19 @@ static int rockchip_pcie_configure_rc(struct platform_device *pdev,
730 716 PCIE_CLIENT_SET_MODE(PCIE_CLIENT_MODE_RC),
731 717 PCIE_CLIENT_GENERAL_CON);
732 718
719 + irq = of_irq_get_byname(dev->of_node, "legacy");
720 + if (irq < 0)
721 + return irq;
722 +
723 + ret = rockchip_pcie_init_irq_domain(rockchip);
724 + if (ret < 0) {
725 + dev_err(dev, "failed to init irq domain\n");
726 + return ret;
727 + }
728 +
729 + irq_set_chained_handler_and_data(irq, rockchip_pcie_intx_handler,
730 + rockchip);
731 +
733 732 pp = &rockchip->pci.pp;
734 733 pp->ops = &rockchip_pcie_host_ops;
735 734
modified drivers/pci/controller/pci-hyperv.c
@@ -1040,19 +1040,38 @@ static void put_pcichild(struct hv_pci_dev *hpdev)
1040 1040
1041 1041 /*
1042 1042 * There is no good way to get notified from vmbus_onoffer_rescind(),
1043 - * so let's use polling here, since this is not a hot path.
1043 + * so let's use polling here, since this is not a hot path. If
1044 + * wait_for_response() has been polling for 2 minutes
1045 + * without either a rescind or completion, add a warning.
1044 1046 */
1047 + #define PCI_RESPONSE_WARN_POLL_COUNT 1200
1048 +
1045 1049 static int wait_for_response(struct hv_device *hdev,
1046 - struct completion *comp)
1050 + struct completion *comp,
1051 + const char *msg_type)
1047 1052 {
1053 + u64 counter = 0;
1054 +
1048 1055 while (true) {
1049 1056 if (hdev->channel->rescind) {
1050 1057 dev_warn_once(&hdev->device, "The device is gone.\n");
1051 1058 return -ENODEV;
1052 1059 }
1053 1060
1054 - if (wait_for_completion_timeout(comp, HZ / 10))
1061 + counter++;
1062 +
1063 + if (wait_for_completion_timeout(comp, HZ / 10)) {
1064 + if (counter > PCI_RESPONSE_WARN_POLL_COUNT)
1065 + dev_warn(&hdev->device,
1066 + "Late %s completion arrived.\n", msg_type);
1055 1067 break;
1068 + }
1069 +
1070 + if (counter == PCI_RESPONSE_WARN_POLL_COUNT) {
1071 + dev_err(&hdev->device,
1072 + "%s stuck waiting for response, relid = %u\n",
1073 + msg_type, hdev->channel->offermsg.child_relid);
1074 + }
1056 1075 }
1057 1076
1058 1077 return 0;
@@ -1518,7 +1537,8 @@ static int hv_read_config_block(struct pci_dev *pdev, void *buf,
1518 1537 if (ret)
1519 1538 return ret;
1520 1539
1521 - ret = wait_for_response(hbus->hdev, &comp_pkt.comp_pkt.host_event);
1540 + ret = wait_for_response(hbus->hdev, &comp_pkt.comp_pkt.host_event,
1541 + "PCI_READ_BLOCK");
1522 1542 if (ret)
1523 1543 return ret;
1524 1544
@@ -1607,7 +1627,8 @@ static int hv_write_config_block(struct pci_dev *pdev, void *buf,
1607 1627 if (ret)
1608 1628 return ret;
1609 1629
1610 - ret = wait_for_response(hbus->hdev, &comp_pkt.host_event);
1630 + ret = wait_for_response(hbus->hdev, &comp_pkt.host_event,
1631 + "PCI_WRITE_BLOCK");
1611 1632 if (ret)
1612 1633 return ret;
1613 1634
@@ -2624,7 +2645,8 @@ static struct hv_pci_dev *new_pcichild_device(struct hv_pcibus_device *hbus,
2624 2645 if (ret)
2625 2646 goto error;
2626 2647
2627 - if (wait_for_response(hbus->hdev, &comp_pkt.host_event))
2648 + if (wait_for_response(hbus->hdev, &comp_pkt.host_event,
2649 + "PCI_QUERY_RESOURCE_REQUIREMENTS"))
2628 2650 goto error;
2629 2651
2630 2652 hpdev->desc = *desc;
@@ -3256,7 +3278,8 @@ static int hv_pci_protocol_negotiation(struct hv_device *hdev,
3256 3278 (unsigned long)pkt, VM_PKT_DATA_INBAND,
3257 3279 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3258 3280 if (!ret)
3259 - ret = wait_for_response(hdev, &comp_pkt.host_event);
3281 + ret = wait_for_response(hdev, &comp_pkt.host_event,
3282 + "PCI_QUERY_PROTOCOL_VERSION");
3260 3283
3261 3284 if (ret) {
3262 3285 dev_err(&hdev->device,
@@ -3476,7 +3499,8 @@ enter_d0_retry:
3476 3499 (unsigned long)pkt, VM_PKT_DATA_INBAND,
3477 3500 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3478 3501 if (!ret)
3479 - ret = wait_for_response(hdev, &comp_pkt.host_event);
3502 + ret = wait_for_response(hdev, &comp_pkt.host_event,
3503 + "PCI_BUS_D0ENTRY");
3480 3504
3481 3505 if (ret)
3482 3506 goto exit;
@@ -3553,7 +3577,8 @@ static int hv_pci_query_relations(struct hv_device *hdev)
3553 3577 ret = vmbus_sendpacket(hdev->channel, &message, sizeof(message),
3554 3578 0, VM_PKT_DATA_INBAND, 0);
3555 3579 if (!ret)
3556 - ret = wait_for_response(hdev, &comp);
3580 + ret = wait_for_response(hdev, &comp,
3581 + "PCI_QUERY_BUS_RELATIONS");
3557 3582
3558 3583 /*
3559 3584 * In the case of fast device addition/removal, it's possible that
@@ -3644,7 +3669,8 @@ static int hv_send_resources_allocated(struct hv_device *hdev)
3644 3669 VM_PKT_DATA_INBAND,
3645 3670 VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
3646 3671 if (!ret)
3647 - ret = wait_for_response(hdev, &comp_pkt.host_event);
3672 + ret = wait_for_response(hdev, &comp_pkt.host_event,
3673 + "PCI_RESOURCE_ASSIGNED");
3648 3674 if (ret)
3649 3675 break;
3650 3676
@@ -4155,6 +4181,9 @@ static struct hv_driver hv_pci_drv = {
4155 4181 .remove = hv_pci_remove,
4156 4182 .suspend = hv_pci_suspend,
4157 4183 .resume = hv_pci_resume,
4184 + .driver = {
4185 + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
4186 + },
4158 4187 };
4159 4188
4160 4189 static void __exit exit_hv_pci_drv(void)
modified drivers/pci/pci.c
@@ -1246,9 +1246,11 @@ static int pci_dev_wait(struct pci_dev *dev, char *reset_type, int timeout)
1246 1246 * initialize.
1247 1247 *
1248 1248 * If the device is below a Root Port with Configuration RRS
1249 - * Software Visibility enabled, reading the Vendor ID returns a
1249 + * Software Visibility enabled, reading the Vendor ID may return a
1250 1250 * special data value if the device responded with RRS. Read the
1251 - * Vendor ID until we get non-RRS status.
1251 + * Vendor ID until we get non-RRS status and something other than
1252 + * ~0. The Vendor ID of VFs reads ~0, so check their Command
1253 + * register instead.
1252 1254 *
1253 1255 * If there's no Root Port or Configuration RRS Software Visibility
1254 1256 * is not enabled, the device may still respond with RRS, but
@@ -1268,8 +1270,13 @@ static int pci_dev_wait(struct pci_dev *dev, char *reset_type, int timeout)
1268 1270
1269 1271 if (root && root->config_rrs_sv) {
1270 1272 pci_read_config_dword(dev, PCI_VENDOR_ID, &id);
1271 - if (!pci_bus_rrs_vendor_id(id))
1272 - break;
1273 + if (!pci_bus_rrs_vendor_id(id)) {
1274 + if (PCI_POSSIBLE_ERROR(id) && dev->is_virtfn)
1275 + pci_read_config_dword(dev, PCI_COMMAND,
1276 + &id);
1277 + if (!PCI_POSSIBLE_ERROR(id))
1278 + break;
1279 + }
1273 1280 } else {
1274 1281 pci_read_config_dword(dev, PCI_COMMAND, &id);
1275 1282 if (!PCI_POSSIBLE_ERROR(id))
modified drivers/pci/pcie/aer.c
@@ -428,7 +428,8 @@ void pci_aer_init(struct pci_dev *dev)
428 428 * Advisory Non-Fatal Errors are masked by default (PCIe r7.0, sec
429 429 * 7.8.4.6).
430 430 */
431 - if (pcie_aer_is_native(dev) && dev->devcap & PCI_EXP_DEVCAP_RBER)
431 + if (pcie_aer_is_native(dev) && dev->devcap & PCI_EXP_DEVCAP_RBER &&
432 + !dev->no_aer_anfe)
432 433 pci_clear_and_set_config_dword(dev,
433 434 dev->aer_cap + PCI_ERR_COR_MASK,
434 435 PCI_ERR_COR_ADV_NFAT, 0);
@@ -1360,8 +1361,10 @@ static DEFINE_KFIFO(aer_recover_ring, struct aer_recover_entry,
1360 1361
1361 1362 static void aer_recover_work_func(struct work_struct *work)
1362 1363 {
1364 + struct aer_capability_regs *regs;
1363 1365 struct aer_recover_entry entry;
1364 1366 struct pci_dev *pdev;
1367 + u32 err;
1365 1368
1366 1369 while (kfifo_get(&aer_recover_ring, &entry)) {
1367 1370 pdev = pci_get_domain_bus_and_slot(entry.domain, entry.bus,
@@ -1375,6 +1378,12 @@ static void aer_recover_work_func(struct work_struct *work)
1375 1378 }
1376 1379 pci_print_aer(pdev, entry.severity, entry.regs);
1377 1380
1381 + regs = entry.regs;
1382 + if (entry.severity == AER_CORRECTABLE)
1383 + err = regs->cor_status & ~regs->cor_mask;
1384 + else
1385 + err = regs->uncor_status & ~regs->uncor_mask;
1386 +
1378 1387 /*
1379 1388 * Memory for aer_capability_regs(entry.regs) is being
1380 1389 * allocated from the ghes_estatus_pool to protect it from
@@ -1385,12 +1394,14 @@ static void aer_recover_work_func(struct work_struct *work)
1385 1394 ghes_estatus_pool_region_free((unsigned long)entry.regs,
1386 1395 sizeof(struct aer_capability_regs));
1387 1396
1388 - if (entry.severity == AER_NONFATAL)
1389 - pcie_do_recovery(pdev, pci_channel_io_normal,
1390 - aer_root_reset);
1391 - else if (entry.severity == AER_FATAL)
1392 - pcie_do_recovery(pdev, pci_channel_io_frozen,
1393 - aer_root_reset);
1397 + if (err) {
1398 + if (entry.severity == AER_NONFATAL)
1399 + pcie_do_recovery(pdev, pci_channel_io_normal,
1400 + aer_root_reset);
1401 + else if (entry.severity == AER_FATAL)
1402 + pcie_do_recovery(pdev, pci_channel_io_frozen,
1403 + aer_root_reset);
1404 + }
1394 1405 pci_dev_put(pdev);
1395 1406 }
1396 1407 }
modified drivers/pci/quirks.c
@@ -2574,6 +2574,17 @@ static void quirk_p64h2_1k_io(struct pci_dev *dev)
2574 2574 }
2575 2575 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1460, quirk_p64h2_1k_io);
2576 2576
2577 + /*
2578 + * Unmasking Advisory Non-Fatal Errors on the Apple T2 Secure Enclave
2579 + * causes a MacBookPro16,1 to lose power. Set this before pci_aer_init()
2580 + * so that it leaves the ANFE mask bit unchanged.
2581 + */
2582 + static void quirk_no_aer_anfe(struct pci_dev *dev)
2583 + {
2584 + dev->no_aer_anfe = 1;
2585 + }
2586 + DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_APPLE, 0x1802, quirk_no_aer_anfe);
2587 +
2577 2588 /*
2578 2589 * Under some circumstances, AER is not linked with extended capabilities.
2579 2590 * Force it to be linked by setting the corresponding control bit in the
@@ -5623,6 +5634,18 @@ static void quirk_no_flr_snet(struct pci_dev *dev)
5623 5634 }
5624 5635 DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_SOLIDRUN, 0x1000, quirk_no_flr_snet);
5625 5636
5637 + /* Some Samsung SSDs advertise Immediate Readiness but aren't ready after FLR */
5638 + static void quirk_no_imm_ready(struct pci_dev *dev)
5639 + {
5640 + if (!dev->imm_ready)
5641 + return;
5642 +
5643 + pci_info(dev, "Ignoring incorrectly advertised Immediate Readiness support\n");
5644 + dev->imm_ready = 0;
5645 + }
5646 + DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80c, quirk_no_imm_ready);
5647 + DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SAMSUNG, 0xa80d, quirk_no_imm_ready);
5648 +
5626 5649 static void quirk_no_ext_tags(struct pci_dev *pdev)
5627 5650 {
5628 5651 struct pci_host_bridge *bridge = pci_find_host_bridge(pdev->bus);
modified drivers/pinctrl/pinctrl-amd.c
@@ -886,6 +886,15 @@ static void amd_gpio_irq_init(struct amd_gpio *gpio_dev)
886 886
887 887 mask = BIT(WAKE_CNTRL_OFF_S0I3) | BIT(WAKE_CNTRL_OFF_S3);
888 888
889 + #ifdef CONFIG_ACPI
890 + /*
891 + * Platforms without _AEI leave GPIO wake sources to firmware, so
892 + * preserve their S4 wake bits.
893 + */
894 + if (acpi_has_method(ACPI_HANDLE(&gpio_dev->pdev->dev), "_AEI"))
895 + mask |= BIT(WAKE_CNTRL_OFF_S4);
896 + #endif
897 +
889 898 for (i = 0; i < desc->npins; i++) {
890 899 int pin = desc->pins[i].number;
891 900 const struct pin_desc *pd = pin_desc_get(gpio_dev->pctrl, pin);
modified drivers/pinctrl/qcom/pinctrl-hawi.c
@@ -47,6 +47,7 @@
47 47 .intr_wakeup_present_bit = 6, \
48 48 .intr_wakeup_enable_bit = 7, \
49 49 .intr_target_bit = 8, \
50 + .intr_target_width = 4, \
50 51 .intr_target_kpss_val = 3, \
51 52 .intr_raw_status_bit = 4, \
52 53 .intr_polarity_bit = 1, \
modified drivers/pinctrl/qcom/pinctrl-ipq5018.c
@@ -361,7 +361,7 @@ static const char * const blsp1_uart0_groups[] = {
361 361 };
362 362
363 363 static const char * const gcc_plltest_groups[] = {
364 - "gpio10", "gpio12",
364 + "gpio10",
365 365 };
366 366
367 367 static const char * const gcc_tlmm_groups[] = {
@@ -539,7 +539,7 @@ static const char * const qdss_tracectl_b_groups[] = {
539 539 };
540 540
541 541 static const char * const pwm0_groups[] = {
542 - "gpio42",
542 + "gpio42", "gpio46",
543 543 };
544 544
545 545 static const char * const qdss_cti_trig_out_b0_groups[] = {
@@ -547,7 +547,7 @@ static const char * const qdss_cti_trig_out_b0_groups[] = {
547 547 };
548 548
549 549 static const char * const pwm1_groups[] = {
550 - "gpio43",
550 + "gpio43", "gpio1",
551 551 };
552 552
553 553 static const char * const qdss_cti_trig_in_b0_groups[] = {
@@ -555,7 +555,7 @@ static const char * const qdss_cti_trig_in_b0_groups[] = {
555 555 };
556 556
557 557 static const char * const pwm2_groups[] = {
558 - "gpio44",
558 + "gpio12", "gpio44",
559 559 };
560 560
561 561 static const char * const qdss_cti_trig_out_b1_groups[] = {
@@ -563,7 +563,7 @@ static const char * const qdss_cti_trig_out_b1_groups[] = {
563 563 };
564 564
565 565 static const char * const pwm3_groups[] = {
566 - "gpio45",
566 + "gpio45", "gpio30", "gpio13",
567 567 };
568 568
569 569 static const char * const qdss_cti_trig_in_b1_groups[] = {
@@ -677,7 +677,7 @@ static const struct pinfunction ipq5018_functions[] = {
677 677
678 678 static const struct msm_pingroup ipq5018_groups[] = {
679 679 PINGROUP(0, atest_char, _, qdss_cti_trig_out_a0, wci_txd, wci_rxd, xfem, _, _, _),
680 - PINGROUP(1, atest_char, _, qdss_cti_trig_in_a0, wci_txd, wci_rxd, xfem, _, _, _),
680 + PINGROUP(1, atest_char, pwm1, qdss_cti_trig_in_a0, wci_txd, wci_rxd, xfem, _, _, _),
681 681 PINGROUP(2, atest_char, _, qdss_cti_trig_out_a1, wci_txd, wci_rxd, xfem, _, _, _),
682 682 PINGROUP(3, atest_char, _, qdss_cti_trig_in_a1, wci_txd, wci_rxd, xfem, _, _, _),
683 683 PINGROUP(4, sdc1_data, qspi_data, blsp1_spi1, btss, dbg_out, qdss_traceclk_a, _, burn0, _),
@@ -688,8 +688,8 @@ static const struct msm_pingroup ipq5018_groups[] = {
688 688 PINGROUP(9, sdc1_clk, qspi_clk, _, qdss_tracedata_a, _, _, _, _, _),
689 689 PINGROUP(10, blsp0_spi, blsp1_uart0, led0, gcc_plltest, qdss_tracedata_a, _, _, _, _),
690 690 PINGROUP(11, blsp0_spi, blsp1_uart0, _, gcc_tlmm, qdss_tracedata_a, _, _, _, _),
691 - PINGROUP(12, blsp0_spi, blsp0_i2c, blsp1_uart0, _, gcc_plltest, qdss_tracedata_a, _, _, _),
692 - PINGROUP(13, blsp0_spi, blsp0_i2c, blsp1_uart0, _, qdss_tracedata_a, _, _, _, _),
691 + PINGROUP(12, blsp0_spi, blsp0_i2c, blsp1_uart0, _, pwm2, qdss_tracedata_a, _, _, _),
692 + PINGROUP(13, blsp0_spi, blsp0_i2c, blsp1_uart0, pwm3, qdss_tracedata_a, _, _, _, _),
693 693 PINGROUP(14, pcie0_clk, _, _, cri_trng0, qdss_tracedata_a, _, _, _, _),
694 694 PINGROUP(15, _, _, cri_trng1, qdss_tracedata_a, _, _, _, _, _),
695 695 PINGROUP(16, pcie0_wake, _, _, cri_trng, qdss_tracedata_a, _, _, _, _),
@@ -706,7 +706,7 @@ static const struct msm_pingroup ipq5018_groups[] = {
706 706 PINGROUP(27, audio_txmclk, wsa_swrm, audio_txmclk, blsp2_spi, btss, _, qdss_tracedata_b, _, _),
707 707 PINGROUP(28, audio_txbclk, wsa_swrm, blsp0_uart1, btss, qdss_tracedata_b, _, _, _, _),
708 708 PINGROUP(29, audio_txfsync, _, blsp0_uart1, _, qdss_tracedata_b, _, _, _, _),
709 - PINGROUP(30, audio_txd, led2, led0, _, _, _, _, _, _),
709 + PINGROUP(30, audio_txd, led2, led0, pwm3, _, _, _, _, _),
710 710 PINGROUP(31, blsp2_spi0, blsp1_uart1, _, qdss_tracedata_b, eud_gpio, _, _, _, _),
711 711 PINGROUP(32, blsp2_spi0, blsp1_uart1, _, qdss_tracedata_b, eud_gpio, _, _, _, _),
712 712 PINGROUP(33, blsp2_i2c0, blsp2_spi0, blsp1_uart1, _, qdss_tracedata_b, eud_gpio, _, _, _),
@@ -722,7 +722,7 @@ static const struct msm_pingroup ipq5018_groups[] = {
722 722 PINGROUP(43, pwm1, qdss_cti_trig_in_b0, wci_txd, wci_rxd, xfem, _, _, _, _),
723 723 PINGROUP(44, pwm2, qdss_cti_trig_out_b1, wci_txd, wci_rxd, xfem, _, _, _, _),
724 724 PINGROUP(45, pwm3, qdss_cti_trig_in_b1, wci_txd, wci_rxd, xfem, _, _, _, _),
725 - PINGROUP(46, led0, _, _, _, _, _, _, _, _),
725 + PINGROUP(46, led0, pwm0, _, _, _, _, _, _, _),
726 726 };
727 727
728 728 static const struct msm_pinctrl_soc_data ipq5018_pinctrl = {
modified drivers/pinctrl/qcom/pinctrl-maili.c
@@ -47,6 +47,7 @@
47 47 .intr_wakeup_present_bit = 6, \
48 48 .intr_wakeup_enable_bit = 7, \
49 49 .intr_target_bit = 8, \
50 + .intr_target_width = 4, \
50 51 .intr_target_kpss_val = 3, \
51 52 .intr_raw_status_bit = 4, \
52 53 .intr_polarity_bit = 1, \
modified drivers/pinctrl/qcom/pinctrl-nord.c
@@ -32,6 +32,7 @@
32 32 .intr_wakeup_present_bit = 6, \
33 33 .intr_wakeup_enable_bit = 7, \
34 34 .intr_target_bit = 8, \
35 + .intr_target_width = 4, \
35 36 .intr_target_kpss_val = 3, \
36 37 .intr_raw_status_bit = 4, \
37 38 .intr_polarity_bit = 1, \
modified drivers/pinctrl/qcom/pinctrl-qcs8300.c
@@ -45,6 +45,7 @@
45 45 .intr_enable_bit = 0, \
46 46 .intr_status_bit = 0, \
47 47 .intr_target_bit = 5, \
48 + .intr_target_width = 4, \
48 49 .intr_target_kpss_val = 3, \
49 50 .intr_raw_status_bit = 4, \
50 51 .intr_polarity_bit = 1, \
modified drivers/pinctrl/qcom/pinctrl-spmi-gpio.c
@@ -734,29 +734,50 @@ static int pmic_gpio_get_direction(struct gpio_chip *chip, unsigned pin)
734 734 (!pad->input_enabled && !pad->output_enabled))
735 735 return -EINVAL;
736 736
737 - /* Make sure the state is aligned on what pmic_gpio_get() returns */
738 - return pad->input_enabled ? GPIO_LINE_DIRECTION_IN : GPIO_LINE_DIRECTION_OUT;
737 + /*
738 + * An open-drain or open-source pad keeps its input buffer enabled while
739 + * driving, so the output buffer is what tells the direction.
740 + */
741 + return pad->output_enabled ? GPIO_LINE_DIRECTION_OUT : GPIO_LINE_DIRECTION_IN;
739 742 }
740 743
741 744 static int pmic_gpio_direction_input(struct gpio_chip *chip, unsigned pin)
742 745 {
743 746 struct pmic_gpio_state *state = gpiochip_get_data(chip);
744 - unsigned long config;
747 + unsigned long configs[2];
745 748
746 - config = pinconf_to_config_packed(PIN_CONFIG_INPUT_ENABLE, 1);
749 + configs[0] = pinconf_to_config_packed(PIN_CONFIG_OUTPUT_ENABLE, 0);
750 + configs[1] = pinconf_to_config_packed(PIN_CONFIG_INPUT_ENABLE, 1);
747 751
748 - return pmic_gpio_config_set(state->ctrl, pin, &config, 1);
752 + return pmic_gpio_config_set(state->ctrl, pin, configs,
753 + ARRAY_SIZE(configs));
749 754 }
750 755
751 756 static int pmic_gpio_direction_output(struct gpio_chip *chip,
752 757 unsigned pin, int val)
753 758 {
754 759 struct pmic_gpio_state *state = gpiochip_get_data(chip);
755 - unsigned long config;
760 + struct pmic_gpio_pad *pad = state->ctrl->desc->pins[pin].drv_data;
761 + unsigned long configs[2];
756 762
757 - config = pinconf_to_config_packed(PIN_CONFIG_LEVEL, val);
763 + /*
764 + * An open-drain or open-source pad only ever drives one rail, so the
765 + * line can still be sampled while the pad is an output. Keep the input
766 + * buffer enabled for those, so that pmic_gpio_get() reports what is on
767 + * the wire rather than the value last written, and disable it for a
768 + * CMOS pad, so that the pad ends up in DIGITAL_OUTPUT rather than
769 + * DIGITAL_INPUT_OUTPUT. Program it either way, as the buffer may have
770 + * been left in the opposite state by the bootloader or by an earlier
771 + * direction change with a different buffer type. gpiolib applies
772 + * PIN_CONFIG_DRIVE_OPEN_DRAIN before calling this, so buffer_type is
773 + * already up to date here.
774 + */
775 + configs[0] = pinconf_to_config_packed(PIN_CONFIG_INPUT_ENABLE,
776 + pad->buffer_type != PMIC_GPIO_OUT_BUF_CMOS);
777 + configs[1] = pinconf_to_config_packed(PIN_CONFIG_LEVEL, val);
758 778
759 - return pmic_gpio_config_set(state->ctrl, pin, &config, 1);
779 + return pmic_gpio_config_set(state->ctrl, pin, configs,
780 + ARRAY_SIZE(configs));
760 781 }
761 782
762 783 static int pmic_gpio_get(struct gpio_chip *chip, unsigned pin)
modified drivers/pinctrl/sunxi/pinctrl-sunxi-dt.c
@@ -84,6 +84,7 @@ static struct sunxi_desc_pin *init_pins_table(struct device *dev,
84 84 * Find the total number of pins.
85 85 * Also work out how much memory we need to store all the pin names.
86 86 */
87 + desc->npins = 0;
87 88 for (i = 0; i < SUNXI_PINCTRL_MAX_BANKS; i++) {
88 89 desc->npins += pins_per_bank[i];
89 90 if (pins_per_bank[i] < 10) {
modified drivers/pmdomain/imx/imx8m-blk-ctrl.c
@@ -15,6 +15,7 @@
15 15 #include <linux/pm_runtime.h>
16 16 #include <linux/regmap.h>
17 17 #include <linux/clk.h>
18 + #include <linux/mutex.h>
18 19
19 20 #include <dt-bindings/power/imx8mm-power.h>
20 21 #include <dt-bindings/power/imx8mn-power.h>
@@ -34,6 +35,12 @@ struct imx8m_blk_ctrl {
34 35 struct regmap *regmap;
35 36 struct imx8m_blk_ctrl_domain *domains;
36 37 struct genpd_onecell_data onecell_data;
38 + /*
39 + * Serializes the blk-ctrl reset/clock sequence across sibling domains;
40 + * their transitions interact through the shared VPUMIX bus domain,
41 + * VPU_NOC and the not-ack-verified ADB400 handshake (ERR050531).
42 + */
43 + struct mutex power_lock;
37 44 };
38 45
39 46 struct imx8m_blk_ctrl_domain_data {
@@ -98,6 +105,8 @@ static int imx8m_blk_ctrl_power_on(struct generic_pm_domain *genpd)
98 105 struct imx8m_blk_ctrl *bc = domain->bc;
99 106 int ret;
100 107
108 + guard(mutex)(&bc->power_lock);
109 +
101 110 /* make sure bus domain is awake */
102 111 ret = pm_runtime_get_sync(bc->bus_power_dev);
103 112 if (ret < 0) {
@@ -164,6 +173,8 @@ static int imx8m_blk_ctrl_power_off(struct generic_pm_domain *genpd)
164 173 const struct imx8m_blk_ctrl_domain_data *data = domain->data;
165 174 struct imx8m_blk_ctrl *bc = domain->bc;
166 175
176 + guard(mutex)(&bc->power_lock);
177 +
167 178 /* put devices into reset and disable clocks */
168 179 if (data->mipi_phy_rst_mask)
169 180 regmap_clear_bits(bc->regmap, BLK_MIPI_RESET_DIV, data->mipi_phy_rst_mask);
@@ -202,6 +213,10 @@ static int imx8m_blk_ctrl_probe(struct platform_device *pdev)
202 213
203 214 bc->dev = dev;
204 215
216 + ret = devm_mutex_init(dev, &bc->power_lock);
217 + if (ret)
218 + return ret;
219 +
205 220 bc_data = of_device_get_match_data(dev);
206 221
207 222 base = devm_platform_ioremap_resource(pdev, 0);
modified drivers/pmdomain/rockchip/pm-domains.c
@@ -759,7 +759,19 @@ static int rockchip_pd_attach_dev(struct generic_pm_domain *genpd,
759 759 }
760 760
761 761 i = 0;
762 - while ((clk = of_clk_get(dev->of_node, i++)) && !IS_ERR(clk)) {
762 + while (1) {
763 + clk = of_clk_get(dev->of_node, i++);
764 + if (IS_ERR(clk)) {
765 + error = PTR_ERR(clk);
766 + if (error == -ENOENT)
767 + break;
768 +
769 + dev_err(dev, "failed to get clock %d: %d\n", i - 1,
770 + error);
771 + pm_clk_destroy(dev);
772 + return error;
773 + }
774 +
763 775 dev_dbg(dev, "adding clock '%pC' to list of PM clocks\n", clk);
764 776 error = pm_clk_add_clk(dev, clk);
765 777 if (error) {
@@ -842,7 +854,7 @@ static int rockchip_pm_add_one_domain(struct rockchip_pmu *pmu,
842 854 dev_err(pmu->dev,
843 855 "%pOFn: failed to get clk at index %d: %d\n",
844 856 node, i, error);
845 - return error;
857 + goto err_put_clocks;
846 858 }
847 859 }
848 860
@@ -1018,7 +1030,9 @@ static int rockchip_pm_add_subdomain(struct rockchip_pmu *pmu,
1018 1030 parent_domain->name, child_domain->name);
1019 1031 }
1020 1032
1021 - rockchip_pm_add_subdomain(pmu, np);
1033 + error = rockchip_pm_add_subdomain(pmu, np);
1034 + if (error)
1035 + return error;
1022 1036 }
1023 1037
1024 1038 return 0;
modified drivers/power/sequencing/pwrseq-pcie-m2.c
@@ -197,6 +197,8 @@ static const struct pci_device_id pwrseq_m2_pci_ids[] = {
197 197 .driver_data = (kernel_ulong_t)"qcom,wcn6855-bt" },
198 198 { PCI_DEVICE_SUB(PCI_VENDOR_ID_QCOM, 0x1107, PCI_VENDOR_ID_QCOM, 0x337c),
199 199 .driver_data = (kernel_ulong_t)"qcom,wcn7850-bt" },
200 + { PCI_DEVICE_SUB(PCI_VENDOR_ID_QCOM, 0x1107, PCI_VENDOR_ID_LENOVO, 0xe0e9),
201 + .driver_data = (kernel_ulong_t)"qcom,wcn7850-bt" },
200 202 { } /* Sentinel */
201 203 };
202 204
@@ -570,6 +572,7 @@ err_destroy_mutex:
570 572 mutex_destroy(&ctx->list_lock);
571 573 err_free_regulators:
572 574 regulator_bulk_free(ctx->num_vregs, ctx->regs);
575 + kfree(ctx->regs);
573 576
574 577 return ret;
575 578 }
@@ -583,6 +586,7 @@ static void pwrseq_pcie_m2_remove(struct platform_device *pdev)
583 586 mutex_destroy(&ctx->list_lock);
584 587
585 588 regulator_bulk_free(ctx->num_vregs, ctx->regs);
589 + kfree(ctx->regs);
586 590 }
587 591
588 592 static const struct of_device_id pwrseq_pcie_m2_of_match[] = {
modified drivers/power/sequencing/pwrseq-qcom-wcn.c
@@ -496,15 +496,8 @@ static int pwrseq_qcom_wcn_probe(struct platform_device *pdev)
496 496 return dev_err_probe(dev, PTR_ERR(ctx->bt_gpio),
497 497 "Failed to get the Bluetooth enable GPIO\n");
498 498
499 - /*
500 - * FIXME: This should actually be GPIOD_OUT_LOW, but doing so would
501 - * cause the WLAN power to be toggled, resulting in PCIe link down.
502 - * Since the PCIe controller driver is not handling link down currently,
503 - * the device becomes unusable. So we need to keep this workaround until
504 - * the link down handling is implemented in the controller driver.
505 - */
506 499 ctx->wlan_gpio = devm_gpiod_get_optional(dev, "wlan-enable",
507 - GPIOD_ASIS);
500 + GPIOD_OUT_LOW);
508 501 if (IS_ERR(ctx->wlan_gpio))
509 502 return dev_err_probe(dev, PTR_ERR(ctx->wlan_gpio),
510 503 "Failed to get the WLAN enable GPIO\n");
@@ -515,13 +508,6 @@ static int pwrseq_qcom_wcn_probe(struct platform_device *pdev)
515 508 return dev_err_probe(dev, PTR_ERR(ctx->xo_clk_gpio),
516 509 "Failed to get the XO_CLK GPIO\n");
517 510
518 - /*
519 - * Set direction to output but keep the current value in order to not
520 - * disable the WLAN module accidentally if it's already powered on.
521 - */
522 - gpiod_direction_output(ctx->wlan_gpio,
523 - gpiod_get_value_cansleep(ctx->wlan_gpio));
524 -
525 511 ctx->clk = devm_clk_get_optional(dev, NULL);
526 512 if (IS_ERR(ctx->clk))
527 513 return dev_err_probe(dev, PTR_ERR(ctx->clk),
modified drivers/power/supply/ds2780_battery.c
@@ -304,7 +304,7 @@ static int ds2780_get_capacity(struct ds2780_device_info *dev_info,
304 304 return ret;
305 305
306 306 *capacity = raw;
307 - return raw;
307 + return 0;
308 308 }
309 309
310 310 static int ds2780_get_status(struct ds2780_device_info *dev_info, int *status)
modified drivers/power/supply/generic-adc-battery.c
@@ -90,12 +90,17 @@ static int gab_read_channel(struct gab *adc_bat, enum gab_chan_type channel,
90 90 int ret;
91 91
92 92 ret = iio_read_channel_processed(adc_bat->channel[channel], result);
93 - if (ret < 0)
93 + if (ret < 0) {
94 94 dev_err(&adc_bat->psy->dev, "read channel error: %d\n", ret);
95 + return ret;
96 + }
97 +
98 + if (channel == GAB_TEMP)
99 + *result /= 100; /* Convert from milli- to deci-degree */
95 100 else
96 101 *result *= 1000;
97 102
98 - return ret;
103 + return 0;
99 104 }
100 105
101 106 static int gab_get_property(struct power_supply *psy,
modified drivers/power/supply/max17042_battery.c
@@ -1233,7 +1233,7 @@ static int max17042_parse_dt(struct max17042_chip *chip)
1233 1233 if (of_property_read_u32(np, "maxim,over-volt", &prop))
1234 1234 chip->vmax = INT_MAX;
1235 1235 else
1236 - chip->vmin = prop;
1236 + chip->vmax = prop;
1237 1237
1238 1238 return 0;
1239 1239 }
modified drivers/power/supply/power_supply_core.c
@@ -1530,6 +1530,19 @@ void power_supply_external_power_changed(struct power_supply *psy)
1530 1530 !psy->desc->external_power_changed)
1531 1531 return;
1532 1532
1533 + /*
1534 + * Keep power_supply_unregister() from returning, and thus from letting
1535 + * the driver's data be freed, while the callback is running. The
1536 + * ->removing check has to happen under the lock: on its own, just like
1537 + * the use_cnt check above, it only tells us the supply was still there
1538 + * when we looked, not that it still is by the time the callback
1539 + * dereferences its driver data.
1540 + */
1541 + guard(rwsem_read)(&psy->epc_sem);
1542 +
1543 + if (psy->removing)
1544 + return;
1545 +
1533 1546 psy->desc->external_power_changed(psy);
1534 1547 }
1535 1548 EXPORT_SYMBOL_GPL(power_supply_external_power_changed);
@@ -1774,6 +1787,7 @@ __power_supply_register(struct device *parent,
1774 1787 }
1775 1788
1776 1789 spin_lock_init(&psy->changed_lock);
1790 + init_rwsem(&psy->epc_sem);
1777 1791 init_rwsem(&psy->extensions_sem);
1778 1792 INIT_LIST_HEAD(&psy->extensions);
1779 1793
@@ -1914,7 +1928,17 @@ EXPORT_SYMBOL_GPL(devm_power_supply_register);
1914 1928 void power_supply_unregister(struct power_supply *psy)
1915 1929 {
1916 1930 WARN_ON(atomic_dec_return(&psy->use_cnt));
1917 - psy->removing = true;
1931 +
1932 + /*
1933 + * Publish ->removing so that no new ->external_power_changed() call can
1934 + * start, and wait via semaphore for one that is already running: it may
1935 + * be a supplier's changed_work, which cancel_work_sync() below does not
1936 + * cover, and it may still dereference driver data that the caller is
1937 + * about to free.
1938 + */
1939 + scoped_guard(rwsem_write, &psy->epc_sem)
1940 + psy->removing = true;
1941 +
1918 1942 cancel_work_sync(&psy->changed_work);
1919 1943 cancel_delayed_work_sync(&psy->deferred_register_work);
1920 1944 sysfs_remove_link(&psy->dev.kobj, "powers");
modified drivers/ptp/ptp_ocp.c
@@ -1825,7 +1825,7 @@ ptp_ocp_watchdog(struct timer_list *t)
1825 1825 static void
1826 1826 ptp_ocp_estimate_pci_timing(struct ptp_ocp *bp)
1827 1827 {
1828 - ktime_t start, end, delay = U64_MAX;
1828 + ktime_t start, end, delay = KTIME_MAX;
1829 1829 u32 ctrl;
1830 1830 int i;
1831 1831
modified drivers/regulator/ltc3676.c
@@ -232,7 +232,7 @@ static const struct regulator_desc ltc3676_regulators[LTC3676_NUM_REGULATORS] =
232 232 LTC3676_FIXED_REG(LDO4, ldo4, LDOB, 2),
233 233 };
234 234
235 - static bool ltc3676_readable_writeable_reg(struct device *dev, unsigned int reg)
235 + static bool ltc3676_writeable_reg(struct device *dev, unsigned int reg)
236 236 {
237 237 switch (reg) {
238 238 case LTC3676_BUCK1 ... LTC3676_IRQSTAT:
@@ -243,6 +243,15 @@ static bool ltc3676_readable_writeable_reg(struct device *dev, unsigned int reg)
243 243 return false;
244 244 }
245 245
246 + static bool ltc3676_readable_reg(struct device *dev, unsigned int reg)
247 + {
248 + switch (reg) {
249 + case LTC3676_BUCK1 ... LTC3676_IRQSTAT:
250 + return true;
251 + }
252 + return false;
253 + }
254 +
246 255 static bool ltc3676_volatile_reg(struct device *dev, unsigned int reg)
247 256 {
248 257 switch (reg) {
@@ -255,8 +264,8 @@ static bool ltc3676_volatile_reg(struct device *dev, unsigned int reg)
255 264 static const struct regmap_config ltc3676_regmap_config = {
256 265 .reg_bits = 8,
257 266 .val_bits = 8,
258 - .writeable_reg = ltc3676_readable_writeable_reg,
259 - .readable_reg = ltc3676_readable_writeable_reg,
267 + .writeable_reg = ltc3676_writeable_reg,
268 + .readable_reg = ltc3676_readable_reg,
260 269 .volatile_reg = ltc3676_volatile_reg,
261 270 .max_register = LTC3676_CLIRQ,
262 271 .use_single_read = true,
modified drivers/regulator/of_regulator.c
@@ -929,21 +929,26 @@ static int is_supply_name(const char *name)
929 929 * before returning to the caller, and @consumers will not be
930 930 * changed.
931 931 *
932 + * On success the array is allocated here and handed to the caller, which
933 + * owns it from then on: release the regulators with regulator_bulk_free()
934 + * and free the array itself with kfree(). The supply names live in the
935 + * same allocation, so they are gone once the array is freed.
936 + *
932 937 * Return: Number of regulators on success, or a negative error number
933 938 * on failure.
934 939 */
935 940 int of_regulator_bulk_get_all(struct device *dev, struct device_node *np,
936 941 struct regulator_bulk_data **consumers)
937 942 {
938 - int num_consumers = 0;
943 + int num_consumers = 0, names_len = 0;
939 944 struct regulator *tmp;
940 945 struct regulator_bulk_data *_consumers = NULL;
941 946 struct property *prop;
947 + char *names;
942 948 int i, n = 0, ret;
943 - char name[64];
944 949
945 950 /*
946 - * first pass: get numbers of xxx-supply
951 + * first pass: get numbers of xxx-supply and the room their names take
947 952 * second pass: fill consumers
948 953 */
949 954 restart:
@@ -953,16 +958,19 @@ restart:
953 958 continue;
954 959 if (!_consumers) {
955 960 num_consumers++;
961 + names_len += i + 1;
956 962 continue;
957 963 } else {
958 - memcpy(name, prop->name, i);
959 - name[i] = '\0';
960 - tmp = regulator_get(dev, name);
964 + memcpy(names, prop->name, i);
965 + names[i] = '\0';
966 + tmp = regulator_get(dev, names);
961 967 if (IS_ERR(tmp)) {
962 968 ret = PTR_ERR(tmp);
963 969 goto error;
964 970 }
971 + _consumers[n].supply = names;
965 972 _consumers[n].consumer = tmp;
973 + names += i + 1;
966 974 n++;
967 975 continue;
968 976 }
@@ -973,9 +981,16 @@ restart:
973 981 }
974 982 if (num_consumers == 0)
975 983 return 0;
976 - _consumers = kmalloc_objs(struct regulator_bulk_data, num_consumers);
984 + /*
985 + * The supply names are kept in the same allocation as the array, so
986 + * that they share its lifetime and the caller has nothing extra to
987 + * free.
988 + */
989 + _consumers = kzalloc(size_add(size_mul(num_consumers, sizeof(*_consumers)),
990 + names_len), GFP_KERNEL);
977 991 if (!_consumers)
978 992 return -ENOMEM;
993 + names = (char *)(_consumers + num_consumers);
979 994 goto restart;
980 995
981 996 error:
modified drivers/regulator/tps6594-regulator.c
@@ -241,21 +241,21 @@ static const struct regulator_desc tps65224_buck_regs[] = {
241 241 TPS65224_MASK_BUCKS_VSET,
242 242 TPS6594_REG_BUCKX_CTRL(1),
243 243 TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges,
244 - 4, 0, 0, NULL, 0, 0),
244 + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0),
245 245 TPS6594_REGULATOR("BUCK3", "buck3", TPS6594_BUCK_3,
246 246 REGULATOR_VOLTAGE, tps6594_bucks_ops, TPS65224_MASK_BUCKS_VSET,
247 247 TPS6594_REG_BUCKX_VOUT_1(2),
248 248 TPS65224_MASK_BUCKS_VSET,
249 249 TPS6594_REG_BUCKX_CTRL(2),
250 250 TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges,
251 - 4, 0, 0, NULL, 0, 0),
251 + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0),
252 252 TPS6594_REGULATOR("BUCK4", "buck4", TPS6594_BUCK_4,
253 253 REGULATOR_VOLTAGE, tps6594_bucks_ops, TPS65224_MASK_BUCKS_VSET,
254 254 TPS6594_REG_BUCKX_VOUT_1(3),
255 255 TPS65224_MASK_BUCKS_VSET,
256 256 TPS6594_REG_BUCKX_CTRL(3),
257 257 TPS6594_BIT_BUCK_EN, 0, 0, tps65224_bucks_2_3_4_ranges,
258 - 4, 0, 0, NULL, 0, 0),
258 + ARRAY_SIZE(tps65224_bucks_2_3_4_ranges), 0, 0, NULL, 0, 0),
259 259 };
260 260
261 261 static const struct tps6594_regulator_irq_type tps6594_buck1_irq_types[] = {
modified drivers/scsi/ch.c
@@ -112,7 +112,6 @@ typedef struct {
112 112 int minor;
113 113 char name[8];
114 114 struct scsi_device *device;
115 - struct scsi_device **dt; /* ptrs to data transfer elements */
116 115 u_int firsts[CH_TYPES];
117 116 u_int counts[CH_TYPES];
118 117 u_int voltags;
@@ -363,15 +362,10 @@ ch_readconfig(scsi_changer *ch)
363 362 vendor_labels[i]);
364 363 }
365 364
366 - /* look up the devices of the data transfer elements */
367 - ch->dt = kzalloc_objs(*ch->dt, ch->counts[CHET_DT]);
368 -
369 - if (!ch->dt) {
370 - kfree(buffer);
371 - return -ENOMEM;
372 - }
373 -
365 + /* report the devices of the data transfer elements */
374 366 for (elem = 0; elem < ch->counts[CHET_DT]; elem++) {
367 + struct scsi_device *sdev;
368 +
375 369 id = -1;
376 370 lun = 0;
377 371 if (elem < CH_DT_MAX && -1 != dt_id[elem]) {
@@ -387,10 +381,8 @@ ch_readconfig(scsi_changer *ch)
387 381 VPRINTK(KERN_INFO, "dt 0x%x: ",elem+ch->firsts[CHET_DT]);
388 382 if (data[6] & 0x80) {
389 383 VPRINTK(KERN_CONT, "not this SCSI bus\n");
390 - ch->dt[elem] = NULL;
391 384 } else if (0 == (data[6] & 0x30)) {
392 385 VPRINTK(KERN_CONT, "ID/LUN unknown\n");
393 - ch->dt[elem] = NULL;
394 386 } else {
395 387 id = ch->device->id;
396 388 lun = 0;
@@ -400,18 +392,16 @@ ch_readconfig(scsi_changer *ch)
400 392 }
401 393 if (-1 != id) {
402 394 VPRINTK(KERN_CONT, "ID %i, LUN %i, ",id,lun);
403 - ch->dt[elem] =
404 - scsi_device_lookup(ch->device->host,
405 - ch->device->channel,
406 - id,lun);
407 - if (!ch->dt[elem]) {
395 + sdev = scsi_device_lookup(ch->device->host,
396 + ch->device->channel,
397 + id, lun);
398 + if (!sdev) {
408 399 /* should not happen */
409 400 VPRINTK(KERN_CONT, "Huh? device not found!\n");
410 401 } else {
411 402 VPRINTK(KERN_CONT, "name: %8.8s %16.16s %4.4s\n",
412 - ch->dt[elem]->vendor,
413 - ch->dt[elem]->model,
414 - ch->dt[elem]->rev);
403 + sdev->vendor, sdev->model, sdev->rev);
404 + scsi_device_put(sdev);
415 405 }
416 406 }
417 407 }
@@ -575,7 +565,6 @@ static void ch_destroy(struct kref *ref)
575 565 scsi_changer *ch = container_of(ref, scsi_changer, ref);
576 566
577 567 ch->device = NULL;
578 - kfree(ch->dt);
579 568 kfree(ch);
580 569 }
581 570
modified drivers/scsi/qedi/qedi_main.c
@@ -2652,8 +2652,6 @@ retry_probe:
2652 2652 snprintf(host_buf, sizeof(host_buf), "host_%d", qedi->shost->host_no);
2653 2653 qedi_ops->common->set_name(qedi->cdev, host_buf);
2654 2654
2655 - qedi_ops->register_ops(qedi->cdev, &qedi_cb_ops, qedi);
2656 -
2657 2655 memset(&params, 0, sizeof(params));
2658 2656 params.mtu = DEF_PATH_MTU + IPV6_HDR_LEN + TCP_HDR_LEN;
2659 2657 qedi->ll2_mtu = DEF_PATH_MTU;
@@ -2670,6 +2668,7 @@ retry_probe:
2670 2668 spin_lock_init(&qedi->task_idx_lock);
2671 2669 mutex_init(&qedi->stats_lock);
2672 2670 }
2671 + qedi_ops->register_ops(qedi->cdev, &qedi_cb_ops, qedi);
2673 2672 qedi_ops->ll2->register_cb_ops(qedi->cdev, &qedi_ll2_cb_ops, qedi);
2674 2673 qedi_ops->ll2->start(qedi->cdev, &params);
2675 2674
modified drivers/soc/tegra/fuse/tegra-apbmisc.c
@@ -309,7 +309,7 @@ void tegra_acpi_init_apbmisc(void)
309 309
310 310 ret = acpi_dev_get_memory_resources(adev, &resource_list);
311 311 if (ret < 0) {
312 - pr_err("failed to get APBMISC memory resources");
312 + pr_err("failed to get APBMISC memory resources\n");
313 313 goto out_put_acpi_dev;
314 314 }
315 315
modified drivers/soc/tegra/pmc.c
@@ -3151,6 +3151,7 @@ static int tegra_pmc_probe(struct platform_device *pdev)
3151 3151
3152 3152 #if defined(CONFIG_ARM)
3153 3153 mutex_lock(&early_pmc->powergates_lock);
3154 + early_pmc->rate = pmc->rate;
3154 3155 iounmap(early_pmc->base);
3155 3156 early_pmc->base = pmc->base;
3156 3157 mutex_unlock(&early_pmc->powergates_lock);
modified drivers/spi/spi-cadence-quadspi.c
@@ -1056,8 +1056,7 @@ static int cqspi_write_setup(struct cqspi_flash_pdata *f_pdata,
1056 1056 * care of polling the status register.
1057 1057 */
1058 1058 if (cqspi->wr_completion) {
1059 - reg = readl(reg_base + CQSPI_REG_WR_COMPLETION_CTRL);
1060 - reg |= CQSPI_REG_WR_DISABLE_AUTO_POLL;
1059 + reg = CQSPI_REG_WR_DISABLE_AUTO_POLL;
1061 1060 writel(reg, reg_base + CQSPI_REG_WR_COMPLETION_CTRL);
1062 1061 /*
1063 1062 * DAC mode require auto polling as flash needs to be polled
modified drivers/spi/spi-nxp-fspi.c
@@ -898,10 +898,10 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi,
898 898 dev_dbg(f->dev, "Target device [CS:%x] selected\n", spi_get_chipselect(spi, 0));
899 899
900 900 /*
901 - * Per the FlexSPI reference manual (initialization sequence), MCR0 and
902 - * the DLL control registers should be configured while the module is in
903 - * stop mode (MCR0[MDIS] = 1). Enter stop mode before reconfiguring the
904 - * RX sample clock source and the DLL, then exit stop mode afterwards.
901 + * Per the FlexSPI reference manual (initialization sequence), MCR0
902 + * should be configured while the module is in stop mode (MCR0[MDIS] = 1).
903 + * Enter stop mode before reconfiguring the RX sample clock source, then
904 + * exit stop mode afterwards.
905 905 */
906 906 reg = fspi_readl(f, f->iobase + FSPI_MCR0);
907 907 fspi_writel(f, reg | FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0);
@@ -936,6 +936,16 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi,
936 936 if (ret)
937 937 return ret;
938 938
939 + /*
940 + * Exit stop mode before running the DLL calibration. The DLL
941 + * reference clock is derived from the module clock domain, which is
942 + * gated while MCR0[MDIS] = 1. Calibrating the DLL in stop mode leaves
943 + * the STS2 lock bits stuck at 0 (the DLL never runs), so clear MDIS
944 + * first and let the module and reference clock run.
945 + */
946 + reg = fspi_readl(f, f->iobase + FSPI_MCR0);
947 + fspi_writel(f, reg & ~FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0);
948 +
939 949 /*
940 950 * If clock rate > 100MHz, then switch from DLL override mode to
941 951 * DLL calibration mode.
@@ -945,10 +955,6 @@ static int nxp_fspi_select_mem(struct nxp_fspi *f, struct spi_device *spi,
945 955 else
946 956 nxp_fspi_dll_override(f);
947 957
948 - /* Exit stop mode now that MCR0 and the DLL have been reconfigured. */
949 - reg = fspi_readl(f, f->iobase + FSPI_MCR0);
950 - fspi_writel(f, reg & ~FSPI_MCR0_MDIS, f->iobase + FSPI_MCR0);
951 -
952 958 f->pre_op_rate = op->max_freq;
953 959
954 960 f->selected = spi_get_chipselect(spi, 0);
modified drivers/spi/spi-sg2044-nor.c
@@ -307,15 +307,15 @@ static ssize_t sg2044_spifmc_tran_cmd(struct sg2044_spifmc *spifmc,
307 307 return 0;
308 308 }
309 309
310 - static void sg2044_spifmc_trans(struct sg2044_spifmc *spifmc,
311 - const struct spi_mem_op *op)
310 + static int sg2044_spifmc_trans(struct sg2044_spifmc *spifmc,
311 + const struct spi_mem_op *op)
312 312 {
313 313 if (op->data.dir == SPI_MEM_DATA_IN)
314 - sg2044_spifmc_read(spifmc, op);
314 + return sg2044_spifmc_read(spifmc, op);
315 315 else if (op->data.dir == SPI_MEM_DATA_OUT)
316 - sg2044_spifmc_write(spifmc, op);
316 + return sg2044_spifmc_write(spifmc, op);
317 317 else
318 - sg2044_spifmc_tran_cmd(spifmc, op);
318 + return sg2044_spifmc_tran_cmd(spifmc, op);
319 319 }
320 320
321 321 static ssize_t sg2044_spifmc_trans_reg(struct sg2044_spifmc *spifmc,
@@ -385,29 +385,64 @@ static ssize_t sg2044_spifmc_trans_reg(struct sg2044_spifmc *spifmc,
385 385 return 0;
386 386 }
387 387
388 + static int sg2044_spifmc_set_speed(struct sg2044_spifmc *spifmc,
389 + unsigned int speed_hz)
390 + {
391 + unsigned long rate = clk_get_rate(spifmc->clk);
392 + u64 div;
393 + u32 reg;
394 +
395 + if (!rate)
396 + return -EINVAL;
397 +
398 + /* SCK = HCLK / (2 * (SckDiv + 1)); round down the resulting SCK. */
399 + div = speed_hz ? DIV_ROUND_UP_ULL(rate, 2ULL * speed_hz) : 1;
400 + if (div > SPIFMC_CTRL_SCK_DIV_MASK + 1)
401 + return -EINVAL;
402 +
403 + reg = readl(spifmc->io_base + SPIFMC_CTRL);
404 + reg &= ~SPIFMC_CTRL_SCK_DIV_MASK;
405 + reg |= div - 1;
406 + writel(reg, spifmc->io_base + SPIFMC_CTRL);
407 +
408 + return 0;
409 + }
410 +
388 411 static int sg2044_spifmc_exec_op(struct spi_mem *mem,
389 412 const struct spi_mem_op *op)
390 413 {
391 414 struct sg2044_spifmc *spifmc;
415 + int ret;
392 416
393 417 spifmc = spi_controller_get_devdata(mem->spi->controller);
394 418
395 419 mutex_lock(&spifmc->lock);
396 420
421 + ret = sg2044_spifmc_set_speed(spifmc, op->max_freq ?
422 + min(op->max_freq, mem->spi->max_speed_hz) :
423 + mem->spi->max_speed_hz);
424 + if (ret)
425 + goto out_unlock;
426 +
397 427 if (op->addr.nbytes == 0)
398 - sg2044_spifmc_trans_reg(spifmc, op);
428 + ret = sg2044_spifmc_trans_reg(spifmc, op);
399 429 else
400 - sg2044_spifmc_trans(spifmc, op);
430 + ret = sg2044_spifmc_trans(spifmc, op);
401 431
432 + out_unlock:
402 433 mutex_unlock(&spifmc->lock);
403 434
404 - return 0;
435 + return ret;
405 436 }
406 437
407 438 static const struct spi_controller_mem_ops sg2044_spifmc_mem_ops = {
408 439 .exec_op = sg2044_spifmc_exec_op,
409 440 };
410 441
442 + static const struct spi_controller_mem_caps sg2044_spifmc_mem_caps = {
443 + .per_op_freq = true,
444 + };
445 +
411 446 static void sg2044_spifmc_init(struct sg2044_spifmc *spifmc)
412 447 {
413 448 u32 tran_csr;
@@ -447,6 +482,10 @@ static int sg2044_spifmc_probe(struct platform_device *pdev)
447 482 if (IS_ERR(spifmc->clk))
448 483 return dev_err_probe(dev, PTR_ERR(spifmc->clk), "Cannot get and enable AHB clock\n");
449 484
485 + ctrl->max_speed_hz = clk_get_rate(spifmc->clk) / 2;
486 + if (!ctrl->max_speed_hz)
487 + return dev_err_probe(dev, -EINVAL, "Invalid AHB clock rate\n");
488 +
450 489 spifmc->dev = &pdev->dev;
451 490 spifmc->ctrl = ctrl;
452 491
@@ -458,6 +497,7 @@ static int sg2044_spifmc_probe(struct platform_device *pdev)
458 497 ctrl->bits_per_word_mask = SPI_BPW_MASK(8);
459 498 ctrl->auto_runtime_pm = false;
460 499 ctrl->mem_ops = &sg2044_spifmc_mem_ops;
500 + ctrl->mem_caps = &sg2044_spifmc_mem_caps;
461 501 ctrl->mode_bits = SPI_RX_DUAL | SPI_TX_DUAL | SPI_RX_QUAD | SPI_TX_QUAD;
462 502
463 503 ret = devm_mutex_init(dev, &spifmc->lock);
modified drivers/tee/optee/ffa_abi.c
@@ -198,7 +198,8 @@ static int to_msg_param_ffa_mem(struct optee_msg_param *mp,
198 198 if (shm) {
199 199 u64 shm_offs = p->u.memref.shm_offs;
200 200
201 - mp->u.fmem.internal_offs = shm->offset;
201 + mp->u.fmem.internal_offs = tee_shm_get_page_offset(shm) &
202 + (FFA_PAGE_SIZE - 1);
202 203
203 204 mp->u.fmem.offs_low = shm_offs;
204 205 mp->u.fmem.offs_high = shm_offs >> 32;
@@ -284,14 +285,26 @@ static int optee_ffa_shm_register(struct tee_context *ctx, struct tee_shm *shm,
284 285 .nattrs = 1,
285 286 };
286 287 struct sg_table sgt;
288 + size_t ffa_offs;
287 289 int rc;
288 290
291 + if (!num_pages)
292 + return -EINVAL;
293 +
289 294 rc = optee_check_mem_type(start, num_pages);
290 295 if (rc)
291 296 return rc;
292 297
293 - rc = sg_alloc_table_from_pages(&sgt, pages, num_pages, 0,
294 - num_pages * PAGE_SIZE, GFP_KERNEL);
298 + /*
299 + * Start the FF-A descriptor at the 4 KiB page containing the shared
300 + * buffer, skipping unused leading 4 KiB pages when PAGE_SIZE is
301 + * larger. Same approach as optee_fill_pages_list() in the SMC ABI.
302 + * This leaves only the offset into that 4 KiB page for internal_offs.
303 + */
304 + ffa_offs = round_down(tee_shm_get_page_offset(shm), FFA_PAGE_SIZE);
305 + rc = sg_alloc_table_from_pages(&sgt, pages, num_pages, ffa_offs,
306 + num_pages * PAGE_SIZE - ffa_offs,
307 + GFP_KERNEL);
295 308 if (rc)
296 309 return rc;
297 310 args.sg = sgt.sgl;
@@ -458,7 +471,8 @@ static void handle_ffa_rpc_func_cmd_shm_alloc(struct tee_context *ctx,
458 471 .attr = OPTEE_MSG_ATTR_TYPE_FMEM_OUTPUT,
459 472 .u.fmem.size = tee_shm_get_size(shm),
460 473 .u.fmem.global_id = shm->sec_world_id,
461 - .u.fmem.internal_offs = shm->offset,
474 + .u.fmem.internal_offs = tee_shm_get_page_offset(shm) &
475 + (FFA_PAGE_SIZE - 1),
462 476 };
463 477
464 478 arg->ret = TEEC_SUCCESS;
@@ -1123,14 +1137,6 @@ static int optee_ffa_probe(struct ffa_device *ffa_dev)
1123 1137
1124 1138 optee_set_dev_group(optee);
1125 1139
1126 - rc = tee_device_register(optee->teedev);
1127 - if (rc)
1128 - goto err_unreg_supp_teedev;
1129 -
1130 - rc = tee_device_register(optee->supp_teedev);
1131 - if (rc)
1132 - goto err_unreg_supp_teedev;
1133 -
1134 1140 rc = rhashtable_init(&optee->ffa.global_ids, &shm_rhash_params);
1135 1141 if (rc)
1136 1142 goto err_unreg_supp_teedev;
@@ -1159,6 +1165,14 @@ static int optee_ffa_probe(struct ffa_device *ffa_dev)
1159 1165 if (optee_ffa_protmem_pool_init(optee, sec_caps))
1160 1166 pr_info("Protected memory service not available\n");
1161 1167
1168 + rc = tee_device_register(optee->teedev);
1169 + if (rc)
1170 + goto err_unregister_devices;
1171 +
1172 + rc = tee_device_register(optee->supp_teedev);
1173 + if (rc)
1174 + goto err_unregister_devices;
1175 +
1162 1176 rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES);
1163 1177 if (rc)
1164 1178 goto err_unregister_devices;
modified drivers/tee/optee/optee_msg.h
@@ -136,8 +136,8 @@ struct optee_msg_param_rmem {
136 136 * struct optee_msg_param_fmem - FF-A memory reference parameter
137 137 * @offs_low: lower bits of offset into shared memory reference
138 138 * @offs_high: higher bits of offset into shared memory reference
139 - * @internal_offs: internal offset into the first page of shared memory
140 - * reference
139 + * @internal_offs: offset into the first 4 KiB page of the FF-A shared
140 + * memory region
141 141 * @size: size of the buffer
142 142 * @global_id: global identifier of the shared memory
143 143 */
modified drivers/tee/optee/smc_abi.c
@@ -1849,14 +1849,6 @@ static int optee_probe(struct platform_device *pdev)
1849 1849
1850 1850 optee_set_dev_group(optee);
1851 1851
1852 - rc = tee_device_register(optee->teedev);
1853 - if (rc)
1854 - goto err_unreg_supp_teedev;
1855 -
1856 - rc = tee_device_register(optee->supp_teedev);
1857 - if (rc)
1858 - goto err_unreg_supp_teedev;
1859 -
1860 1852 optee_cq_init(&optee->call_queue, thread_count);
1861 1853 optee_supp_init(&optee->supp);
1862 1854 optee->smc.memremaped_shm = memremaped_shm;
@@ -1916,6 +1908,14 @@ static int optee_probe(struct platform_device *pdev)
1916 1908 if (optee->smc.sec_caps & OPTEE_SMC_SEC_CAP_DYNAMIC_SHM)
1917 1909 pr_info("dynamic shared memory is enabled\n");
1918 1910
1911 + rc = tee_device_register(optee->teedev);
1912 + if (rc)
1913 + goto err_disable_shm_cache;
1914 +
1915 + rc = tee_device_register(optee->supp_teedev);
1916 + if (rc)
1917 + goto err_disable_shm_cache;
1918 +
1919 1919 rc = optee_enumerate_devices(PTA_CMD_GET_DEVICES);
1920 1920 if (rc)
1921 1921 goto err_disable_shm_cache;
@@ -1942,7 +1942,6 @@ err_supp_uninit:
1942 1942 optee_shm_arg_cache_uninit(optee);
1943 1943 optee_supp_uninit(&optee->supp);
1944 1944 mutex_destroy(&optee->call_queue.mutex);
1945 - err_unreg_supp_teedev:
1946 1945 tee_device_unregister(optee->supp_teedev);
1947 1946 err_unreg_teedev:
1948 1947 tee_device_unregister(optee->teedev);
modified drivers/tee/qcomtee/async.c
@@ -97,10 +97,10 @@ static void qcomtee_get_async_buffer(struct qcomtee_object_invoke_ctx *oic,
97 97 /**
98 98 * async_release() - Process QTEE async release requests.
99 99 * @oic: context used for the current invocation.
100 - * @msg: async message for object release.
100 + * @async_msg: async message for object release.
101 101 * @size: size of the async buffer available.
102 102 *
103 - * Return: Size of the outbound buffer used when processing @msg.
103 + * Return: Size of the outbound buffer used when processing @async_msg.
104 104 */
105 105 static size_t async_release(struct qcomtee_object_invoke_ctx *oic,
106 106 struct qcomtee_async_msg_hdr *async_msg,
modified drivers/tee/qcomtee/qcomtee_msg.h
@@ -112,7 +112,7 @@ union qcomtee_msg_arg {
112 112
113 113 /**
114 114 * struct qcomtee_msg_object_invoke - Direct object invocation message.
115 - * @ctx: object ID hosted in QTEE.
115 + * @cxt: object ID hosted in QTEE.
116 116 * @op: operation for the object.
117 117 * @counts: number of different types of arguments in @args.
118 118 * @args: array of arguments.
modified drivers/tee/qcomtee/qcomtee_object.h
@@ -74,6 +74,7 @@ enum qcomtee_object_type {
74 74 * @QCOMTEE_ARG_TYPE_OO: output object (OO).
75 75 * @QCOMTEE_ARG_TYPE_IB: input buffer (IB).
76 76 * @QCOMTEE_ARG_TYPE_IO: input object (IO).
77 + * @QCOMTEE_ARG_TYPE_NR: number of argument types.
77 78 *
78 79 * Use the invalid type to specify the end of the argument array.
79 80 */
modified drivers/tee/tee_shm.c
@@ -343,6 +343,10 @@ int tee_dyn_shm_alloc_helper(struct tee_shm *shm, size_t size, size_t align,
343 343 unsigned int i;
344 344 int rc = 0;
345 345
346 + /* get_order(0) is undefined and exceeds MAX_PAGE_ORDER. */
347 + if (!nr_pages)
348 + return -EINVAL;
349 +
346 350 /*
347 351 * Ignore alignment since this is already going to be page aligned
348 352 * and there's no need for any larger alignment.
modified drivers/tty/serial/8250/8250_port.c
@@ -3417,8 +3417,11 @@ static void __serial8250_console_write(struct uart_8250_port *up,
3417 3417 * If the console printer did not fully output the previous line, it
3418 3418 * must have been handed or taken over. Insert a newline in order to
3419 3419 * maintain clean output.
3420 + *
3421 + * Braille consoles are an exception. The serial port is not used
3422 + * for printk(). The driver is supposed to write exactly what it gets.
3420 3423 */
3421 - if (!up->console_line_ended) {
3424 + if (unlikely(!up->console_line_ended && !nbcon_write_context_is_braille(wctxt))) {
3422 3425 if (use_fifo)
3423 3426 __serial8250_console_fifo_write(up, wctxt, "\n", 1);
3424 3427 else
modified drivers/tty/serial/amba-pl011.c
@@ -2656,7 +2656,7 @@ pl011_console_write_atomic(struct console *co, struct nbcon_write_context *wctxt
2656 2656 uap, REG_CR);
2657 2657 }
2658 2658
2659 - if (!uap->console_line_ended)
2659 + if (unlikely(!uap->console_line_ended && !nbcon_is_braille(co)))
2660 2660 uart_console_write(&uap->port, "\n", 1, pl011_console_putchar);
2661 2661 uart_console_write(&uap->port, wctxt->outbuf, wctxt->len, pl011_console_putchar);
2662 2662
modified drivers/tty/serial/imx.c
@@ -2136,7 +2136,7 @@ static void imx_uart_console_write_atomic(struct console *co,
2136 2136 imx_uart_writel(sport, ucr1, UCR1);
2137 2137 imx_uart_writel(sport, old_ucr.ucr2 | UCR2_TXEN, UCR2);
2138 2138
2139 - if (!sport->last_putchar_was_newline)
2139 + if (unlikely(!sport->last_putchar_was_newline && !nbcon_is_braille(co)))
2140 2140 uart_console_write(port, "\n", 1, imx_uart_console_putchar);
2141 2141 uart_console_write(port, wctxt->outbuf, wctxt->len,
2142 2142 imx_uart_console_putchar);
modified drivers/tty/serial/sifive.c
@@ -821,7 +821,7 @@ static void sifive_serial_console_write_atomic(struct console *co,
821 821 ier = __ssp_readl(ssp, SIFIVE_SERIAL_IE_OFFS);
822 822 __ssp_writel(0, SIFIVE_SERIAL_IE_OFFS, ssp);
823 823
824 - if (!ssp->console_line_ended)
824 + if (unlikely(!ssp->console_line_ended && !nbcon_is_braille(co)))
825 825 uart_console_write(port, "\n", 1, sifive_serial_console_putchar);
826 826 uart_console_write(port, wctxt->outbuf, wctxt->len,
827 827 sifive_serial_console_putchar);
modified drivers/ufs/core/ufs-mcq.c
@@ -312,20 +312,24 @@ static int ufshcd_mcq_get_tag(struct ufs_hba *hba, struct cq_entry *cqe)
312 312 UFSHCD_NUM_RESERVED;
313 313 }
314 314
315 + static void ufshcd_mcq_compl_cqe(struct ufs_hba *hba, struct cq_entry *cqe)
316 + {
317 + int tag = ufshcd_mcq_get_tag(hba, cqe);
318 +
319 + ufshcd_compl_one_cqe(hba, tag, cqe);
320 + /* After processing the CQE, mark it as an empty (invalid) entry. */
321 + cqe->command_desc_base_addr = 0;
322 + }
323 +
315 324 static void ufshcd_mcq_process_cqe(struct ufs_hba *hba,
316 325 struct ufs_hw_queue *hwq)
317 326 {
318 327 struct cq_entry *cqe = ufshcd_mcq_cur_cqe(hwq);
319 328
320 - if (cqe->command_desc_base_addr) {
321 - int tag = ufshcd_mcq_get_tag(hba, cqe);
322 -
323 - ufshcd_compl_one_cqe(hba, tag, cqe);
324 - /* After processed the cqe, mark it empty (invalid) entry */
325 - cqe->command_desc_base_addr = 0;
326 - } else {
329 + if (cqe->command_desc_base_addr)
330 + ufshcd_mcq_compl_cqe(hba, cqe);
331 + else
327 332 dev_err(hba->dev, "Abnormal CQ entry!\n");
328 - }
329 333 }
330 334
331 335 /*
@@ -333,7 +337,7 @@ static void ufshcd_mcq_process_cqe(struct ufs_hba *hba,
333 337 * controller disabled (HCE = 0). Reading host controller registers, e.g. the
334 338 * CQ tail pointer (CQTPy), may not be safe with the host controller disabled.
335 339 * Hence, iterate over all completion queue entries. This won't result in
336 - * double completions because ufshcd_mcq_process_cqe() clears a CQE after it
340 + * double completions because ufshcd_mcq_compl_cqe() clears a CQE after it
337 341 * has been processed.
338 342 */
339 343 void ufshcd_mcq_compl_all_cqes_lock(struct ufs_hba *hba,
@@ -344,13 +348,13 @@ void ufshcd_mcq_compl_all_cqes_lock(struct ufs_hba *hba,
344 348
345 349 spin_lock_irqsave(&hwq->cq_lock, flags);
346 350 while (entries > 0) {
347 - ufshcd_mcq_process_cqe(hba, hwq);
351 + struct cq_entry *cqe = ufshcd_mcq_cur_cqe(hwq);
352 +
353 + if (cqe->command_desc_base_addr)
354 + ufshcd_mcq_compl_cqe(hba, cqe);
348 355 ufshcd_mcq_inc_cq_head_slot(hwq);
349 356 entries--;
350 357 }
351 -
352 - ufshcd_mcq_update_cq_tail_slot(hwq);
353 - hwq->cq_head_slot = hwq->cq_tail_slot;
354 358 spin_unlock_irqrestore(&hwq->cq_lock, flags);
355 359 }
356 360
modified drivers/ufs/core/ufshcd.c
@@ -6044,8 +6044,6 @@ static bool ufshcd_mcq_force_compl_one(struct request *rq, void *priv)
6044 6044 if (blk_mq_is_reserved_rq(rq) || !hwq)
6045 6045 return true;
6046 6046
6047 - ufshcd_mcq_compl_all_cqes_lock(hba, hwq);
6048 -
6049 6047 /*
6050 6048 * For those cmds of which the cqes are not present in the cq, complete
6051 6049 * them explicitly.
@@ -6061,19 +6059,6 @@ static bool ufshcd_mcq_force_compl_one(struct request *rq, void *priv)
6061 6059 return true;
6062 6060 }
6063 6061
6064 - static bool ufshcd_mcq_compl_one(struct request *rq, void *priv)
6065 - {
6066 - struct scsi_device *sdev = rq->q->queuedata;
6067 - struct Scsi_Host *shost = sdev->host;
6068 - struct ufs_hba *hba = shost_priv(shost);
6069 - struct ufs_hw_queue *hwq = ufshcd_mcq_req_to_hwq(hba, rq);
6070 -
6071 - if (!blk_mq_is_reserved_rq(rq) && hwq)
6072 - ufshcd_mcq_poll_cqe_lock(hba, hwq);
6073 -
6074 - return true;
6075 - }
6076 -
6077 6062 /**
6078 6063 * ufshcd_mcq_compl_pending_transfer - MCQ mode function. It is
6079 6064 * invoked from the error handler context or ufshcd_host_reset_and_restore()
@@ -6088,10 +6073,18 @@ static bool ufshcd_mcq_compl_one(struct request *rq, void *priv)
6088 6073 static void ufshcd_mcq_compl_pending_transfer(struct ufs_hba *hba,
6089 6074 bool force_compl)
6090 6075 {
6091 - blk_mq_tagset_busy_iter(&hba->host->tag_set,
6092 - force_compl ? ufshcd_mcq_force_compl_one :
6093 - ufshcd_mcq_compl_one,
6094 - NULL);
6076 + int i;
6077 +
6078 + for (i = 0; i < hba->nr_hw_queues; i++) {
6079 + if (force_compl)
6080 + ufshcd_mcq_compl_all_cqes_lock(hba, &hba->uhq[i]);
6081 + else
6082 + ufshcd_mcq_poll_cqe_lock(hba, &hba->uhq[i]);
6083 + }
6084 +
6085 + if (force_compl)
6086 + blk_mq_tagset_busy_iter(&hba->host->tag_set,
6087 + ufshcd_mcq_force_compl_one, NULL);
6095 6088 }
6096 6089
6097 6090 /**
@@ -9556,6 +9549,7 @@ static void ufshcd_async_scan(void *data, async_cookie_t cookie)
9556 9549 ret = ufshcd_add_lus(hba);
9557 9550
9558 9551 out:
9552 + ufshcd_release(hba);
9559 9553 pm_runtime_put_sync(hba->dev);
9560 9554
9561 9555 if (ret)
@@ -11278,6 +11272,9 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11278 11272
11279 11273 ufshcd_init_clk_gating(hba);
11280 11274
11275 + /* Released by ufshcd_async_scan(), or by out_release on failure. */
11276 + ufshcd_hold(hba);
11277 +
11281 11278 ufshcd_init_clk_scaling(hba);
11282 11279
11283 11280 /*
@@ -11298,7 +11295,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11298 11295 err = devm_request_irq(dev, irq, ufshcd_intr, IRQF_SHARED, UFSHCD, hba);
11299 11296 if (err) {
11300 11297 dev_err(hba->dev, "request irq failed\n");
11301 - goto out_disable;
11298 + goto out_release;
11302 11299 } else {
11303 11300 hba->is_irq_enabled = true;
11304 11301 }
@@ -11314,7 +11311,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11314 11311 dev_err(hba->dev, "Host controller enable failed\n");
11315 11312 ufshcd_print_evt_hist(hba);
11316 11313 ufshcd_print_host_state(hba);
11317 - goto out_disable;
11314 + goto out_release;
11318 11315 }
11319 11316
11320 11317 INIT_DELAYED_WORK(&hba->rpm_dev_flush_recheck_work, ufshcd_rpm_dev_flush_recheck_work);
@@ -11328,7 +11325,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11328 11325
11329 11326 err = ufshcd_add_scsi_host(hba);
11330 11327 if (err)
11331 - goto out_disable;
11328 + goto out_release;
11332 11329
11333 11330 /* Hold auto suspend until async scan completes */
11334 11331 pm_runtime_get_sync(dev);
@@ -11348,7 +11345,7 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11348 11345
11349 11346 err = ufshcd_link_startup(hba);
11350 11347 if (err)
11351 - goto out_disable;
11348 + goto out_release;
11352 11349
11353 11350 if (hba->mcq_enabled)
11354 11351 ufshcd_config_mcq(hba);
@@ -11365,23 +11362,23 @@ int ufshcd_init(struct ufs_hba *hba, void __iomem *mmio_base, unsigned int irq)
11365 11362 /* Verify device initialization by sending NOP OUT UPIU */
11366 11363 err = ufshcd_verify_dev_init(hba);
11367 11364 if (err)
11368 - goto out_disable;
11365 + goto out_release;
11369 11366
11370 11367 /* Initiate UFS initialization, and waiting until completion */
11371 11368 err = ufshcd_complete_dev_init(hba);
11372 11369 if (err)
11373 - goto out_disable;
11370 + goto out_release;
11374 11371
11375 11372 err = ufshcd_device_params_init(hba);
11376 11373 if (err)
11377 - goto out_disable;
11374 + goto out_release;
11378 11375
11379 11376 err = ufshcd_post_device_init(hba);
11380 11377
11381 11378 initialized:
11382 11379 ufshcd_process_probe_result(hba, probe_start, err);
11383 11380 if (err)
11384 - goto out_disable;
11381 + goto out_release;
11385 11382
11386 11383 ufs_sysfs_add_nodes(hba->dev);
11387 11384 hba->dme_qos_sysfs_handle = sysfs_get_dirent(hba->dev->kobj.sd,
@@ -11392,6 +11389,8 @@ initialized:
11392 11389 ufshcd_pm_qos_init(hba);
11393 11390 return 0;
11394 11391
11392 + out_release:
11393 + ufshcd_release(hba);
11395 11394 out_disable:
11396 11395 hba->is_irq_enabled = false;
11397 11396 ufshcd_hba_exit(hba);
modified drivers/ufs/host/ufs-mediatek.c
@@ -509,6 +509,7 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on)
509 509 struct ufs_mtk_host *host = ufshcd_get_variant(hba);
510 510 struct phy *mphy = host->mphy;
511 511 struct arm_smccc_res res;
512 + int err;
512 513 int ret = 0;
513 514
514 515 if (!mphy || !(on ^ host->mphy_powered_on))
@@ -523,7 +524,18 @@ static int ufs_mtk_mphy_power_on(struct ufs_hba *hba, bool on)
523 524 usleep_range(200, 210);
524 525 ufs_mtk_va09_pwr_ctrl(res, 1);
525 526 }
526 - phy_power_on(mphy);
527 + ret = phy_power_on(mphy);
528 + if (ret) {
529 + if (ufs_mtk_is_va09_supported(hba)) {
530 + ufs_mtk_va09_pwr_ctrl(res, 0);
531 + err = regulator_disable(host->reg_va09);
532 + if (err)
533 + dev_err(hba->dev,
534 + "failed to unwind va09: %d\n", err);
535 + }
536 + dev_err(hba->dev, "failed to enable mphy: %d\n", ret);
537 + return ret;
538 + }
527 539 } else {
528 540 phy_power_off(mphy);
529 541 if (ufs_mtk_is_va09_supported(hba)) {
@@ -1295,7 +1307,9 @@ static int ufs_mtk_init(struct ufs_hba *hba)
1295 1307 *
1296 1308 * Enable phy clocks specifically here.
1297 1309 */
1298 - ufs_mtk_mphy_power_on(hba, true);
1310 + err = ufs_mtk_mphy_power_on(hba, true);
1311 + if (err)
1312 + goto out_variant_clear;
1299 1313
1300 1314 if (ufs_mtk_is_rtff_mtcmos(hba)) {
1301 1315 /* First Restore here, to avoid backup unexpected value */
modified drivers/usb/mtu3/mtu3_trace.h
@@ -224,6 +224,7 @@ DECLARE_EVENT_CLASS(mtu3_log_ep,
224 224 __field(unsigned int, flags)
225 225 __field(unsigned int, direction)
226 226 __field(struct mtu3_gpd_ring *, gpd_ring)
227 + __field(dma_addr_t, gpd_ring_dma)
227 228 ),
228 229 TP_fast_assign(
229 230 __assign_str(name);
@@ -235,12 +236,13 @@ DECLARE_EVENT_CLASS(mtu3_log_ep,
235 236 __entry->flags = mep->flags;
236 237 __entry->direction = mep->is_in;
237 238 __entry->gpd_ring = &mep->gpd_ring;
239 + __entry->gpd_ring_dma = mep->gpd_ring.dma
238 240 ),
239 241 TP_printk("%s: type %s maxp %d slot %d mult %d burst %d ring %p/%pad flags %c:%c%c%c:%c",
240 242 __get_str(name), usb_ep_type_string(__entry->type),
241 243 __entry->maxp, __entry->slot,
242 244 __entry->mult, __entry->maxburst,
243 - __entry->gpd_ring, &__entry->gpd_ring->dma,
245 + __entry->gpd_ring, &__entry->gpd_ring_dma,
244 246 __entry->flags & MTU3_EP_ENABLED ? 'E' : 'e',
245 247 __entry->flags & MTU3_EP_STALL ? 'S' : 's',
246 248 __entry->flags & MTU3_EP_WEDGE ? 'W' : 'w',
modified fs/9p/v9fs.h
@@ -137,6 +137,7 @@ struct v9fs_session_info {
137 137 struct list_head slist; /* list of sessions registered with v9fs */
138 138 struct rw_semaphore rename_sem;
139 139 long session_lock_timeout; /* retry interval for blocking locks */
140 + struct rcu_head rcu; /* v9fs_vfs_get_link_dotl() reads ->cache in rcu pathwalk */
140 141 };
141 142
142 143 #define NDENTRY_TIMEOUT_NEVER (-1U)
modified fs/9p/vfs_super.c
@@ -173,8 +173,8 @@ static void v9fs_kill_super(struct super_block *s)
173 173
174 174 v9fs_session_cancel(v9ses);
175 175 v9fs_session_close(v9ses);
176 - kfree(v9ses);
177 - s->s_fs_info = NULL;
176 + /* v9fs_vfs_get_link_dotl() may still read ->cache in rcu pathwalk */
177 + kfree_rcu(v9ses, rcu);
178 178 p9_debug(P9_DEBUG_VFS, "exiting kill_super\n");
179 179 }
180 180
modified fs/afs/internal.h
@@ -251,6 +251,8 @@ struct afs_super_info {
251 251 struct afs_volume *volume; /* volume record */
252 252 enum afs_flock_mode flock_mode:8; /* File locking emulation mode */
253 253 bool dyn_root; /* True if dynamic root */
254 + /* afs_atcell_get_link() reads ->net_ns in rcu pathwalk */
255 + struct rcu_head rcu;
254 256 };
255 257
256 258 static inline struct afs_super_info *AFS_FS_S(struct super_block *sb)
modified fs/afs/super.c
@@ -523,7 +523,7 @@ static void afs_destroy_sbi(struct afs_super_info *as)
523 523 afs_put_volume(as->volume, afs_volume_trace_put_destroy_sbi);
524 524 afs_unuse_cell(as->cell, afs_cell_trace_unuse_sbi);
525 525 put_net(as->net_ns);
526 - kfree(as);
526 + kfree_rcu(as, rcu);
527 527 }
528 528 }
529 529
modified fs/autofs/waitq.c
@@ -12,15 +12,13 @@
12 12 */
13 13 static autofs_wqt_t autofs_next_wait_queue = 1;
14 14
15 - void autofs_catatonic_mode(struct autofs_sb_info *sbi)
15 + static void autofs_catatonic_mode_locked(struct autofs_sb_info *sbi)
16 16 {
17 17 struct autofs_wait_queue *wq, *nwq;
18 18
19 - mutex_lock(&sbi->wq_mutex);
20 - if (sbi->flags & AUTOFS_SBI_CATATONIC) {
21 - mutex_unlock(&sbi->wq_mutex);
19 + lockdep_assert_held(&sbi->wq_mutex);
20 + if (sbi->flags & AUTOFS_SBI_CATATONIC)
22 21 return;
23 - }
24 22
25 23 pr_debug("entering catatonic mode\n");
26 24
@@ -40,6 +38,21 @@ void autofs_catatonic_mode(struct autofs_sb_info *sbi)
40 38 fput(sbi->pipe); /* Close the pipe */
41 39 sbi->pipe = NULL;
42 40 sbi->pipefd = -1;
41 + }
42 +
43 + void autofs_catatonic_mode(struct autofs_sb_info *sbi)
44 + {
45 + mutex_lock(&sbi->wq_mutex);
46 + autofs_catatonic_mode_locked(sbi);
47 + mutex_unlock(&sbi->wq_mutex);
48 + }
49 +
50 + static void autofs_catatonic_mode_for_pipe(struct autofs_sb_info *sbi,
51 + struct file *pipe)
52 + {
53 + mutex_lock(&sbi->wq_mutex);
54 + if (sbi->pipe == pipe)
55 + autofs_catatonic_mode_locked(sbi);
43 56 mutex_unlock(&sbi->wq_mutex);
44 57 }
45 58
@@ -170,7 +183,7 @@ static void autofs_notify_daemon(struct autofs_sb_info *sbi,
170 183 autofs_wait_release(sbi, wq->wait_queue_token, ret);
171 184 break;
172 185 default:
173 - autofs_catatonic_mode(sbi);
186 + autofs_catatonic_mode_for_pipe(sbi, pipe);
174 187 break;
175 188 }
176 189 fput(pipe);
modified fs/btrfs/inode.c
@@ -9623,7 +9623,6 @@ int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9623 9623 struct completion sync_reads;
9624 9624 unsigned long i = 0;
9625 9625 struct btrfs_bio *bbio;
9626 - int ret;
9627 9626
9628 9627 /*
9629 9628 * Fast path for synchronous reads which completes in this call, io_uring
@@ -9670,10 +9669,10 @@ int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9670 9669
9671 9670 if (uring_ctx) {
9672 9671 if (refcount_dec_and_test(&priv->pending_refs)) {
9673 - ret = blk_status_to_errno(READ_ONCE(priv->status));
9674 - btrfs_uring_read_extent_endio(uring_ctx, ret);
9672 + int error = blk_status_to_errno(READ_ONCE(priv->status));
9673 +
9674 + btrfs_uring_read_extent_endio(uring_ctx, error);
9675 9675 kfree(priv);
9676 - return ret;
9677 9676 }
9678 9677
9679 9678 return -EIOCBQUEUED;
modified fs/btrfs/ioctl.c
@@ -4601,7 +4601,7 @@ static void btrfs_uring_read_finished(struct io_tw_req tw_req, io_tw_token_t tw)
4601 4601 size_t page_offset;
4602 4602 ssize_t ret;
4603 4603
4604 - /* The inode lock has already been acquired in btrfs_uring_read_extent. */
4604 + /* The inode lock has already been acquired in btrfs_encoded_read(). */
4605 4605 btrfs_lockdep_inode_acquire(inode, i_rwsem);
4606 4606
4607 4607 if (priv->err) {
@@ -4667,7 +4667,6 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter,
4667 4667 struct iovec *iov, struct io_uring_cmd *cmd)
4668 4668 {
4669 4669 struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
4670 - struct extent_io_tree *io_tree = &inode->io_tree;
4671 4670 struct page **pages = NULL;
4672 4671 struct btrfs_uring_priv *priv = NULL;
4673 4672 unsigned long nr_pages;
@@ -4723,8 +4722,6 @@ static int btrfs_uring_read_extent(struct kiocb *iocb, struct iov_iter *iter,
4723 4722 return -EIOCBQUEUED;
4724 4723
4725 4724 out_fail:
4726 - btrfs_unlock_extent(io_tree, start, lockend, &cached_state);
4727 - btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4728 4725 kfree(priv);
4729 4726 for (int i = 0; i < nr_pages; i++) {
4730 4727 if (pages[i])
@@ -4837,7 +4834,7 @@ static int btrfs_uring_encoded_read(struct io_uring_cmd *cmd, unsigned int issue
4837 4834 ret = btrfs_encoded_read(&kiocb, &data->iter, &data->args, &cached_state,
4838 4835 &disk_bytenr, &disk_io_size);
4839 4836 if (ret == -EAGAIN)
4840 - goto out_acct;
4837 + goto out_free;
4841 4838 if (ret < 0 && ret != -EIOCBQUEUED)
4842 4839 goto out_free;
4843 4840
@@ -4865,8 +4862,10 @@ static int btrfs_uring_encoded_read(struct io_uring_cmd *cmd, unsigned int issue
4865 4862 cached_state, disk_bytenr, disk_io_size,
4866 4863 count, data->args.compression,
4867 4864 data->iov, cmd);
4868 -
4869 - goto out_acct;
4865 + if (ret == -EIOCBQUEUED)
4866 + goto out_acct;
4867 + btrfs_unlock_extent(io_tree, start, lockend, &cached_state);
4868 + btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4870 4869 }
4871 4870
4872 4871 out_free:
@@ -4877,8 +4876,10 @@ out_acct:
4877 4876 add_rchar(current, ret);
4878 4877 inc_syscr(current);
4879 4878
4880 - if (ret != -EIOCBQUEUED && ret != -EAGAIN)
4879 + if (ret != -EIOCBQUEUED) {
4881 4880 kfree(data);
4881 + bc->data = NULL;
4882 + }
4882 4883
4883 4884 return ret;
4884 4885 }
@@ -4907,6 +4908,11 @@ static int btrfs_uring_encoded_write(struct io_uring_cmd *cmd, unsigned int issu
4907 4908 goto out_acct;
4908 4909 }
4909 4910
4911 + if (issue_flags & IO_URING_F_NONBLOCK) {
4912 + ret = -EAGAIN;
4913 + goto out_acct;
4914 + }
4915 +
4910 4916 if (!data) {
4911 4917 data = kzalloc_obj(*data, GFP_NOFS);
4912 4918 if (!data) {
@@ -4975,11 +4981,6 @@ static int btrfs_uring_encoded_write(struct io_uring_cmd *cmd, unsigned int issu
4975 4981 }
4976 4982 }
4977 4983
4978 - if (issue_flags & IO_URING_F_NONBLOCK) {
4979 - ret = -EAGAIN;
4980 - goto out_acct;
4981 - }
4982 -
4983 4984 pos = data->args.offset;
4984 4985 ret = rw_verify_area(WRITE, file, &pos, data->args.len);
4985 4986 if (ret < 0)
@@ -5005,8 +5006,8 @@ out_acct:
5005 5006 add_wchar(current, ret);
5006 5007 inc_syscw(current);
5007 5008
5008 - if (ret != -EAGAIN)
5009 - kfree(data);
5009 + kfree(data);
5010 + bc->data = NULL;
5010 5011 return ret;
5011 5012 }
5012 5013
modified fs/btrfs/scrub.c
@@ -536,8 +536,10 @@ static int scrub_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
536 536 }
537 537 ret = paths_from_inode(inum, ipath);
538 538
539 - if (ret < 0)
539 + if (ret < 0) {
540 + btrfs_put_root(local_root);
540 541 goto err;
542 + }
541 543
542 544 /*
543 545 * we deliberately ignore the bit ipath might have been too small to
modified fs/btrfs/transaction.c
@@ -432,6 +432,7 @@ static int record_root_in_trans(struct btrfs_trans_handle *trans,
432 432 spin_lock(&fs_info->fs_roots_radix_lock);
433 433 if (btrfs_get_root_last_trans(root) == trans->transid && !force) {
434 434 spin_unlock(&fs_info->fs_roots_radix_lock);
435 + clear_bit(BTRFS_ROOT_IN_TRANS_SETUP, &root->state);
435 436 return 0;
436 437 }
437 438 radix_tree_tag_set(&fs_info->fs_roots_radix,
modified fs/btrfs/xattr.c
@@ -161,6 +161,7 @@ int btrfs_setxattr(struct btrfs_trans_handle *trans, struct inode *inode,
161 161 const u16 old_data_len = btrfs_dir_data_len(leaf, di);
162 162 const u32 item_size = btrfs_item_size(leaf, slot);
163 163 const u32 data_size = sizeof(*di) + name_len + size;
164 + unsigned long name_ptr;
164 165 unsigned long data_ptr;
165 166 char *ptr;
166 167
@@ -189,8 +190,16 @@ int btrfs_setxattr(struct btrfs_trans_handle *trans, struct inode *inode,
189 190 ptr = btrfs_item_ptr(leaf, slot, char);
190 191 ptr += btrfs_item_size(leaf, slot) - data_size;
191 192 di = (struct btrfs_dir_item *)ptr;
193 + memzero_extent_buffer(leaf, (unsigned long)ptr +
194 + offsetof(struct btrfs_dir_item, location),
195 + sizeof(struct btrfs_disk_key));
196 + btrfs_set_dir_flags(leaf, di, BTRFS_FT_XATTR);
197 + btrfs_set_dir_transid(leaf, di, trans->transid);
198 + btrfs_set_dir_name_len(leaf, di, name_len);
192 199 btrfs_set_dir_data_len(leaf, di, size);
200 + name_ptr = (unsigned long)(di + 1);
193 201 data_ptr = ((unsigned long)(di + 1)) + name_len;
202 + write_extent_buffer(leaf, name, name_ptr, name_len);
194 203 write_extent_buffer(leaf, value, data_ptr, size);
195 204 } else {
196 205 /*
@@ -320,10 +329,8 @@ ssize_t btrfs_listxattr(struct dentry *dentry, char *buffer, size_t size)
320 329 if (!size)
321 330 goto next;
322 331
323 - if (!buffer || (name_len + 1) > size_left) {
324 - iter_ret = -ERANGE;
325 - break;
326 - }
332 + if (!buffer || (name_len + 1) > size_left)
333 + return -ERANGE;
327 334
328 335 read_extent_buffer(leaf, buffer, name_ptr, name_len);
329 336 buffer[name_len] = '\0';
modified fs/dcache.c
@@ -1583,6 +1583,8 @@ EXPORT_SYMBOL(path_has_submounts);
1583 1583 *
1584 1584 * Only one of d_invalidate() and d_set_mounted() must succeed. For
1585 1585 * this reason take rename_lock and d_lock on dentry and ancestors.
1586 + * Likewise for dont_mount() which marks a dentry that is being removed
1587 + * under d_lock.
1586 1588 */
1587 1589 int d_set_mounted(struct dentry *dentry)
1588 1590 {
@@ -1599,7 +1601,7 @@ int d_set_mounted(struct dentry *dentry)
1599 1601 spin_unlock(&p->d_lock);
1600 1602 }
1601 1603 spin_lock(&dentry->d_lock);
1602 - if (!d_unlinked(dentry)) {
1604 + if (!d_unlinked(dentry) && !cant_mount(dentry)) {
1603 1605 ret = -EBUSY;
1604 1606 if (!d_mountpoint(dentry)) {
1605 1607 dentry->d_flags |= DCACHE_MOUNTED;
modified fs/ext4/ext4.h
@@ -1774,6 +1774,8 @@ struct ext4_sb_info {
1774 1774 struct list_head s_es_list; /* List of inodes with reclaimable extents */
1775 1775 long s_es_nr_inode;
1776 1776 struct ext4_es_stats s_es_stats;
1777 + /* ext4_get_link() reads the sbi in rcu pathwalk */
1778 + struct rcu_head s_rcu;
1777 1779 struct mb_cache *s_ea_block_cache;
1778 1780 struct mb_cache *s_ea_inode_cache;
1779 1781
modified fs/ext4/extents-test.c
@@ -151,6 +151,7 @@ static void extents_kunit_exit(struct kunit *test)
151 151
152 152 sbi = k_ctx.k_ei->vfs_inode.i_sb->s_fs_info;
153 153 ext4_es_unregister_shrinker(sbi);
154 + ext4_es_destroy_stats(sbi);
154 155 deactivate_super(sbi->s_sb);
155 156 kfree(sbi);
156 157 kfree(k_ctx.k_ei);
@@ -340,6 +341,7 @@ out:
340 341 k_ctx.k_data = NULL;
341 342
342 343 ext4_es_unregister_shrinker(sbi);
344 + ext4_es_destroy_stats(sbi);
343 345 out_deactivate:
344 346 deactivate_locked_super(sb);
345 347 kfree(sbi);
modified fs/ext4/extents.c
@@ -6409,6 +6409,7 @@ EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_ext_dirty);
6409 6409 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_ext_zeroout);
6410 6410 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_register_shrinker);
6411 6411 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_unregister_shrinker);
6412 + EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_destroy_stats);
6412 6413 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_create_blocks);
6413 6414 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_init_tree);
6414 6415 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_es_lookup_extent);
modified fs/ext4/extents_status.c
@@ -1881,12 +1881,17 @@ err1:
1881 1881 }
1882 1882
1883 1883 void ext4_es_unregister_shrinker(struct ext4_sb_info *sbi)
1884 + {
1885 + shrinker_free(sbi->s_es_shrinker);
1886 + }
1887 +
1888 + /* ext4_get_link() bumps the hit and miss counters in rcu pathwalk */
1889 + void ext4_es_destroy_stats(struct ext4_sb_info *sbi)
1884 1890 {
1885 1891 percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_hits);
1886 1892 percpu_counter_destroy(&sbi->s_es_stats.es_stats_cache_misses);
1887 1893 percpu_counter_destroy(&sbi->s_es_stats.es_stats_all_cnt);
1888 1894 percpu_counter_destroy(&sbi->s_es_stats.es_stats_shk_cnt);
1889 - shrinker_free(sbi->s_es_shrinker);
1890 1895 }
1891 1896
1892 1897 /*
modified fs/ext4/extents_status.h
@@ -238,6 +238,7 @@ static inline void ext4_es_store_pblock_status(struct extent_status *es,
238 238
239 239 extern int ext4_es_register_shrinker(struct ext4_sb_info *sbi);
240 240 extern void ext4_es_unregister_shrinker(struct ext4_sb_info *sbi);
241 + extern void ext4_es_destroy_stats(struct ext4_sb_info *sbi);
241 242
242 243 extern int ext4_seq_es_shrinker_info_show(struct seq_file *seq, void *v);
243 244
modified fs/ext4/super.c
@@ -1279,6 +1279,14 @@ static void ext4_flex_groups_free(struct ext4_sb_info *sbi)
1279 1279 }
1280 1280 }
1281 1281
1282 + static void ext4_put_sbi_rcu(struct rcu_head *head)
1283 + {
1284 + struct ext4_sb_info *sbi = container_of(head, struct ext4_sb_info, s_rcu);
1285 +
1286 + ext4_es_destroy_stats(sbi);
1287 + kfree(sbi);
1288 + }
1289 +
1282 1290 static void ext4_put_super(struct super_block *sb)
1283 1291 {
1284 1292 struct ext4_sb_info *sbi = EXT4_SB(sb);
@@ -1374,7 +1382,6 @@ static void ext4_put_super(struct super_block *sb)
1374 1382 ext4_stop_mmpd(sbi);
1375 1383
1376 1384 brelse(sbi->s_sbh);
1377 - sb->s_fs_info = NULL;
1378 1385 /*
1379 1386 * Now that we are completely done shutting down the
1380 1387 * superblock, we need to actually destroy the kobject.
@@ -1387,7 +1394,8 @@ static void ext4_put_super(struct super_block *sb)
1387 1394 #if IS_ENABLED(CONFIG_UNICODE)
1388 1395 utf8_unload(sb->s_encoding);
1389 1396 #endif
1390 - kfree(sbi);
1397 + /* ext4_get_link() reads the sbi and the counters in rcu pathwalk */
1398 + call_rcu(&sbi->s_rcu, ext4_put_sbi_rcu);
1391 1399 }
1392 1400
1393 1401 static struct kmem_cache *ext4_inode_cachep;
@@ -5057,6 +5065,7 @@ out:
5057 5065 static int ext4_check_journal_data_mode(struct super_block *sb)
5058 5066 {
5059 5067 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
5068 + printk(KERN_WARNING "EXT4-fs: The data=journal mount option is deprecated and support will be removed in January 2028\n");
5060 5069 printk_once(KERN_WARNING "EXT4-fs: Warning: mounting with "
5061 5070 "data=journal disables delayed allocation, "
5062 5071 "dioread_nolock, O_DIRECT and fast_commit support!\n");
@@ -5805,6 +5814,7 @@ failed_mount3a:
5805 5814 /* Drain deferred EA inode iputs from journal replay */
5806 5815 flush_delayed_work(&sbi->s_ea_inode_work);
5807 5816 ext4_es_unregister_shrinker(sbi);
5817 + ext4_es_destroy_stats(sbi);
5808 5818 failed_mount3:
5809 5819 /* flush s_sb_upd_work before sbi destroy */
5810 5820 flush_work(&sbi->s_sb_upd_work);
modified fs/fcntl.c
@@ -372,6 +372,9 @@ static long fcntl_set_rw_hint(struct file *file, unsigned long arg)
372 372 u64 __user *argp = (u64 __user *)arg;
373 373 u64 hint;
374 374
375 + /* nothing is ever written to it */
376 + if (IS_IMMUTABLE(inode))
377 + return -EPERM;
375 378 if (!inode_owner_or_capable(file_mnt_idmap(file), inode))
376 379 return -EPERM;
377 380
modified fs/fhandle.c
@@ -298,6 +298,22 @@ static bool capable_wrt_mount(struct mount *mount)
298 298 return mnt_ns && ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN);
299 299 }
300 300
301 + /*
302 + * Does the caller have an unobstructed way to everything below @root? Only
303 + * if the mount is mounted, the caller is privileged over its mount namespace
304 + * and no locked child covers something below @root->dentry. One answer from
305 + * under mount_lock: an umount in between clears ->mnt_ns and takes the
306 + * children off the mount, the locked ones too.
307 + */
308 + static bool subtree_unobstructed(const struct path *root)
309 + {
310 + struct mount *mnt = real_mount(root->mnt);
311 +
312 + guard(mount_locked_reader)();
313 + return is_mounted(root->mnt) && capable_wrt_mount(mnt) &&
314 + !has_locked_children(mnt, root->dentry);
315 + }
316 +
301 317 static inline int may_decode_fh(struct handle_to_path_ctx *ctx,
302 318 unsigned int o_flags)
303 319 {
@@ -332,9 +348,7 @@ static inline int may_decode_fh(struct handle_to_path_ctx *ctx,
332 348
333 349 if (ns_capable(root->mnt->mnt_sb->s_user_ns, CAP_SYS_ADMIN))
334 350 ctx->flags = HANDLE_CHECK_PERMS;
335 - else if (is_mounted(root->mnt) &&
336 - capable_wrt_mount(real_mount(root->mnt)) &&
337 - !has_locked_children(real_mount(root->mnt), root->dentry))
351 + else if (subtree_unobstructed(root))
338 352 ctx->flags = HANDLE_CHECK_PERMS | HANDLE_CHECK_SUBTREE;
339 353 else
340 354 return -EPERM;
modified fs/file_table.c
@@ -520,7 +520,8 @@ static void __fput(struct file *file)
520 520 dput(dentry);
521 521 if (unlikely(mode & FMODE_NEED_UNMOUNT))
522 522 dissolve_on_fput(mnt);
523 - mntput(mnt);
523 + else
524 + mntput(mnt);
524 525 out:
525 526 file_free(file);
526 527 }
modified fs/fs_context.c
@@ -315,6 +315,10 @@ struct fs_context *fs_context_for_reconfigure(struct dentry *dentry,
315 315 unsigned int sb_flags,
316 316 unsigned int sb_flags_mask)
317 317 {
318 + /* kernel-internal superblocks are nobody's to reconfigure */
319 + if (dentry->d_sb->s_flags & SB_NOUSER)
320 + return ERR_PTR(-EINVAL);
321 +
318 322 return alloc_fs_context(dentry->d_sb->s_type, dentry, sb_flags,
319 323 sb_flags_mask, FS_CONTEXT_FOR_RECONFIGURE);
320 324 }
modified fs/mount.h
@@ -6,6 +6,8 @@
6 6 #include <linux/fs_pin.h>
7 7
8 8 extern struct file_system_type nullfs_fs_type;
9 + extern struct dentry *nullfs_new_file(struct super_block *sb);
10 + extern struct vfsmount *knullfs;
9 11 extern struct list_head notify_list;
10 12
11 13 struct mnt_namespace {
@@ -33,16 +35,20 @@ struct mnt_namespace {
33 35 } __randomize_layout;
34 36
35 37 struct mnt_pcp {
36 - int mnt_count;
38 + unsigned int mnt_gets;
39 + unsigned int mnt_puts;
37 40 int mnt_writers;
38 41 };
39 42
40 43 struct mountpoint {
41 44 struct hlist_node m_hash;
42 45 struct dentry *m_dentry;
43 - struct hlist_head m_list;
46 + struct hlist_head m_list; /* mounts on it and pins */
47 + struct hlist_head m_covers; /* covers of unmounted parents */
44 48 };
45 49
50 + struct mnt_cover;
51 +
46 52 struct mount {
47 53 struct hlist_node mnt_hash;
48 54 struct mount *mnt_parent;
@@ -84,7 +90,7 @@ struct mount {
84 90 struct mountpoint *mnt_mp; /* where is it mounted */
85 91 union {
86 92 struct hlist_node mnt_mp_list; /* list mounts with the same mountpoint */
87 - struct hlist_node mnt_umount;
93 + struct hlist_node mnt_umount; /* on the unmounted list */
88 94 };
89 95 #ifdef CONFIG_FSNOTIFY
90 96 struct fsnotify_mark_connector __rcu *mnt_fsnotify_marks;
@@ -98,7 +104,8 @@ struct mount {
98 104 int mnt_group_id; /* peer group identifier */
99 105 int mnt_expiry_mark; /* true if marked for expiry */
100 106 struct hlist_head mnt_pins;
101 - struct hlist_head mnt_stuck_children;
107 + struct mnt_cover *mnt_cover; /* the one it may leave behind */
108 + struct hlist_head mnt_covers; /* left behind by its unmounted children */
102 109 struct hlist_node mnt_ns_visible; /* link in ns->mnt_visible_mounts */
103 110 struct mount *overmount; /* mounted on ->mnt_root */
104 111 } __randomize_layout;
@@ -233,6 +240,9 @@ static inline struct mnt_namespace *to_mnt_ns(struct ns_common *ns)
233 240 #ifdef CONFIG_FSNOTIFY
234 241 static inline void mnt_notify_add(struct mount *m)
235 242 {
243 + /* queued already under this namespace_sem hold */
244 + if (!list_empty(&m->to_notify))
245 + return;
236 246 /* Optimize the case where there are no watches */
237 247 if ((m->mnt_ns && m->mnt_ns->n_fsnotify_marks) ||
238 248 (m->prev_ns && m->prev_ns->n_fsnotify_marks))
modified fs/namei.c
@@ -4721,8 +4721,7 @@ static struct dentry *lookup_fast_for_open(struct nameidata *nd, int open_flag)
4721 4721 return dentry;
4722 4722
4723 4723 if (open_flag & O_CREAT) {
4724 - /* Discard negative dentries. Need inode_lock to do the create */
4725 - if (!dentry->d_inode) {
4724 + if (d_is_negative(dentry)) {
4726 4725 if (!(nd->flags & LOOKUP_RCU))
4727 4726 dput(dentry);
4728 4727 dentry = NULL;
modified fs/namespace.c
@@ -80,6 +80,8 @@ static u64 mnt_id_ctr = MNT_UNIQUE_ID_OFFSET;
80 80 static struct hlist_head *mount_hashtable __ro_after_init;
81 81 static struct hlist_head *mountpoint_hashtable __ro_after_init;
82 82 static struct kmem_cache *mnt_cache __ro_after_init;
83 + struct vfsmount *knullfs __ro_after_init; /* private nullfs instance */
84 + static struct vfsmount *knullfs_file __ro_after_init; /* its regular file */
83 85 static DECLARE_RWSEM(namespace_sem);
84 86 static HLIST_HEAD(unmounted); /* protected by namespace_sem */
85 87 static LIST_HEAD(ex_mountpoints); /* protected by namespace_sem */
@@ -130,7 +132,6 @@ static void mnt_ns_release(struct mnt_namespace *ns)
130 132 {
131 133 /* keep alive for {list,stat}mount() */
132 134 if (ns && refcount_dec_and_test(&ns->passive)) {
133 - fsnotify_mntns_delete(ns);
134 135 put_user_ns(ns->user_ns);
135 136 kfree(ns);
136 137 }
@@ -210,6 +211,19 @@ static inline struct hlist_head *mp_hash(struct dentry *dentry)
210 211 return &mountpoint_hashtable[tmp & mp_hash_mask];
211 212 }
212 213
214 + /*
215 + * What an unmounted mount leaves behind at its unmounted parent instead of
216 + * staying attached to it. A lookup on the parent at the mountpoint finds
217 + * a stand-in for as long as the cover is there. The parent frees it.
218 + */
219 + struct mnt_cover {
220 + struct hlist_node node; /* parent->mnt_covers, RCU */
221 + struct hlist_node pin; /* mp->m_covers, keeps the mountpoint */
222 + struct dentry *dentry;
223 + struct mountpoint *mp;
224 + struct rcu_head rcu;
225 + };
226 +
213 227 static int mnt_alloc_id(struct mount *mnt)
214 228 {
215 229 int res;
@@ -249,16 +263,24 @@ void mnt_release_group_id(struct mount *mnt)
249 263 mnt->mnt_group_id = 0;
250 264 }
251 265
252 - /*
253 - * vfsmount lock must be held for read
254 - */
255 - static inline void mnt_add_count(struct mount *mnt, int n)
266 + static inline void mnt_inc_count(struct mount *mnt)
267 + {
268 + #ifdef CONFIG_SMP
269 + this_cpu_inc(mnt->mnt_pcp->mnt_gets);
270 + #else
271 + preempt_disable();
272 + mnt->mnt_count++;
273 + preempt_enable();
274 + #endif
275 + }
276 +
277 + static inline void mnt_dec_count(struct mount *mnt)
256 278 {
257 279 #ifdef CONFIG_SMP
258 - this_cpu_add(mnt->mnt_pcp->mnt_count, n);
280 + this_cpu_inc(mnt->mnt_pcp->mnt_puts);
259 281 #else
260 282 preempt_disable();
261 - mnt->mnt_count += n;
283 + mnt->mnt_count--;
262 284 preempt_enable();
263 285 #endif
264 286 }
@@ -269,14 +291,21 @@ static inline void mnt_add_count(struct mount *mnt, int n)
269 291 int mnt_get_count(struct mount *mnt)
270 292 {
271 293 #ifdef CONFIG_SMP
272 - int count = 0;
294 + unsigned int gets = 0, puts = 0;
273 295 int cpu;
274 296
275 - for_each_possible_cpu(cpu) {
276 - count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count;
277 - }
297 + /* puts first, so a put counted here has its get counted below */
298 + for_each_possible_cpu(cpu)
299 + puts += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_puts;
300 + /*
301 + * Pairs with the smp_wmb() in mntput_no_expire() and with the
302 + * smp_mb() in __legitimize_mnt().
303 + */
304 + smp_mb();
305 + for_each_possible_cpu(cpu)
306 + gets += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_gets;
278 307
279 - return count;
308 + return gets - puts;
280 309 #else
281 310 return mnt->mnt_count;
282 311 #endif
@@ -288,6 +317,10 @@ static struct mount *alloc_vfsmnt(const char *name)
288 317 if (mnt) {
289 318 int err;
290 319
320 + mnt->mnt_cover = kzalloc_obj(struct mnt_cover, GFP_KERNEL_ACCOUNT);
321 + if (!mnt->mnt_cover)
322 + goto out_free_cache;
323 +
291 324 err = mnt_alloc_id(mnt);
292 325 if (err)
293 326 goto out_free_cache;
@@ -305,7 +338,7 @@ static struct mount *alloc_vfsmnt(const char *name)
305 338 if (!mnt->mnt_pcp)
306 339 goto out_free_devname;
307 340
308 - this_cpu_add(mnt->mnt_pcp->mnt_count, 1);
341 + this_cpu_inc(mnt->mnt_pcp->mnt_gets);
309 342 #else
310 343 mnt->mnt_count = 1;
311 344 mnt->mnt_writers = 0;
@@ -320,8 +353,11 @@ static struct mount *alloc_vfsmnt(const char *name)
320 353 INIT_HLIST_HEAD(&mnt->mnt_slave_list);
321 354 INIT_HLIST_NODE(&mnt->mnt_slave);
322 355 INIT_HLIST_NODE(&mnt->mnt_mp_list);
323 - INIT_HLIST_HEAD(&mnt->mnt_stuck_children);
356 + INIT_HLIST_HEAD(&mnt->mnt_covers);
324 357 INIT_HLIST_NODE(&mnt->mnt_ns_visible);
358 + #ifdef CONFIG_FSNOTIFY
359 + INIT_LIST_HEAD(&mnt->to_notify);
360 + #endif
325 361 RB_CLEAR_NODE(&mnt->mnt_node);
326 362 mnt->mnt.mnt_idmap = &nop_mnt_idmap;
327 363 }
@@ -334,6 +370,7 @@ out_free_devname:
334 370 out_free_id:
335 371 mnt_free_id(mnt);
336 372 out_free_cache:
373 + kfree(mnt->mnt_cover);
337 374 kmem_cache_free(mnt_cache, mnt);
338 375 return NULL;
339 376 }
@@ -725,6 +762,8 @@ int sb_prepare_remount_readonly(struct super_block *sb)
725 762 static void free_vfsmnt(struct mount *mnt)
726 763 {
727 764 mnt_idmap_put(mnt_idmap(&mnt->mnt));
765 + /* NULL if it left it behind */
766 + kfree(mnt->mnt_cover);
728 767 kfree_const(mnt->mnt_devname);
729 768 #ifdef CONFIG_SMP
730 769 free_percpu(mnt->mnt_pcp);
@@ -746,13 +785,13 @@ int __legitimize_mnt(struct vfsmount *bastard, unsigned seq)
746 785 if (bastard == NULL)
747 786 return 0;
748 787 mnt = real_mount(bastard);
749 - mnt_add_count(mnt, 1);
750 - smp_mb(); // see mntput_no_expire() and do_umount()
788 + mnt_inc_count(mnt);
789 + smp_mb(); /* pairs with the smp_mb() in mnt_get_count() */
751 790 if (likely(!read_seqretry(&mount_lock, seq)))
752 791 return 0;
753 792 lock_mount_hash();
754 793 if (unlikely(bastard->mnt_flags & (MNT_SYNC_UMOUNT | MNT_DOOMED))) {
755 - mnt_add_count(mnt, -1);
794 + mnt_dec_count(mnt);
756 795 unlock_mount_hash();
757 796 return 1;
758 797 }
@@ -781,20 +820,31 @@ static bool legitimize_mnt(struct vfsmount *bastard, unsigned seq)
781 820 * @dentry: dentry of mountpoint
782 821 *
783 822 * If @mnt has a child mount @c mounted on @dentry find and return it.
823 + * If @mnt is unmounted and a child that was unmounted with it left its
824 + * cover behind at @dentry, return the stand-in for it instead: knullfs
825 + * for a directory, its regular file for anything else.
784 826 * Caller must either hold the spinlock component of @mount_lock or
785 827 * hold rcu_read_lock(), sample the seqcount component before the call
786 828 * and recheck it afterwards.
787 829 *
788 - * Return: The child of @mnt mounted on @dentry or %NULL.
830 + * Return: The child of @mnt mounted on @dentry, a stand-in or %NULL.
789 831 */
790 832 struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry)
791 833 {
792 834 struct hlist_head *head = m_hash(mnt, dentry);
835 + struct mnt_cover *cover;
793 836 struct mount *p;
794 837
795 838 hlist_for_each_entry_rcu(p, head, mnt_hash)
796 839 if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry)
797 840 return p;
841 + /* an unmounted mount keeps the covers its unmounted children left */
842 + /* a lockless caller rechecks mount_lock after a miss, a stale flag is harmless */
843 + if (unlikely(data_race(mnt->mnt_flags) & MNT_UMOUNT)) {
844 + hlist_for_each_entry_rcu(cover, &real_mount(mnt)->mnt_covers, node)
845 + if (cover->dentry == dentry)
846 + return real_mount(d_is_dir(dentry) ? knullfs : knullfs_file);
847 + }
798 848 return NULL;
799 849 }
800 850
@@ -910,6 +960,7 @@ mountpoint:
910 960 mp->m_dentry = dget(dentry);
911 961 hlist_add_head(&mp->m_hash, mp_hash(dentry));
912 962 INIT_HLIST_HEAD(&mp->m_list);
963 + INIT_HLIST_HEAD(&mp->m_covers);
913 964 hlist_add_head(&m->node, &mp->m_list);
914 965 m->mp = no_free_ptr(mp);
915 966 read_sequnlock_excl(&mount_lock);
@@ -922,7 +973,7 @@ mountpoint:
922 973 */
923 974 static void maybe_free_mountpoint(struct mountpoint *mp, struct list_head *list)
924 975 {
925 - if (hlist_empty(&mp->m_list)) {
976 + if (hlist_empty(&mp->m_list) && hlist_empty(&mp->m_covers)) {
926 977 struct dentry *dentry = mp->m_dentry;
927 978 spin_lock(&dentry->d_lock);
928 979 dentry->d_flags &= ~DCACHE_MOUNTED;
@@ -1009,6 +1060,36 @@ static void umount_mnt(struct mount *mnt)
1009 1060 __umount_mnt(mnt, &ex_mountpoints);
1010 1061 }
1011 1062
1063 + /*
1064 + * @mnt is unmounted together with its parent and would have stayed attached
1065 + * to it. Leave its cover behind before it is detached so that a lookup on the
1066 + * parent at the mountpoint keeps finding a mount instead of what @mnt covered.
1067 + *
1068 + * locks: mount_lock[write_seqlock]
1069 + */
1070 + static void leave_cover(struct mount *mnt)
1071 + {
1072 + struct mnt_cover *cover = mnt->mnt_cover;
1073 +
1074 + mnt->mnt_cover = NULL;
1075 + cover->dentry = mnt->mnt_mountpoint;
1076 + cover->mp = mnt->mnt_mp;
1077 + /* keeps the mountpoint once @mnt has let go of it */
1078 + hlist_add_head(&cover->pin, &cover->mp->m_covers);
1079 + hlist_add_head_rcu(&cover->node, &mnt->mnt_parent->mnt_covers);
1080 + }
1081 +
1082 + /*
1083 + * locks: mount_lock[write_seqlock]
1084 + */
1085 + static void drop_cover(struct mnt_cover *cover, struct list_head *shrink_list)
1086 + {
1087 + hlist_del_rcu(&cover->node);
1088 + hlist_del(&cover->pin);
1089 + maybe_free_mountpoint(cover->mp, shrink_list);
1090 + kfree_rcu(cover, rcu);
1091 + }
1092 +
1012 1093 /*
1013 1094 * vfsmount lock must be held for write
1014 1095 */
@@ -1058,7 +1139,10 @@ static void attach_mnt(struct mount *mnt, struct mount *parent,
1058 1139 void mnt_change_mountpoint(struct mount *parent, struct mountpoint *mp, struct mount *mnt)
1059 1140 {
1060 1141 struct mountpoint *old_mp = mnt->mnt_mp;
1142 + struct mount *old_parent = mnt->mnt_parent;
1061 1143
1144 + if (old_parent->overmount == mnt)
1145 + old_parent->overmount = NULL;
1062 1146 list_del_init(&mnt->mnt_child);
1063 1147 hlist_del_init(&mnt->mnt_mp_list);
1064 1148 hlist_del_init_rcu(&mnt->mnt_hash);
@@ -1254,6 +1338,7 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root,
1254 1338
1255 1339 mnt->mnt.mnt_flags = READ_ONCE(old->mnt.mnt_flags) &
1256 1340 ~MNT_INTERNAL_FLAGS;
1341 + mnt->mnt_t_flags = old->mnt_t_flags & T_UNBINDABLE;
1257 1342
1258 1343 if (flag & (CL_SLAVE | CL_PRIVATE))
1259 1344 mnt->mnt_group_id = 0; /* not a peer of original */
@@ -1296,8 +1381,6 @@ static struct mount *clone_mnt(struct mount *old, struct dentry *root,
1296 1381
1297 1382 static void cleanup_mnt(struct mount *mnt)
1298 1383 {
1299 - struct hlist_node *p;
1300 - struct mount *m;
1301 1384 /*
1302 1385 * The warning here probably indicates that somebody messed
1303 1386 * up a mnt_want/drop_write() pair. If this happens, the
@@ -1308,10 +1391,6 @@ static void cleanup_mnt(struct mount *mnt)
1308 1391 WARN_ON(mnt_get_writers(mnt));
1309 1392 if (unlikely(mnt->mnt_pins.first))
1310 1393 mnt_pin_kill(mnt);
1311 - hlist_for_each_entry_safe(m, p, &mnt->mnt_stuck_children, mnt_umount) {
1312 - hlist_del(&m->mnt_umount);
1313 - mntput(&m->mnt);
1314 - }
1315 1394 fsnotify_vfsmount_delete(&mnt->mnt);
1316 1395 dput(mnt->mnt.mnt_root);
1317 1396 deactivate_super(mnt->mnt.mnt_sb);
@@ -1337,17 +1416,14 @@ static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput);
1337 1416
1338 1417 static void noinline mntput_no_expire_slowpath(struct mount *mnt)
1339 1418 {
1419 + struct mnt_cover *cover;
1420 + struct hlist_node *n;
1340 1421 LIST_HEAD(list);
1341 1422 int count;
1342 1423
1343 1424 VFS_BUG_ON(mnt->mnt_ns);
1344 1425 lock_mount_hash();
1345 - /*
1346 - * make sure that if __legitimize_mnt() has not seen us grab
1347 - * mount_lock, we'll see their refcount increment here.
1348 - */
1349 - smp_mb();
1350 - mnt_add_count(mnt, -1);
1426 + mnt_dec_count(mnt);
1351 1427 count = mnt_get_count(mnt);
1352 1428 if (count != 0) {
1353 1429 WARN_ON(count < 0);
@@ -1367,13 +1443,10 @@ static void noinline mntput_no_expire_slowpath(struct mount *mnt)
1367 1443 if (unlikely(!list_empty(&mnt->mnt_expire)))
1368 1444 list_del(&mnt->mnt_expire);
1369 1445
1370 - if (unlikely(!list_empty(&mnt->mnt_mounts))) {
1371 - struct mount *p, *tmp;
1372 - list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
1373 - __umount_mnt(p, &list);
1374 - hlist_add_head(&p->mnt_umount, &mnt->mnt_stuck_children);
1375 - }
1376 - }
1446 + /* nothing stays attached to an unmounted mount */
1447 + VFS_WARN_ON_ONCE(!list_empty(&mnt->mnt_mounts));
1448 + hlist_for_each_entry_safe(cover, n, &mnt->mnt_covers, node)
1449 + drop_cover(cover, &list);
1377 1450 unlock_mount_hash();
1378 1451 shrink_dentry_list(&list);
1379 1452
@@ -1404,7 +1477,8 @@ static void mntput_no_expire(struct mount *mnt)
1404 1477 * non-NULL under rcu_read_lock(), the reference
1405 1478 * we are dropping is not the final one.
1406 1479 */
1407 - mnt_add_count(mnt, -1);
1480 + smp_wmb(); /* pairs with the smp_mb() in mnt_get_count() */
1481 + mnt_dec_count(mnt);
1408 1482 rcu_read_unlock();
1409 1483 return;
1410 1484 }
@@ -1426,7 +1500,7 @@ EXPORT_SYMBOL(mntput);
1426 1500 struct vfsmount *mntget(struct vfsmount *mnt)
1427 1501 {
1428 1502 if (mnt)
1429 - mnt_add_count(real_mount(mnt), 1);
1503 + mnt_inc_count(real_mount(mnt));
1430 1504 return mnt;
1431 1505 }
1432 1506 EXPORT_SYMBOL(mntget);
@@ -1737,36 +1811,17 @@ static inline void namespace_lock(void)
1737 1811 enum umount_tree_flags {
1738 1812 UMOUNT_SYNC = 1,
1739 1813 UMOUNT_PROPAGATE = 2,
1740 - UMOUNT_CONNECTED = 4,
1814 + UMOUNT_COVER = 4,
1741 1815 };
1742 1816
1743 - static bool disconnect_mount(struct mount *mnt, enum umount_tree_flags how)
1817 + /* Do we need to leave the mountpoint on the parent covered? */
1818 + static bool needs_cover(struct mount *mnt, enum umount_tree_flags how)
1744 1819 {
1745 - /* Leaving mounts connected is only valid for lazy umounts */
1746 1820 if (how & UMOUNT_SYNC)
1747 - return true;
1748 -
1749 - /* A mount without a parent has nothing to be connected to */
1750 - if (!mnt_has_parent(mnt))
1751 - return true;
1752 -
1753 - /* Because the reference counting rules change when mounts are
1754 - * unmounted and connected, umounted mounts may not be
1755 - * connected to mounted mounts.
1756 - */
1757 - if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
1758 - return true;
1759 -
1760 - /* Has it been requested that the mount remain connected? */
1761 - if (how & UMOUNT_CONNECTED)
1762 1821 return false;
1763 -
1764 - /* Is the mount locked such that it needs to remain connected? */
1765 - if (IS_MNT_LOCKED(mnt))
1822 + if (!(mnt->mnt_parent->mnt.mnt_flags & MNT_UMOUNT))
1766 1823 return false;
1767 -
1768 - /* By default disconnect the mount */
1769 - return true;
1824 + return (how & UMOUNT_COVER) || IS_MNT_LOCKED(mnt);
1770 1825 }
1771 1826
1772 1827 /*
@@ -1783,6 +1838,8 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
1783 1838
1784 1839 /* Gather the mounts to umount */
1785 1840 for (p = mnt; p; p = next_mnt(p, mnt)) {
1841 + /* A mount is unmounted once. */
1842 + VFS_WARN_ON_ONCE(p->mnt.mnt_flags & MNT_UMOUNT);
1786 1843 p->mnt.mnt_flags |= MNT_UMOUNT;
1787 1844 if (mnt_ns_attached(p))
1788 1845 move_from_ns(p);
@@ -1802,7 +1859,6 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
1802 1859
1803 1860 while (!list_empty(&tmp_list)) {
1804 1861 struct mnt_namespace *ns;
1805 - bool disconnect;
1806 1862 p = list_first_entry(&tmp_list, struct mount, mnt_list);
1807 1863 list_del_init(&p->mnt_expire);
1808 1864 list_del_init(&p->mnt_list);
@@ -1815,17 +1871,12 @@ static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
1815 1871 if (how & UMOUNT_SYNC)
1816 1872 p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
1817 1873
1818 - disconnect = disconnect_mount(p, how);
1819 1874 if (mnt_has_parent(p)) {
1820 - if (!disconnect) {
1821 - /* Don't forget about p */
1822 - list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
1823 - } else {
1824 - umount_mnt(p);
1825 - }
1875 + if (needs_cover(p, how))
1876 + leave_cover(p);
1877 + umount_mnt(p);
1826 1878 }
1827 - if (disconnect)
1828 - hlist_add_head(&p->mnt_umount, &unmounted);
1879 + hlist_add_head(&p->mnt_umount, &unmounted);
1829 1880
1830 1881 /*
1831 1882 * At this point p->mnt_ns is NULL, notification will be queued
@@ -1954,7 +2005,6 @@ static int do_umount(struct mount *mnt, int flags)
1954 2005 umount_tree(mnt, UMOUNT_PROPAGATE);
1955 2006 retval = 0;
1956 2007 } else {
1957 - smp_mb(); // paired with __legitimize_mnt()
1958 2008 shrink_submounts(mnt);
1959 2009 retval = -EBUSY;
1960 2010 if (!propagate_mount_busy(mnt, 2)) {
@@ -1976,11 +2026,16 @@ out:
1976 2026 * detach_mounts allows lazily unmounting those mounts instead of
1977 2027 * leaking them.
1978 2028 *
2029 + * The dentry is unhashed before the mounts go so that no lookup finds
2030 + * what they covered. The caller removes it for good afterwards.
2031 + *
1979 2032 * The caller may hold dentry->d_inode->i_rwsem.
1980 2033 */
1981 2034 void __detach_mounts(struct dentry *dentry)
1982 2035 {
1983 2036 struct pinned_mountpoint mp = {};
2037 + struct mnt_cover *cover;
2038 + struct hlist_node *n;
1984 2039 struct mount *mnt;
1985 2040
1986 2041 guard(namespace_excl)();
@@ -1989,15 +2044,16 @@ void __detach_mounts(struct dentry *dentry)
1989 2044 if (!lookup_mountpoint(dentry, &mp))
1990 2045 return;
1991 2046
2047 + /* the name goes first, what covered it goes second */
2048 + d_drop(dentry);
1992 2049 event++;
1993 2050 while (mp.node.next) {
1994 2051 mnt = hlist_entry(mp.node.next, struct mount, mnt_mp_list);
1995 - if (mnt->mnt.mnt_flags & MNT_UMOUNT) {
1996 - umount_mnt(mnt);
1997 - hlist_add_head(&mnt->mnt_umount, &unmounted);
1998 - }
1999 - else umount_tree(mnt, UMOUNT_CONNECTED);
2052 + umount_tree(mnt, UMOUNT_COVER);
2000 2053 }
2054 + /* the dentry goes away, so do the covers left behind on it */
2055 + hlist_for_each_entry_safe(cover, n, &mp.mp->m_covers, pin)
2056 + drop_cover(cover, &ex_mountpoints);
2001 2057 unpin_mountpoint(&mp);
2002 2058 }
2003 2059
@@ -2196,6 +2252,11 @@ struct mount *copy_tree(struct mount *src_root, struct dentry *dentry,
2196 2252 }
2197 2253 if (!(flag & CL_COPY_MNT_NS_FILE) &&
2198 2254 is_mnt_ns_file(src_mnt->mnt.mnt_root)) {
2255 + if (src_mnt->mnt.mnt_flags & MNT_LOCKED) {
2256 + /* Both a mount namespace file and locked. */
2257 + dst_mnt = ERR_PTR(-EPERM);
2258 + goto out;
2259 + }
2199 2260 src_mnt = skip_mnt_tree(src_mnt);
2200 2261 continue;
2201 2262 }
@@ -2294,9 +2355,11 @@ void drop_collected_paths(const struct path *paths, const struct path *prealloc)
2294 2355
2295 2356 static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *, bool);
2296 2357
2358 + /* Consumes the caller's reference to @mnt. */
2297 2359 void dissolve_on_fput(struct vfsmount *mnt)
2298 2360 {
2299 - struct mount *m = real_mount(mnt);
2361 + struct vfsmount *p __free(mntput) = mnt;
2362 + struct mount *m = real_mount(p);
2300 2363
2301 2364 /*
2302 2365 * m used to be the root of anon namespace; if it still is one,
@@ -2319,13 +2382,14 @@ void dissolve_on_fput(struct vfsmount *mnt)
2319 2382
2320 2383 emptied_ns = m->mnt_ns;
2321 2384 lock_mount_hash();
2322 - umount_tree(m, UMOUNT_CONNECTED);
2385 + umount_tree(m, UMOUNT_COVER);
2323 2386 unlock_mount_hash();
2387 + mntput(no_free_ptr(p));
2324 2388 }
2325 2389 }
2326 2390
2327 2391 /* locks: namespace_shared && pinned(mnt) || mount_locked_reader */
2328 - static bool __has_locked_children(struct mount *mnt, struct dentry *dentry)
2392 + bool has_locked_children(struct mount *mnt, struct dentry *dentry)
2329 2393 {
2330 2394 struct mount *child;
2331 2395
@@ -2339,10 +2403,16 @@ static bool __has_locked_children(struct mount *mnt, struct dentry *dentry)
2339 2403 return false;
2340 2404 }
2341 2405
2342 - bool has_locked_children(struct mount *mnt, struct dentry *dentry)
2406 + /* locks: namespace_shared && pinned(mnt) || mount_locked_reader */
2407 + static bool __has_children(struct mount *mnt, struct dentry *dentry)
2343 2408 {
2344 - guard(mount_locked_reader)();
2345 - return __has_locked_children(mnt, dentry);
2409 + struct mount *child;
2410 +
2411 + list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) {
2412 + if (is_subdir(child->mnt_mountpoint, dentry))
2413 + return true;
2414 + }
2415 + return false;
2346 2416 }
2347 2417
2348 2418 /*
@@ -2401,7 +2471,7 @@ struct vfsmount *clone_private_mount(const struct path *path)
2401 2471 if (!ns_capable(old_mnt->mnt_ns->user_ns, CAP_SYS_ADMIN))
2402 2472 return ERR_PTR(-EPERM);
2403 2473
2404 - if (__has_locked_children(old_mnt, path->dentry))
2474 + if (has_locked_children(old_mnt, path->dentry))
2405 2475 return ERR_PTR(-EINVAL);
2406 2476
2407 2477 new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE);
@@ -2564,11 +2634,11 @@ enum mnt_tree_flags_t {
2564 2634 static int attach_recursive_mnt(struct mount *source_mnt,
2565 2635 const struct pinned_mountpoint *dest)
2566 2636 {
2567 - struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns;
2568 2637 struct mount *dest_mnt = dest->parent;
2569 2638 struct mountpoint *dest_mp = dest->mp;
2570 2639 HLIST_HEAD(tree_list);
2571 2640 struct mnt_namespace *ns = dest_mnt->mnt_ns;
2641 + struct user_namespace *user_ns = ns->user_ns;
2572 2642 struct pinned_mountpoint root = {};
2573 2643 struct mountpoint *shorter = NULL;
2574 2644 struct mount *child, *p;
@@ -2577,13 +2647,31 @@ static int attach_recursive_mnt(struct mount *source_mnt,
2577 2647 int err = 0;
2578 2648 bool moving = mnt_has_parent(source_mnt);
2579 2649
2650 + /*
2651 + * A caller in an unprivileged mount namespaces may trigger an
2652 + * automount and propagate locked mounts into privileged mount
2653 + * namespaces. Take ownership from the target mount namespace.
2654 + * It's equivalent for everything but the automount case.
2655 + *
2656 + * Detached trees in anonymous mount namespaces by be handed
2657 + * over via SCM_RIGHTS or inherited in other ways on purpose
2658 + * the attaching task's mount namespace is authoritative, not
2659 + * the creator of the detached tree.
2660 + */
2661 + if (is_anon_ns(ns))
2662 + user_ns = current->nsproxy->mnt_ns->user_ns;
2663 + else
2664 + user_ns = ns->user_ns;
2665 +
2580 2666 /*
2581 2667 * Preallocate a mountpoint in case the new mounts need to be
2582 2668 * mounted beneath mounts on the same mountpoint.
2583 2669 */
2584 - for (top = source_mnt; unlikely(top->overmount); top = top->overmount) {
2670 + for (top = source_mnt; ; top = top->overmount) {
2585 2671 if (!shorter && is_mnt_ns_file(top->mnt.mnt_root))
2586 2672 shorter = top->mnt_mp;
2673 + if (likely(!top->overmount))
2674 + break;
2587 2675 }
2588 2676 err = get_mountpoint(top->mnt.mnt_root, &root);
2589 2677 if (err)
@@ -2654,15 +2742,17 @@ static int attach_recursive_mnt(struct mount *source_mnt,
2654 2742 /*
2655 2743 * If @q was locked it was meant to hide
2656 2744 * whatever was under it. Let @child take over
2657 - * that job and lock it, then we can unlock @q.
2658 - * That'll allow another namespace to shed @q
2659 - * and reveal @child. Clearly, that mounter
2660 - * consented to this by not severing the mount
2661 - * relationship. Otherwise, what's the point.
2745 + * that job and lock it. If @child is the mount
2746 + * the caller placed we can then unlock @q:
2747 + * nothing another namespace does removes it
2748 + * again. A propagated copy goes away when the
2749 + * mounter of the original unmounts it, so @q
2750 + * keeps its lock.
2662 2751 */
2663 2752 if (IS_MNT_LOCKED(q)) {
2664 2753 child->mnt.mnt_flags |= MNT_LOCKED;
2665 - q->mnt.mnt_flags &= ~MNT_LOCKED;
2754 + if (child == source_mnt)
2755 + q->mnt.mnt_flags &= ~MNT_LOCKED;
2666 2756 }
2667 2757 mnt_change_mountpoint(r, mp, q);
2668 2758 }
@@ -2759,6 +2849,11 @@ static void do_lock_mount(const struct path *path,
2759 2849
2760 2850 scoped_guard(mount_locked_reader) {
2761 2851 m = where_to_mount(path, &dentry, beneath);
2852 + /* sticky, so it takes no locks to refuse it */
2853 + if (unlikely(cant_mount(dentry))) {
2854 + res->parent = ERR_PTR(-ENOENT);
2855 + return;
2856 + }
2762 2857 if (&m->mnt != path->mnt) {
2763 2858 mntget(&m->mnt);
2764 2859 dget(dentry);
@@ -2989,7 +3084,14 @@ static struct mount *__do_loopback(const struct path *old_path,
2989 3084 if (!may_copy_tree(old_path))
2990 3085 return ERR_PTR(-EINVAL);
2991 3086
2992 - if (!recurse && __has_locked_children(old, old_path->dentry))
3087 + /* a pseudo dentry is freed without an RCU delay, no walk may find it */
3088 + if (old_path->dentry->d_flags & DCACHE_NORCU)
3089 + return ERR_PTR(-EINVAL);
3090 +
3091 + if (recurse && !old->mnt_ns)
3092 + return ERR_PTR(-EINVAL);
3093 +
3094 + if (!recurse && has_locked_children(old, old_path->dentry))
2993 3095 return ERR_PTR(-EINVAL);
2994 3096
2995 3097 if (recurse)
@@ -3028,7 +3130,11 @@ static int do_loopback(const struct path *path, const char *old_name,
3028 3130 if (IS_ERR(mnt))
3029 3131 return PTR_ERR(mnt);
3030 3132
3031 - err = graft_tree(mnt, &mp);
3133 + /* the copy may carry mount namespace files from below the source */
3134 + if (recurse && !check_for_nsfs_mounts(mnt))
3135 + err = -EINVAL;
3136 + else
3137 + err = graft_tree(mnt, &mp);
3032 3138 if (err) {
3033 3139 lock_mount_hash();
3034 3140 umount_tree(mnt, UMOUNT_SYNC);
@@ -3088,7 +3194,7 @@ static struct file *open_detached_copy(struct path *path, unsigned int flags)
3088 3194 path->mnt = mntget(&ns->root->mnt);
3089 3195 file = dentry_open(path, O_PATH, current_cred());
3090 3196 if (IS_ERR(file))
3091 - dissolve_on_fput(path->mnt);
3197 + dissolve_on_fput(no_free_ptr(path->mnt));
3092 3198 else
3093 3199 file->f_mode |= FMODE_NEED_UNMOUNT;
3094 3200 return file;
@@ -3110,12 +3216,18 @@ static struct mnt_namespace *create_new_namespace(struct path *path,
3110 3216 struct mount *mnt;
3111 3217 unsigned int copy_flags = 0;
3112 3218 bool locked = false, recurse = flags & MOUNT_COPY_RECURSIVE;
3219 + bool foreign = user_ns != ns->user_ns;
3113 3220
3114 3221 if (unlikely(!d_can_lookup(path->dentry)))
3115 3222 return ERR_PTR(-ENOTDIR);
3116 3223
3117 - if (user_ns != ns->user_ns)
3118 - copy_flags |= CL_SLAVE;
3224 + /*
3225 + * Without privileges over the mount namespace the copy is made from
3226 + * nothing mounted below @path may be left out. It would reveal what
3227 + * it covers. That's what unshare() gives such a caller as well.
3228 + */
3229 + if (foreign)
3230 + copy_flags |= CL_SLAVE | CL_COPY_UNBINDABLE;
3119 3231
3120 3232 new_ns = alloc_mnt_ns(user_ns, false);
3121 3233 if (IS_ERR(new_ns))
@@ -3149,10 +3261,14 @@ static struct mnt_namespace *create_new_namespace(struct path *path,
3149 3261 /*
3150 3262 * We don't emulate unshare()ing a mount namespace. We stick to
3151 3263 * the restrictions of creating detached bind-mounts. It has a
3152 - * lot saner and simpler semantics.
3264 + * lot saner and simpler semantics. A caller without privileges
3265 + * over the mount namespace can't leave out any child though.
3153 3266 */
3154 3267 if (flags & MOUNT_COPY_NEW)
3155 3268 mnt = clone_mnt(real_mount(path->mnt), path->dentry, copy_flags);
3269 + else if (foreign && !recurse &&
3270 + __has_children(real_mount(path->mnt), path->dentry))
3271 + mnt = ERR_PTR(-EINVAL);
3156 3272 else
3157 3273 mnt = __do_loopback(path, recurse, copy_flags);
3158 3274 scoped_guard(mount_writer) {
@@ -3169,7 +3285,7 @@ static struct mnt_namespace *create_new_namespace(struct path *path,
3169 3285 * of the real rootfs we created.
3170 3286 */
3171 3287 attach_mnt(mnt, new_ns_root, mp.mp);
3172 - if (user_ns != ns->user_ns)
3288 + if (foreign)
3173 3289 lock_mnt_tree(new_ns_root);
3174 3290 }
3175 3291
@@ -3463,11 +3579,11 @@ static int do_set_group(const struct path *from_path, const struct path *to_path
3463 3579 return -EINVAL;
3464 3580
3465 3581 /* From mount should not have locked children in place of To's root */
3466 - if (__has_locked_children(from, to->mnt.mnt_root))
3582 + if (has_locked_children(from, to->mnt.mnt_root))
3467 3583 return -EINVAL;
3468 3584
3469 3585 /* Setting sharing groups is only allowed on private mounts */
3470 - if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to))
3586 + if (IS_MNT_SHARED(to) || IS_MNT_SLAVE(to) || IS_MNT_UNBINDABLE(to))
3471 3587 return -EINVAL;
3472 3588
3473 3589 /* From should not be private */
@@ -3536,8 +3652,9 @@ static bool mount_is_ancestor(const struct mount *p1, const struct mount *p2)
3536 3652 * @mnt_to: mount under which to mount
3537 3653 * @mp: mountpoint of @mnt_to
3538 3654 *
3539 - * - Make sure that the caller can unmount the topmost mount ensuring
3540 - * that the caller could reveal the underlying mountpoint.
3655 + * - Make sure that @mnt_from can take over the lock of @mnt_to. A
3656 + * mount of a mount namespace file is left out of a copy of the tree
3657 + * and can't.
3541 3658 * - Ensure that nothing has been mounted on top of @mnt_from before we
3542 3659 * grabbed @namespace_sem to avoid creating pointless shadow mounts.
3543 3660 * - Prevent mounting beneath a mount if the propagation relationship
@@ -3553,6 +3670,15 @@ static int can_move_mount_beneath(const struct mount *mnt_from,
3553 3670 {
3554 3671 struct mount *parent_mnt_to = mnt_to->mnt_parent;
3555 3672
3673 + /*
3674 + * @mnt_from takes over the lock of @mnt_to. copy_tree() leaves a
3675 + * mount of a mount namespace file out of every copy made without
3676 + * CL_COPY_MNT_NS_FILE, together with what is mounted on it, so it
3677 + * can't keep anything hidden.
3678 + */
3679 + if (IS_MNT_LOCKED(mnt_to) && is_mnt_ns_file(mnt_from->mnt.mnt_root))
3680 + return -EINVAL;
3681 +
3556 3682 /* Avoid creating shadow mounts during mount propagation. */
3557 3683 if (mnt_from->overmount)
3558 3684 return -EINVAL;
@@ -3743,7 +3869,7 @@ static int do_add_mount(struct mount *newmnt, const struct pinned_mountpoint *mp
3743 3869 if (!(mnt_flags & MNT_SHRINKABLE))
3744 3870 return -EINVAL;
3745 3871 /* ... and for those we'd better have mountpoint still alive */
3746 - if (!parent->mnt_ns)
3872 + if (!is_mounted(&parent->mnt))
3747 3873 return -EINVAL;
3748 3874 }
3749 3875
@@ -3953,6 +4079,8 @@ void mark_mounts_for_expiry(struct list_head *mounts)
3953 4079 list_for_each_entry_safe(mnt, next, mounts, mnt_expire) {
3954 4080 if (!is_mounted(&mnt->mnt))
3955 4081 continue;
4082 + /* lock_mnt_tree() leaves expirable mounts alone */
4083 + VFS_WARN_ON_ONCE(IS_MNT_LOCKED(mnt));
3956 4084 if (!xchg(&mnt->mnt_expiry_mark, 1) ||
3957 4085 propagate_mount_busy(mnt, 1))
3958 4086 continue;
@@ -3960,6 +4088,11 @@ void mark_mounts_for_expiry(struct list_head *mounts)
3960 4088 }
3961 4089 while (!list_empty(&graveyard)) {
3962 4090 mnt = list_first_entry(&graveyard, struct mount, mnt_expire);
4091 + /* an earlier umount_tree() may have moved a busy mount here */
4092 + if (propagate_mount_busy(mnt, 1)) {
4093 + list_move(&mnt->mnt_expire, mounts);
4094 + continue;
4095 + }
3963 4096 touch_mnt_namespace(mnt->mnt_ns);
3964 4097 umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
3965 4098 }
@@ -3967,17 +4100,38 @@ void mark_mounts_for_expiry(struct list_head *mounts)
3967 4100
3968 4101 EXPORT_SYMBOL_GPL(mark_mounts_for_expiry);
3969 4102
4103 + /*
4104 + * Unmount @mnt if it's a shrinkable mount without children that nobody uses.
4105 + *
4106 + * mount_lock must be held for write
4107 + */
4108 + static bool shrink_submount(struct mount *mnt)
4109 + {
4110 + /* not the kernel's to remove either */
4111 + if (IS_MNT_LOCKED(mnt) || propagate_mount_busy(mnt, 1))
4112 + return false;
4113 + touch_mnt_namespace(mnt->mnt_ns);
4114 + umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC);
4115 + return true;
4116 + }
4117 +
3970 4118 /*
3971 4119 * Ripoff of 'select_parent()'
3972 4120 *
3973 - * search the list of submounts for a given mountpoint, and move any
3974 - * shrinkable submounts to the 'graveyard' list.
4121 + * unmount the shrinkable submounts of @parent that aren't busy, children
4122 + * before their parent, and say whether anything went
4123 + *
4124 + * The cursor into the children of @this_parent survives the umount of a
4125 + * child mount without child mounts. The mounts that get umounted together with
4126 + * it are located under receiving mounts of @this_parent and never under
4127 + * @this_parent itself. The one exception is @this_parent getting unmounted
4128 + * then the walk starts over.
3975 4129 */
3976 - static int select_submounts(struct mount *parent, struct list_head *graveyard)
4130 + static bool __shrink_submounts(struct mount *parent)
3977 4131 {
3978 4132 struct mount *this_parent = parent;
3979 4133 struct list_head *next;
3980 - int found = 0;
4134 + bool shrunk = false;
3981 4135
3982 4136 repeat:
3983 4137 next = this_parent->mnt_mounts.next;
@@ -3996,42 +4150,45 @@ resume:
3996 4150 this_parent = mnt;
3997 4151 goto repeat;
3998 4152 }
3999 -
4000 - if (!propagate_mount_busy(mnt, 1)) {
4001 - list_move_tail(&mnt->mnt_expire, graveyard);
4002 - found++;
4003 - }
4153 + if (!shrink_submount(mnt))
4154 + continue;
4155 + shrunk = true;
4156 + if (unlikely(this_parent->mnt.mnt_flags & MNT_UMOUNT))
4157 + return true;
4004 4158 }
4005 4159 /*
4006 4160 * All done at this level ... ascend and resume the search
4007 4161 */
4008 4162 if (this_parent != parent) {
4009 - next = this_parent->mnt_child.next;
4010 - this_parent = this_parent->mnt_parent;
4163 + struct mount *mnt = this_parent;
4164 +
4165 + next = mnt->mnt_child.next;
4166 + this_parent = mnt->mnt_parent;
4167 + /* its children are gone, maybe it can go as well */
4168 + if (shrink_submount(mnt)) {
4169 + shrunk = true;
4170 + if (unlikely(this_parent->mnt.mnt_flags & MNT_UMOUNT))
4171 + return true;
4172 + }
4011 4173 goto resume;
4012 4174 }
4013 - return found;
4175 + return shrunk;
4014 4176 }
4015 4177
4016 4178 /*
4017 - * process a list of expirable mountpoints with the intent of discarding any
4018 - * submounts of a specific parent mountpoint
4179 + * unmount the shrinkable submounts of @mnt that aren't busy
4180 + *
4181 + * The busy check and the umount of a mount are adjacent. An umount can
4182 + * still empty or move a mount in a part of the tree that was walked
4183 + * already, so walk again until nothing goes.
4019 4184 *
4020 4185 * mount_lock must be held for write
4021 4186 */
4022 4187 static void shrink_submounts(struct mount *mnt)
4023 4188 {
4024 - LIST_HEAD(graveyard);
4025 - struct mount *m;
4026 -
4027 - /* extract submounts of 'mountpoint' from the expiration list */
4028 - while (select_submounts(mnt, &graveyard)) {
4029 - while (!list_empty(&graveyard)) {
4030 - m = list_first_entry(&graveyard, struct mount,
4031 - mnt_expire);
4032 - touch_mnt_namespace(m->mnt_ns);
4033 - umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC);
4034 - }
4189 + for (;;) {
4190 + if (!__shrink_submounts(mnt))
4191 + break;
4035 4192 }
4036 4193 }
4037 4194
@@ -4196,6 +4353,8 @@ static void free_mnt_ns(struct mnt_namespace *ns)
4196 4353 if (!is_anon_ns(ns))
4197 4354 ns_common_free(ns);
4198 4355 dec_mnt_namespaces(ns->ucounts);
4356 + /* the last active reference is gone, no mark can show up anymore */
4357 + fsnotify_mntns_delete(ns);
4199 4358 mnt_ns_tree_remove(ns);
4200 4359 }
4201 4360
@@ -4545,7 +4704,7 @@ SYSCALL_DEFINE3(fsmount, int, fs_fd, unsigned int, flags,
4545 4704 FD_PREPARE(fdf, (flags & FSMOUNT_CLOEXEC) ? O_CLOEXEC : 0,
4546 4705 dentry_open(&new_path, O_PATH, fc->cred));
4547 4706 if (fdf.err) {
4548 - dissolve_on_fput(new_path.mnt);
4707 + dissolve_on_fput(no_free_ptr(new_path.mnt));
4549 4708 return fdf.err;
4550 4709 }
4551 4710
@@ -4697,14 +4856,15 @@ int path_pivot_root(struct path *new, struct path *old)
4697 4856
4698 4857 new_mnt = real_mount(new->mnt);
4699 4858 root_mnt = real_mount(root.mnt);
4859 + /* only a mounted mount has a parent that namespace_sem pins */
4860 + if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
4861 + return -EINVAL;
4700 4862 ex_parent = new_mnt->mnt_parent;
4701 4863 root_parent = root_mnt->mnt_parent;
4702 4864 if (IS_MNT_SHARED(old_mnt) ||
4703 4865 IS_MNT_SHARED(ex_parent) ||
4704 4866 IS_MNT_SHARED(root_parent))
4705 4867 return -EINVAL;
4706 - if (!check_mnt(root_mnt) || !check_mnt(new_mnt))
4707 - return -EINVAL;
4708 4868 if (new_mnt->mnt.mnt_flags & MNT_LOCKED)
4709 4869 return -EINVAL;
4710 4870 if (d_unlinked(new->dentry))
@@ -4955,6 +5115,11 @@ static int do_mount_setattr(const struct path *path, struct mount_kattr *kattr)
4955 5115 * propagation.
4956 5116 */
4957 5117 namespace_lock();
5118 + /* invent_group_ids() walks the tree, only walk a mounted one */
5119 + if (!anon_ns_root(mnt) && !check_mnt(mnt)) {
5120 + namespace_unlock();
5121 + return -EINVAL;
5122 + }
4958 5123 if (kattr->propagation == MS_SHARED) {
4959 5124 err = invent_group_ids(mnt, kattr->kflags & MOUNT_KATTR_RECURSE);
4960 5125 if (err) {
@@ -4967,6 +5132,7 @@ static int do_mount_setattr(const struct path *path, struct mount_kattr *kattr)
4967 5132 err = -EINVAL;
4968 5133 lock_mount_hash();
4969 5134
5135 + /* Checked under namespace_sem already if the propagation changes. */
4970 5136 if (!anon_ns_root(mnt) && !check_mnt(mnt))
4971 5137 goto out;
4972 5138
@@ -5319,15 +5485,25 @@ static void statmount_sb_basic(struct kstatmount *s)
5319 5485 s->sm.sb_flags = sb->s_flags & (SB_RDONLY|SB_SYNCHRONOUS|SB_DIRSYNC|SB_LAZYTIME);
5320 5486 }
5321 5487
5488 + static void statmount_mnt_parent(struct kstatmount *s, const struct mount *m)
5489 + {
5490 + s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique;
5491 + s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id;
5492 + }
5493 +
5322 5494 static void statmount_mnt_basic(struct kstatmount *s)
5323 5495 {
5324 5496 struct mount *m = real_mount(s->mnt);
5325 5497
5326 5498 s->sm.mask |= STATMOUNT_MNT_BASIC;
5327 5499 s->sm.mnt_id = m->mnt_id_unique;
5328 - s->sm.mnt_parent_id = m->mnt_parent->mnt_id_unique;
5329 5500 s->sm.mnt_id_old = m->mnt_id;
5330 - s->sm.mnt_parent_id_old = m->mnt_parent->mnt_id;
5501 + /* An unmounted mount is cut loose from its parent under mount_lock alone. */
5502 + if (likely(is_mounted(s->mnt)))
5503 + statmount_mnt_parent(s, m);
5504 + else
5505 + scoped_guard(mount_locked_reader)
5506 + statmount_mnt_parent(s, m);
5331 5507 s->sm.mnt_attr = mnt_to_attr_flags(&m->mnt);
5332 5508 s->sm.mnt_propagation = mnt_to_propagation_flags(m);
5333 5509 s->sm.mnt_peer_group = m->mnt_group_id;
@@ -6199,6 +6375,25 @@ static void __init mount_rootfs_on_nullfs(struct vfsmount *mnt,
6199 6375 attach_mnt(real_mount(mnt), mp.parent, mp.mp);
6200 6376 }
6201 6377
6378 + static struct vfsmount *__init knullfs_file_mount(void)
6379 + {
6380 + struct dentry *file;
6381 + struct mount *mnt;
6382 +
6383 + file = nullfs_new_file(knullfs->mnt_sb);
6384 + if (IS_ERR(file))
6385 + return ERR_CAST(file);
6386 + mnt = clone_mnt(real_mount(knullfs), file, CL_PRIVATE);
6387 + dput(file);
6388 + if (IS_ERR(mnt))
6389 + return ERR_CAST(mnt);
6390 + mnt->mnt_ns = MNT_NS_INTERNAL;
6391 + mnt->mnt.mnt_flags |= MNT_INTERNAL;
6392 + mnt->mnt.mnt_flags &= ~MNT_READONLY;
6393 + dont_mount(mnt->mnt.mnt_root);
6394 + return &mnt->mnt;
6395 + }
6396 +
6202 6397 static void __init init_mount_tree(void)
6203 6398 {
6204 6399 struct vfsmount *mnt, *nullfs_mnt;
@@ -6210,10 +6405,14 @@ static void __init init_mount_tree(void)
6210 6405 *
6211 6406 * (1) nullfs with mount id 1
6212 6407 * (2) mutable rootfs with mount id 2
6213 - * (3) private nullfs for kthreads (SB_KERNMOUNT)
6408 + * (3) private nullfs for kthreads (SB_KERNMOUNT), kept in knullfs
6409 + * (4) a second mount of (3) rooted on a regular file, kept in
6410 + * knullfs_file
6214 6411 *
6215 6412 * with (2) mounted on top of (1). The init_task's root and pwd
6216 6413 * are pointed at (3) so all kthreads start isolated in nullfs.
6414 + * A lookup at the cover an unmounted mount left behind finds (3)
6415 + * or (4), see __lookup_mnt().
6217 6416 */
6218 6417 nullfs_mnt = vfs_kern_mount(&nullfs_fs_type, 0, "nullfs", NULL);
6219 6418 if (IS_ERR(nullfs_mnt))
@@ -6245,11 +6444,18 @@ static void __init init_mount_tree(void)
6245 6444 init_mnt_ns.nr_mounts++;
6246 6445 }
6247 6446
6248 - nullfs_mnt = kern_mount(&nullfs_fs_type);
6249 - if (IS_ERR(nullfs_mnt))
6447 + knullfs = kern_mount(&nullfs_fs_type);
6448 + if (IS_ERR(knullfs))
6250 6449 panic("VFS: Failed to create private nullfs instance");
6251 - root.mnt = nullfs_mnt;
6252 - root.dentry = nullfs_mnt->mnt_root;
6450 + /* nothing is ever mounted on the root of a kernel thread */
6451 + dont_mount(knullfs->mnt_root);
6452 + /* and nothing is ever written through it */
6453 + knullfs->mnt_flags |= MNT_READONLY;
6454 + knullfs_file = knullfs_file_mount();
6455 + if (IS_ERR(knullfs_file))
6456 + panic("VFS: Failed to create the nullfs file stand-in");
6457 + root.mnt = knullfs;
6458 + root.dentry = knullfs->mnt_root;
6253 6459
6254 6460 init_task.nsproxy->mnt_ns = &init_mnt_ns;
6255 6461 get_mnt_ns(&init_mnt_ns);
modified fs/notify/mark.c
@@ -903,6 +903,10 @@ static int fsnotify_add_mark_list(struct fsnotify_mark *mark, void *obj,
903 903 if (WARN_ON(!fsnotify_valid_obj_type(obj_type)))
904 904 return -EINVAL;
905 905
906 + /* the filesystem doesn't want its objects watched */
907 + if (sb && (sb->s_type->fs_flags & FS_DISALLOW_NOTIFY))
908 + return -EINVAL;
909 +
906 910 /*
907 911 * Attach the sb info before attaching a connector to any object on sb.
908 912 * The sb info will remain attached as long as sb lives.
@@ -925,6 +929,11 @@ restart:
925 929 goto restart;
926 930 }
927 931
932 + if (conn->flags & FSNOTIFY_CONN_FLAG_DESTROYING) {
933 + err = -ENOENT;
934 + goto out_err;
935 + }
936 +
928 937 /* is mark the first mark? */
929 938 if (hlist_empty(&conn->list)) {
930 939 hlist_add_head_rcu(&mark->obj_list, &conn->list);
@@ -1112,6 +1121,12 @@ void fsnotify_destroy_marks(fsnotify_connp_t *connp)
1112 1121 conn = fsnotify_grab_connector(connp);
1113 1122 if (!conn)
1114 1123 return;
1124 + /*
1125 + * New marks could be inserted before our cursor and survive the final
1126 + * detachment of the connector from the object. Prevent additions to
1127 + * this connector before dropping its lock.
1128 + */
1129 + conn->flags |= FSNOTIFY_CONN_FLAG_DESTROYING;
1115 1130 /*
1116 1131 * We have to be careful since we can race with e.g.
1117 1132 * fsnotify_clear_marks_by_group() and once we drop the conn->lock, the
modified fs/ntfs3/dir.c
@@ -186,11 +186,20 @@ int ntfs_nls_to_utf16(struct ntfs_sb_info *sbi, const u8 *name, u32 name_len,
186 186 {
187 187 int ret, slen, i;
188 188 const u8 *end;
189 - struct nls_table *nls = sbi->options->nls;
189 + struct ntfs_mount_options *opts;
190 + struct nls_table *nls;
191 + bool ads;
190 192 u16 *uname = uni->name;
191 193
192 194 static_assert(sizeof(wchar_t) == sizeof(u16));
193 195
196 + /* ntfs_fs_reconfigure() may replace the options, but not ->nls */
197 + rcu_read_lock();
198 + opts = READ_ONCE(sbi->options);
199 + nls = opts->nls;
200 + ads = opts->ads;
201 + rcu_read_unlock();
202 +
194 203 if (!nls) {
195 204 /* utf8 -> utf16 */
196 205 ret = _utf8s_to_utf16s(name, name_len, endian, uname, max_ulen);
@@ -230,7 +239,7 @@ int ntfs_nls_to_utf16(struct ntfs_sb_info *sbi, const u8 *name, u32 name_len,
230 239
231 240 uni->len = ret;
232 241 uni->ads_len = 0;
233 - if (ret > 0 && sbi->options->ads) {
242 + if (ret > 0 && ads) {
234 243 uname = uni->name;
235 244 /* Find delimiter in range [1 : ret-2). */
236 245 for (i = 1; i + 1 < ret; i++) {
modified fs/ntfs3/ntfs_fs.h
@@ -91,6 +91,8 @@ enum utf16_endian;
91 91 struct ntfs_mount_options {
92 92 char *nls_name;
93 93 struct nls_table *nls;
94 + /* ->d_hash() and ->d_compare() read the options in rcu pathwalk */
95 + struct rcu_head rcu;
94 96
95 97 kuid_t fs_uid;
96 98 kgid_t fs_gid;
@@ -211,6 +213,7 @@ struct ntfs_index {
211 213 /* Ntfs file system in-core superblock data. */
212 214 struct ntfs_sb_info {
213 215 struct super_block *sb;
216 + struct rcu_head rcu;
214 217
215 218 u32 discard_granularity;
216 219 u64 discard_granularity_mask_inv; // ~(discard_granularity_mask_inv-1)
modified fs/ntfs3/super.c
@@ -196,7 +196,7 @@ void *ntfs_set_shared(void *ptr, u32 bytes)
196 196 void *ret = NULL;
197 197 int i, j = -1;
198 198
199 - spin_lock(&s_shared_lock);
199 + spin_lock_bh(&s_shared_lock);
200 200 for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
201 201 if (!s_shared[i].cnt) {
202 202 j = i;
@@ -214,7 +214,7 @@ void *ntfs_set_shared(void *ptr, u32 bytes)
214 214 s_shared[j].cnt = 1;
215 215 ret = ptr;
216 216 }
217 - spin_unlock(&s_shared_lock);
217 + spin_unlock_bh(&s_shared_lock);
218 218
219 219 return ret;
220 220 }
@@ -231,7 +231,7 @@ void *ntfs_put_shared(void *ptr)
231 231 void *ret = ptr;
232 232 int i;
233 233
234 - spin_lock(&s_shared_lock);
234 + spin_lock_bh(&s_shared_lock);
235 235 for (i = 0; i < ARRAY_SIZE(s_shared); i++) {
236 236 if (s_shared[i].cnt && s_shared[i].ptr == ptr) {
237 237 if (--s_shared[i].cnt)
@@ -239,7 +239,7 @@ void *ntfs_put_shared(void *ptr)
239 239 break;
240 240 }
241 241 }
242 - spin_unlock(&s_shared_lock);
242 + spin_unlock_bh(&s_shared_lock);
243 243
244 244 return ret;
245 245 }
@@ -251,6 +251,11 @@ static inline void put_mount_options(struct ntfs_mount_options *options)
251 251 kfree(options);
252 252 }
253 253
254 + static void put_mount_options_rcu(struct rcu_head *head)
255 + {
256 + put_mount_options(container_of(head, struct ntfs_mount_options, rcu));
257 + }
258 +
254 259 enum Opt {
255 260 Opt_uid,
256 261 Opt_gid,
@@ -444,6 +449,7 @@ static int ntfs_fs_reconfigure(struct fs_context *fc)
444 449 struct super_block *sb = fc->root->d_sb;
445 450 struct ntfs_sb_info *sbi = sb->s_fs_info;
446 451 struct ntfs_mount_options *new_opts = fc->fs_private;
452 + struct ntfs_mount_options *old_opts;
447 453 int ro_rw;
448 454
449 455 ro_rw = sb_rdonly(sb) && !(fc->sb_flags & SB_RDONLY);
@@ -473,7 +479,15 @@ static int ntfs_fs_reconfigure(struct fs_context *fc)
473 479 }
474 480
475 481 sync_filesystem(sb);
476 - swap(sbi->options, fc->fs_private);
482 + old_opts = sbi->options;
483 + /* pairs with the READ_ONCE() in ntfs_nls_to_utf16() */
484 + smp_store_release(&sbi->options, new_opts);
485 + fc->fs_private = NULL;
486 + /*
487 + * ntfs_d_hash() and ntfs_d_compare() of a pathwalk in rcu mode may
488 + * still read the old options through the sbi.
489 + */
490 + call_rcu(&old_opts->rcu, put_mount_options_rcu);
477 491
478 492 return 0;
479 493 }
@@ -708,6 +722,8 @@ static noinline void ntfs3_put_sbi(struct ntfs_sb_info *sbi)
708 722
709 723 static void ntfs3_free_sbi(struct ntfs_sb_info *sbi)
710 724 {
725 + if (sbi->options)
726 + put_mount_options(sbi->options);
711 727 kfree(sbi->new_rec);
712 728 kvfree(ntfs_put_shared(sbi->upcase));
713 729 kvfree(sbi->def_table);
@@ -719,6 +735,11 @@ static void ntfs3_free_sbi(struct ntfs_sb_info *sbi)
719 735 kfree(sbi);
720 736 }
721 737
738 + static void ntfs3_free_sbi_rcu(struct rcu_head *head)
739 + {
740 + ntfs3_free_sbi(container_of(head, struct ntfs_sb_info, rcu));
741 + }
742 +
722 743 static void ntfs_put_super(struct super_block *sb)
723 744 {
724 745 struct ntfs_sb_info *sbi = sb->s_fs_info;
@@ -728,11 +749,11 @@ static void ntfs_put_super(struct super_block *sb)
728 749 /* Mark rw ntfs as clear, if possible. */
729 750 ntfs_set_state(sbi, NTFS_DIRTY_CLEAR);
730 751
731 - if (sbi->options) {
732 - put_mount_options(sbi->options);
733 - sbi->options = NULL;
734 - }
735 -
752 + /*
753 + * The mount options stay until the sbi is freed: ->d_hash() and
754 + * ->d_compare() of a pathwalk in rcu mode read the nls table through
755 + * them.
756 + */
736 757 ntfs3_put_sbi(sbi);
737 758 }
738 759
@@ -1939,9 +1960,11 @@ static void ntfs3_kill_sb(struct super_block *sb)
1939 1960
1940 1961 kill_block_super(sb);
1941 1962
1942 - if (sbi->options)
1943 - put_mount_options(sbi->options);
1944 - ntfs3_free_sbi(sbi);
1963 + /*
1964 + * A pathwalk in rcu mode may still be in ->d_hash() or ->d_compare()
1965 + * and read the upcase table and the nls table through the sbi.
1966 + */
1967 + call_rcu(&sbi->rcu, ntfs3_free_sbi_rcu);
1945 1968 }
1946 1969
1947 1970 // clang-format off
modified fs/nullfs.c
@@ -3,6 +3,8 @@
3 3 #include <linux/fs/super_types.h>
4 4 #include <linux/fs_context.h>
5 5 #include <linux/magic.h>
6 + #include <linux/splice.h>
7 + #include <linux/uio.h>
6 8
7 9 #include "mount.h"
8 10
@@ -10,6 +12,121 @@ static const struct super_operations nullfs_super_operations = {
10 12 .statfs = simple_statfs,
11 13 };
12 14
15 + static loff_t nullfs_dir_llseek(struct file *file, loff_t offset, int whence)
16 + {
17 + /* an empty directory has two entries . and .. at offsets 0 and 1 */
18 + return generic_file_llseek_size(file, offset, whence, 2, 2);
19 + }
20 +
21 + static int nullfs_dir_readdir(struct file *file, struct dir_context *ctx)
22 + {
23 + dir_emit_dots(file, ctx);
24 + return 0;
25 + }
26 +
27 + /* the one inode of nullfs is shared by every holder, so no locks on it */
28 + static int nullfs_nolock(struct file *file, int cmd, struct file_lock *fl)
29 + {
30 + return -ENOLCK;
31 + }
32 +
33 + /* what libfs gives an empty directory, plus the refusal of file locks */
34 + static const struct file_operations nullfs_dir_operations = {
35 + .llseek = nullfs_dir_llseek,
36 + .read = generic_read_dir,
37 + .iterate_shared = nullfs_dir_readdir,
38 + .fsync = noop_fsync,
39 + .lock = nullfs_nolock,
40 + .flock = nullfs_nolock,
41 + .fop_flags = FOP_IMMUTABLE,
42 + };
43 +
44 + static ssize_t nullfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
45 + {
46 + return 0;
47 + }
48 +
49 + static ssize_t nullfs_file_splice_read(struct file *in, loff_t *ppos,
50 + struct pipe_inode_info *pipe,
51 + size_t len, unsigned int flags)
52 + {
53 + return 0;
54 + }
55 +
56 + static ssize_t nullfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
57 + {
58 + size_t count = iov_iter_count(from);
59 +
60 + iov_iter_advance(from, count);
61 + return count;
62 + }
63 +
64 + static int nullfs_pipe_to_null(struct pipe_inode_info *pipe,
65 + struct pipe_buffer *buf, struct splice_desc *sd)
66 + {
67 + return sd->len;
68 + }
69 +
70 + static ssize_t nullfs_file_splice_write(struct pipe_inode_info *pipe,
71 + struct file *out, loff_t *ppos,
72 + size_t len, unsigned int flags)
73 + {
74 + return splice_from_pipe(pipe, out, ppos, len, flags, nullfs_pipe_to_null);
75 + }
76 +
77 + static int nullfs_file_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
78 + struct iattr *attr)
79 + {
80 + if (attr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID))
81 + return -EPERM;
82 + return 0;
83 + }
84 +
85 + static const struct inode_operations nullfs_file_inode_operations = {
86 + .setattr = nullfs_file_setattr,
87 + };
88 +
89 + static const struct file_operations nullfs_file_operations = {
90 + .llseek = generic_file_llseek,
91 + .read_iter = nullfs_file_read_iter,
92 + .write_iter = nullfs_file_write_iter,
93 + .splice_read = nullfs_file_splice_read,
94 + .splice_write = nullfs_file_splice_write,
95 + .fsync = noop_fsync,
96 + .lock = nullfs_nolock,
97 + .flock = nullfs_nolock,
98 + };
99 +
100 + /*
101 + * An empty regular file on @sb as a dentry of its own, never hashed under
102 + * the root so no lookup finds it.
103 + */
104 + struct dentry *nullfs_new_file(struct super_block *sb)
105 + {
106 + struct dentry *dentry;
107 + struct inode *inode;
108 +
109 + inode = new_inode(sb);
110 + if (!inode)
111 + return ERR_PTR(-ENOMEM);
112 +
113 + /* the root directory is 1 */
114 + inode->i_ino = 2;
115 + inode->i_mode = S_IFREG | 0666;
116 + inode->i_op = &nullfs_file_inode_operations;
117 + inode->i_fop = &nullfs_file_operations;
118 + simple_inode_init_ts(inode);
119 + inode->i_flags |= S_NOATIME;
120 +
121 + dentry = d_alloc_anon(sb);
122 + if (!dentry) {
123 + iput(inode);
124 + return ERR_PTR(-ENOMEM);
125 + }
126 + d_instantiate(dentry, inode);
127 + return dentry;
128 + }
129 +
13 130 static int nullfs_fs_fill_super(struct super_block *s, struct fs_context *fc)
14 131 {
15 132 struct inode *inode;
@@ -30,10 +147,11 @@ static int nullfs_fs_fill_super(struct super_block *s, struct fs_context *fc)
30 147
31 148 /* nullfs is permanently empty... */
32 149 make_empty_dir_inode(inode);
150 + inode->i_fop = &nullfs_dir_operations;
33 151 simple_inode_init_ts(inode);
34 152 inode->i_ino = 1;
35 - /* ... and immutable. */
36 - inode->i_flags |= S_IMMUTABLE;
153 + /* ... and immutable, reading it leaves no trace either. */
154 + inode->i_flags |= S_IMMUTABLE | S_NOATIME;
37 155
38 156 s->s_root = d_make_root(inode);
39 157 if (!s->s_root)
@@ -61,6 +179,7 @@ static int nullfs_init_fs_context(struct fs_context *fc)
61 179
62 180 struct file_system_type nullfs_fs_type = {
63 181 .name = "nullfs",
182 + .fs_flags = FS_DISALLOW_NOTIFY,
64 183 .init_fs_context = nullfs_init_fs_context,
65 184 .kill_sb = kill_anon_super,
66 185 };
modified fs/ocfs2/dlm/dlmcommon.h
@@ -435,6 +435,8 @@ enum {
435 435 DLM_DEREF_LOCKRES_DONE = 522,
436 436 };
437 437
438 + extern spinlock_t dlm_reco_state_lock;
439 +
438 440 struct dlm_reco_node_data
439 441 {
440 442 int state;
modified fs/ocfs2/dlm/dlmdebug.c
@@ -736,8 +736,11 @@ static int debug_state_print(struct dlm_ctxt *dlm, char *buf, int len)
736 736 buf + out, len - out);
737 737 out += scnprintf(buf + out, len - out, "\n");
738 738
739 + spin_unlock(&dlm->spinlock);
740 +
739 741 /* Recovery Node State: */
740 742 out += scnprintf(buf + out, len - out, "Recovery Node State:\n");
743 + spin_lock(&dlm_reco_state_lock);
741 744 list_for_each_entry(node, &dlm->reco.node_data, list) {
742 745 switch (node->state) {
743 746 case DLM_RECO_NODE_DATA_INIT:
@@ -769,7 +772,7 @@ static int debug_state_print(struct dlm_ctxt *dlm, char *buf, int len)
769 772 node->node_num, state);
770 773 }
771 774
772 - spin_unlock(&dlm->spinlock);
775 + spin_unlock(&dlm_reco_state_lock);
773 776
774 777 return out;
775 778 }
modified fs/ocfs2/dlm/dlmrecovery.c
@@ -80,7 +80,7 @@ static int dlm_lockres_master_requery(struct dlm_ctxt *dlm,
80 80
81 81 static u64 dlm_get_next_mig_cookie(void);
82 82
83 - static DEFINE_SPINLOCK(dlm_reco_state_lock);
83 + DEFINE_SPINLOCK(dlm_reco_state_lock);
84 84 static DEFINE_SPINLOCK(dlm_mig_cookie_lock);
85 85 static u64 dlm_mig_cookie = 1;
86 86
modified fs/overlayfs/params.c
@@ -216,6 +216,9 @@ static ssize_t ovl_parse_param_split_lowerdirs(char *str)
216 216 if (*s == '\\') {
217 217 /* keep esc chars in split lowerdir */
218 218 *d++ = *s++;
219 + /* A trailing backslash escapes nothing. */
220 + if (!*s)
221 + return -EINVAL;
219 222 } else if (*s == ':') {
220 223 bool next_colon = (*(s + 1) == ':');
221 224
modified fs/pipe.c
@@ -838,9 +838,11 @@ pipe_fasync(int fd, struct file *filp, int on)
838 838 if (filp->f_mode & FMODE_READ)
839 839 retval = fasync_helper(fd, filp, on, &pipe->fasync_readers);
840 840 if ((filp->f_mode & FMODE_WRITE) && retval >= 0) {
841 + int read_ret = retval;
842 +
841 843 retval = fasync_helper(fd, filp, on, &pipe->fasync_writers);
842 - if (retval < 0 && (filp->f_mode & FMODE_READ))
843 - /* this can happen only if on == T */
844 + /* Undo only a reader entry added by this call. */
845 + if (retval < 0 && read_ret > 0)
844 846 fasync_helper(-1, filp, 0, &pipe->fasync_readers);
845 847 }
846 848 mutex_unlock(&pipe->mutex);
modified fs/pnode.c
@@ -410,19 +410,99 @@ bool propagation_would_overmount(const struct mount *from,
410 410 return false;
411 411 }
412 412
413 + /* Does @m receive propagation from @parent? */
414 + static bool receives_from(struct mount *m, struct mount *parent)
415 + {
416 + if (m == parent)
417 + return false;
418 + for (; m; m = m->mnt_master)
419 + if (m == parent || peers(m, parent))
420 + return true;
421 + return false;
422 + }
423 +
424 + /*
425 + * Does @m receive propagation from the victim's parent as well? If so, then
426 + * the mount at the victim's mountpoint inside of @m is a umount candidate as
427 + * well. So it's the next candidate in the chain. Otherwise the chain ends at
428 + * @m.
429 + */
430 + static struct mount *next_candidate(struct mount *m, struct mount *victim)
431 + {
432 + if (!receives_from(m, victim->mnt_parent))
433 + return NULL;
434 + return __lookup_mnt(&m->mnt, victim->mnt_mountpoint);
435 + }
436 +
437 + /*
438 + * Would propagate_umount() pull out a mount of the chain of candidates that
439 + * starts at @c, and does that mount have references beyond its own?
440 + *
441 + * This mirrors how trim_one(), trim_ancestors() and handle_locked() handle a
442 + * synchronous umount:
443 + *
444 + * - single victim
445 + * - without children
446 + * - with MNT_LOCKED already cleared on every candidate by propagate_mount_unlock()
447 + *
448 + * A copy of the victim gets unmounted when each of its children is
449 + * the next candidate in the chain or its overmount, unless the next
450 + * unmount candidate is not its overmount and some unmount candidate further
451 + * down has a child outside the chain. Keep this in sync with
452 + * Documentation/filesystems/propagate_umount.txt.
453 + */
454 + static bool chain_busy(struct mount *c, struct mount *victim)
455 + {
456 + struct mount *m, *n, *next, *deepest = NULL;
457 + bool above;
458 +
459 + /* the deepest candidate with a child outside the chain */
460 + for (m = c; m; m = next) {
461 + next = next_candidate(m, victim);
462 + list_for_each_entry(n, &m->mnt_mounts, mnt_child) {
463 + if (n != next && n != victim) {
464 + deepest = m;
465 + break;
466 + }
467 + }
468 + }
469 +
470 + above = deepest != NULL; /* @deepest is at or below @m */
471 + for (m = c; m; m = next) {
472 + bool goes = true;
473 +
474 + next = next_candidate(m, victim);
475 + list_for_each_entry(n, &m->mnt_mounts, mnt_child) {
476 + if (n != next && n != m->overmount && n != victim) {
477 + goes = false;
478 + break;
479 + }
480 + }
481 + if (goes && next && next != m->overmount && above && m != deepest)
482 + goes = false;
483 + if (m == deepest)
484 + above = false;
485 + if (goes && do_refcount_check(m, 1))
486 + return true;
487 + }
488 + return false;
489 + }
490 +
413 491 /*
414 492 * check if the mount 'mnt' can be unmounted successfully.
415 493 * @mnt: the mount to be checked for unmount
416 494 * NOTE: unmounting 'mnt' would naturally propagate to all
417 495 * other mounts its parent propagates to.
418 - * Check if any of these mounts that **do not have submounts**
419 - * have more references than 'refcnt'. If so return busy.
496 + * Check if any of the mounts that propagate_umount() would pull out
497 + * along with it have more references than their own. If so return busy.
420 498 *
421 499 * vfsmount lock must be held for write
422 500 */
423 501 int propagate_mount_busy(struct mount *mnt, int refcnt)
424 502 {
425 503 struct mount *parent = mnt->mnt_parent;
504 + struct dentry *mp = mnt->mnt_mountpoint;
505 + struct mount *m;
426 506
427 507 /*
428 508 * quickly check if the current mount can be unmounted.
@@ -435,24 +515,16 @@ int propagate_mount_busy(struct mount *mnt, int refcnt)
435 515 if (mnt == parent)
436 516 return 0;
437 517
438 - for (struct mount *m = propagation_next(parent, parent); m;
439 - m = propagation_next(m, parent)) {
440 - struct list_head *head;
441 - struct mount *child = __lookup_mnt(&m->mnt, mnt->mnt_mountpoint);
518 + /* the candidates are the mounts at @mp below the receivers */
519 + for (m = propagation_next(parent, parent); m;
520 + m = propagation_next(m, parent)) {
521 + struct mount *c = __lookup_mnt(&m->mnt, mp);
442 522
443 - if (!child)
523 + /* each chain once, from its top: skip receivers that are candidates */
524 + if (!c || (mnt_has_parent(m) && m->mnt_mountpoint == mp &&
525 + receives_from(m->mnt_parent, parent)))
444 526 continue;
445 -
446 - head = &child->mnt_mounts;
447 - if (!list_empty(head)) {
448 - /*
449 - * a mount that covers child completely wouldn't prevent
450 - * it being pulled out; any other would.
451 - */
452 - if (!list_is_singular(head) || !child->overmount)
453 - continue;
454 - }
455 - if (do_refcount_check(child, 1))
527 + if (chain_busy(c, mnt))
456 528 return 1;
457 529 }
458 530 return 0;
@@ -625,8 +697,8 @@ static void handle_locked(struct mount *m, struct list_head *to_umount)
625 697 * the same parent and mountpoint; that will be remedied as soon as we
626 698 * return from propagate_umount() - its caller (umount_tree()) will detach
627 699 * the stack from the parent it (and now @m) is attached to. umount_tree()
628 - * might choose to keep unmounted pieces stuck to each other, but it always
629 - * detaches them from the mounts that remain in the tree.
700 + * detaches every unmounted mount from its parent, whether that parent
701 + * remains in the tree or not.
630 702 */
631 703 static void reparent(struct mount *m)
632 704 {
modified fs/readdir.c
@@ -87,6 +87,8 @@ EXPORT_SYMBOL(wrap_directory_iterator);
87 87 int iterate_dir(struct file *file, struct dir_context *ctx)
88 88 {
89 89 struct inode *inode = file_inode(file);
90 + /* never an entry, never removed: nothing for the lock to keep still */
91 + bool locked = !(file->f_op->fop_flags & FOP_IMMUTABLE);
90 92 int res = -ENOTDIR;
91 93
92 94 if (!file->f_op->iterate_shared)
@@ -100,9 +102,11 @@ int iterate_dir(struct file *file, struct dir_context *ctx)
100 102 if (res)
101 103 goto out;
102 104
103 - res = down_read_killable(&inode->i_rwsem);
104 - if (res)
105 - goto out;
105 + if (locked) {
106 + res = down_read_killable(&inode->i_rwsem);
107 + if (res)
108 + goto out;
109 + }
106 110
107 111 res = -ENOENT;
108 112 if (!IS_DEADDIR(inode)) {
@@ -112,7 +116,8 @@ int iterate_dir(struct file *file, struct dir_context *ctx)
112 116 fsnotify_access(file);
113 117 file_accessed(file);
114 118 }
115 - inode_unlock_shared(inode);
119 + if (locked)
120 + inode_unlock_shared(inode);
116 121 out:
117 122 return res;
118 123 }
modified fs/tracefs/event_inode.c
@@ -91,6 +91,14 @@ static void free_ei_rcu(struct rcu_head *rcu)
91 91 }
92 92 }
93 93
94 + /* read under eventfs_srcu and, by tracefs_d_revalidate(), in rcu pathwalk */
95 + static void free_ei_srcu(struct rcu_head *rcu)
96 + {
97 + struct eventfs_inode *ei = container_of(rcu, struct eventfs_inode, rcu);
98 +
99 + call_rcu(&ei->rcu, free_ei_rcu);
100 + }
101 +
94 102 /*
95 103 * eventfs_inode reference count management.
96 104 *
@@ -112,7 +120,7 @@ static void release_ei(struct kref *ref)
112 120 entry->release(entry->name, ei->data);
113 121 }
114 122
115 - call_srcu(&eventfs_srcu, &ei->rcu, free_ei_rcu);
123 + call_srcu(&eventfs_srcu, &ei->rcu, free_ei_srcu);
116 124 }
117 125
118 126 static inline void put_ei(struct eventfs_inode *ei)
modified fs/unicode/utf8-core.c
@@ -3,6 +3,7 @@
3 3 #include <linux/kernel.h>
4 4 #include <linux/string.h>
5 5 #include <linux/slab.h>
6 + #include <linux/rcupdate.h>
6 7 #include <linux/parser.h>
7 8 #include <linux/errno.h>
8 9 #include <linux/stringhash.h>
@@ -183,12 +184,24 @@ out_free_um:
183 184 }
184 185 EXPORT_SYMBOL(utf8_load);
185 186
187 + static void utf8_unload_rcu(struct rcu_head *head)
188 + {
189 + struct unicode_map *um = container_of(head, struct unicode_map, rcu);
190 +
191 + symbol_put(utf8_data_table);
192 + kfree(um);
193 + }
194 +
195 + /*
196 + * A pathwalk in rcu mode may still be in ->d_hash() or ->d_compare() of a
197 + * filesystem that is being torn down and read the map through its
198 + * superblock, so the map and the tables it points to have to outlive the
199 + * grace period.
200 + */
186 201 void utf8_unload(struct unicode_map *um)
187 202 {
188 - if (um) {
189 - symbol_put(utf8_data_table);
190 - kfree(um);
191 - }
203 + if (um)
204 + call_rcu(&um->rcu, utf8_unload_rcu);
192 205 }
193 206 EXPORT_SYMBOL(utf8_unload);
194 207
modified fs/verity/fsverity_private.h
@@ -11,6 +11,7 @@
11 11 #define pr_fmt(fmt) "fs-verity: " fmt
12 12
13 13 #include <linux/fsverity.h>
14 + #include <linux/rcupdate.h>
14 15 #include <linux/rhashtable.h>
15 16
16 17 /*
@@ -76,7 +77,19 @@ struct merkle_tree_params {
76 77 struct fsverity_info {
77 78 struct rhash_head rhash_head;
78 79 struct merkle_tree_params tree_params;
79 - u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE];
80 + union {
81 + u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE];
82 +
83 + /*
84 + * Used for final freeing of the struct, in which case root_hash
85 + * is no longer needed. Specifically, the only fields needed
86 + * besides the rcu_head are those needed by fsverity_free_info()
87 + * itself, and those that can be accessed by fsverity_get_info()
88 + * (rhash_head and inode) during the RCU-protected rhashtable
89 + * chain search trying to find another inode's fsverity_info.
90 + */
91 + struct rcu_head rcu_head;
92 + };
80 93 u8 file_digest[FS_VERITY_MAX_DIGEST_SIZE];
81 94 struct inode *inode;
82 95 unsigned long *hash_block_verified;
modified fs/verity/open.c
@@ -399,11 +399,22 @@ void fsverity_free_info(struct fsverity_info *vi)
399 399 kmem_cache_free(fsverity_info_cachep, vi);
400 400 }
401 401
402 + static void fsverity_free_info_rcu(struct rcu_head *head)
403 + {
404 + fsverity_free_info(container_of(head, struct fsverity_info, rcu_head));
405 + }
406 +
402 407 void fsverity_remove_info(struct fsverity_info *vi)
403 408 {
404 409 rhashtable_remove_fast(&fsverity_info_hash, &vi->rhash_head,
405 410 fsverity_info_hash_params);
406 - fsverity_free_info(vi);
411 + /*
412 + * The freeing must be RCU-delayed because __fsverity_get_info() for a
413 + * *different* inode's fsverity_info in the same rhashtable hash chain
414 + * can still be accessing *this* fsverity_info's rhash_head and inode
415 + * fields as part of the RCU-protected hash chain search.
416 + */
417 + call_rcu(&vi->rcu_head, fsverity_free_info_rcu);
407 418 }
408 419
409 420 void fsverity_cleanup_inode(struct inode *inode)
modified fs/xfs/libxfs/xfs_exchmaps.c
@@ -49,7 +49,7 @@ struct xfs_exchmaps_adjacent {
49 49 .right2 = { .br_startblock = HOLESTARTBLOCK }, \
50 50 }
51 51
52 - /* Information to reset reflink flag / CoW fork state after an exchange. */
52 + /* Information to reset CoW fork state after an exchange. */
53 53
54 54 /*
55 55 * If the reflink flag is set on either inode, make sure it has an incore CoW
@@ -127,9 +127,7 @@ xmi_has_more_exchange_work(const struct xfs_exchmaps_intent *xmi)
127 127 static inline bool
128 128 xmi_has_postop_work(const struct xfs_exchmaps_intent *xmi)
129 129 {
130 - return xmi->xmi_flags & (XFS_EXCHMAPS_CLEAR_INO1_REFLINK |
131 - XFS_EXCHMAPS_CLEAR_INO2_REFLINK |
132 - __XFS_EXCHMAPS_INO2_SHORTFORM);
130 + return xmi->xmi_flags & __XFS_EXCHMAPS_INO2_SHORTFORM;
133 131 }
134 132
135 133 /* Check all mappings to make sure we can actually exchange them. */
@@ -525,18 +523,6 @@ free:
525 523 return error;
526 524 }
527 525
528 - /* Clear the reflink flag after an exchange. */
529 - static inline void
530 - xfs_exchmaps_clear_reflink(
531 - struct xfs_trans *tp,
532 - struct xfs_inode *ip)
533 - {
534 - trace_xfs_reflink_unset_inode_flag(ip);
535 -
536 - ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
537 - xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
538 - }
539 -
540 526 /* Finish whatever work might come after an exchange operation. */
541 527 static int
542 528 xfs_exchmaps_do_postop_work(
@@ -557,16 +543,6 @@ xfs_exchmaps_do_postop_work(
557 543 return error;
558 544 }
559 545
560 - if (xmi->xmi_flags & XFS_EXCHMAPS_CLEAR_INO1_REFLINK) {
561 - xfs_exchmaps_clear_reflink(tp, xmi->xmi_ip1);
562 - xmi->xmi_flags &= ~XFS_EXCHMAPS_CLEAR_INO1_REFLINK;
563 - }
564 -
565 - if (xmi->xmi_flags & XFS_EXCHMAPS_CLEAR_INO2_REFLINK) {
566 - xfs_exchmaps_clear_reflink(tp, xmi->xmi_ip2);
567 - xmi->xmi_flags &= ~XFS_EXCHMAPS_CLEAR_INO2_REFLINK;
568 - }
569 -
570 546 return 0;
571 547 }
572 548
@@ -948,46 +924,14 @@ xfs_exchmaps_intent_destroy_cache(void)
948 924 }
949 925
950 926 /*
951 - * Decide if we will exchange the reflink flags between the two files after the
952 - * exchange. The only time we want to do this is if we're exchanging all
953 - * mappings under EOF and the inode reflink flags have different states.
927 + * Allocate and initialize a new incore intent item from a request.
954 928 */
955 - static inline bool
956 - xmi_can_exchange_reflink_flags(
957 - const struct xfs_exchmaps_req *req,
958 - unsigned int reflink_state)
959 - {
960 - struct xfs_mount *mp = req->ip1->i_mount;
961 -
962 - /*
963 - * The INO1_WRITTEN optimization can skip exchanging hole and
964 - * unwritten mappings, which means we cannot guarantee that all
965 - * shared extents actually moved to the other file. Clearing the
966 - * reflink flag of an inode that still holds shared extents breaks
967 - * the CoW write path, so refuse to exchange the flags in that case.
968 - */
969 - if (req->flags & XFS_EXCHMAPS_INO1_WRITTEN)
970 - return false;
971 -
972 - if (hweight32(reflink_state) != 1)
973 - return false;
974 - if (req->startoff1 != 0 || req->startoff2 != 0)
975 - return false;
976 - if (req->blockcount != XFS_B_TO_FSB(mp, req->ip1->i_disk_size))
977 - return false;
978 - if (req->blockcount != XFS_B_TO_FSB(mp, req->ip2->i_disk_size))
979 - return false;
980 - return true;
981 - }
982 -
983 -
984 - /* Allocate and initialize a new incore intent item from a request. */
985 929 struct xfs_exchmaps_intent *
986 930 xfs_exchmaps_init_intent(
987 931 const struct xfs_exchmaps_req *req)
988 932 {
989 933 struct xfs_exchmaps_intent *xmi;
990 - unsigned int rs = 0;
934 + struct xfs_mount *mp = req->ip1->i_mount;
991 935
992 936 xmi = kmem_cache_zalloc(xfs_exchmaps_intent_cache,
993 937 GFP_NOFS | __GFP_NOFAIL);
@@ -1005,27 +949,18 @@ xfs_exchmaps_init_intent(
1005 949 return xmi;
1006 950 }
1007 951
1008 - if (req->flags & XFS_EXCHMAPS_SET_SIZES) {
1009 - xmi->xmi_flags |= XFS_EXCHMAPS_SET_SIZES;
1010 - xmi->xmi_isize1 = req->ip2->i_disk_size;
1011 - xmi->xmi_isize2 = req->ip1->i_disk_size;
1012 - }
1013 -
1014 - /* Record the state of each inode's reflink flag before the op. */
1015 - if (xfs_is_reflink_inode(req->ip1))
1016 - rs |= 1;
1017 - if (xfs_is_reflink_inode(req->ip2))
1018 - rs |= 2;
1019 -
1020 952 /*
1021 - * Figure out if we're clearing the reflink flags (which effectively
1022 - * exchanges them) after the operation.
953 + * If the caller wanted, set each file's size to that file's exchange
954 + * offset + length exchanged from the other file because the ranges in
955 + * each file might be different lengths.
1023 956 */
1024 - if (xmi_can_exchange_reflink_flags(req, rs)) {
1025 - if (rs & 1)
1026 - xmi->xmi_flags |= XFS_EXCHMAPS_CLEAR_INO1_REFLINK;
1027 - if (rs & 2)
1028 - xmi->xmi_flags |= XFS_EXCHMAPS_CLEAR_INO2_REFLINK;
957 + if (req->flags & XFS_EXCHMAPS_SET_SIZES) {
958 + loff_t off1 = XFS_FSB_TO_B(mp, xmi->xmi_startoff1);
959 + loff_t off2 = XFS_FSB_TO_B(mp, xmi->xmi_startoff2);
960 +
961 + xmi->xmi_flags |= XFS_EXCHMAPS_SET_SIZES;
962 + xmi->xmi_isize1 = off1 + (req->ip2->i_disk_size - off2);
963 + xmi->xmi_isize2 = off2 + (req->ip1->i_disk_size - off1);
1029 964 }
1030 965
1031 966 if (S_ISDIR(VFS_I(xmi->xmi_ip2)->i_mode) ||
modified fs/xfs/libxfs/xfs_log_format.h
@@ -927,10 +927,8 @@ struct xfs_xmi_log_format {
927 927 */
928 928 #define XFS_EXCHMAPS_INO1_WRITTEN (1ULL << 2)
929 929
930 - /* Clear the reflink flag from inode1 after the operation. */
930 + /* No longer set, but older intents may carry them; keep them valid. */
931 931 #define XFS_EXCHMAPS_CLEAR_INO1_REFLINK (1ULL << 3)
932 -
933 - /* Clear the reflink flag from inode2 after the operation. */
934 932 #define XFS_EXCHMAPS_CLEAR_INO2_REFLINK (1ULL << 4)
935 933
936 934 #define XFS_EXCHMAPS_LOGGED_FLAGS (XFS_EXCHMAPS_ATTR_FORK | \
modified fs/xfs/xfs_bmap_util.c
@@ -1544,7 +1544,6 @@ xfs_swap_extents(
1544 1544 struct xfs_bstat *sbp = &sxp->sx_stat;
1545 1545 int src_log_flags, target_log_flags;
1546 1546 int error = 0;
1547 - uint64_t f;
1548 1547 int resblks = 0;
1549 1548 unsigned int flags = 0;
1550 1549 struct timespec64 ctime, mtime;
@@ -1700,14 +1699,12 @@ xfs_swap_extents(
1700 1699 if (error)
1701 1700 goto out_trans_cancel;
1702 1701
1703 - /* Do we have to swap reflink flags? */
1704 - if ((ip->i_diflags2 & XFS_DIFLAG2_REFLINK) ^
1705 - (tip->i_diflags2 & XFS_DIFLAG2_REFLINK)) {
1706 - f = ip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1707 - ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1708 - ip->i_diflags2 |= tip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1709 - tip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1710 - tip->i_diflags2 |= f & XFS_DIFLAG2_REFLINK;
1702 + /* Either inode may now own shared blocks; flag both, with CoW forks. */
1703 + if ((ip->i_diflags2 | tip->i_diflags2) & XFS_DIFLAG2_REFLINK) {
1704 + ip->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1705 + tip->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1706 + xfs_ifork_init_cow(ip);
1707 + xfs_ifork_init_cow(tip);
1711 1708 }
1712 1709
1713 1710 /* Swap the cow forks. */
modified fs/xfs/xfs_exchrange.c
@@ -290,17 +290,20 @@ retry:
290 290 goto out_unlock;
291 291
292 292 /*
293 - * If the caller wanted us to exchange the contents of two complete
294 - * files of unequal length, exchange the incore sizes now. This should
295 - * be safe because we flushed both files' page caches, exchanged all
296 - * the mappings, and updated the ondisk sizes.
293 + * If the caller wanted, set each file's size to that file's exchange
294 + * offset + length exchanged from the other file because the ranges in
295 + * each file might be different lengths. This should be safe because
296 + * we flushed both files' page caches, exchanged all the mappings, and
297 + * updated the ondisk sizes.
297 298 */
298 299 if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF) {
299 - loff_t temp;
300 + loff_t old_ip1_size = i_size_read(VFS_I(ip1));
301 + loff_t old_ip2_size = i_size_read(VFS_I(ip2));
300 302
301 - temp = i_size_read(VFS_I(ip2));
302 - i_size_write(VFS_I(ip2), i_size_read(VFS_I(ip1)));
303 - i_size_write(VFS_I(ip1), temp);
303 + i_size_write(VFS_I(ip2), fxr->file2_offset +
304 + (old_ip1_size - fxr->file1_offset));
305 + i_size_write(VFS_I(ip1), fxr->file1_offset +
306 + (old_ip2_size - fxr->file2_offset));
304 307 }
305 308
306 309 out_unlock:
@@ -445,6 +448,30 @@ xfs_exchange_range_checks(
445 448 return blen == fxr->length ? 0 : -EINVAL;
446 449 }
447 450
451 + /* Flush all relevant dirty pagecache near the range to be exchanged. */
452 + static inline int
453 + xfs_exchange_range_flush(
454 + struct xfs_inode *ip,
455 + const struct xfs_exchrange *fxr,
456 + loff_t offset)
457 + {
458 + /*
459 + * If TO_EOF is set, the ondisk file size update logic depends on the
460 + * ondisk file size matching the incore file size. Flush everything.
461 + */
462 + if (fxr->flags & XFS_EXCHANGE_RANGE_TO_EOF)
463 + return filemap_write_and_wait(VFS_I(ip)->i_mapping);
464 +
465 + /*
466 + * Because we're updating the ondisk mappings, flush all dirty data
467 + * between the ondisk size and the exchange offset to reduce the chance
468 + * of zeroed file contents in that gap after a crash.
469 + */
470 + return filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
471 + min(offset, ip->i_disk_size),
472 + offset + fxr->length - 1);
473 + }
474 +
448 475 /*
449 476 * Check that the two inodes are eligible for range exchanges, the ranges make
450 477 * sense, and then flush all dirty data. Caller must ensure that the inodes
@@ -470,15 +497,11 @@ xfs_exchange_range_prep(
470 497 if (!same_inode)
471 498 inode_dio_wait(inode2);
472 499
473 - error = filemap_write_and_wait_range(inode1->i_mapping,
474 - fxr->file1_offset,
475 - fxr->file1_offset + fxr->length - 1);
500 + error = xfs_exchange_range_flush(XFS_I(inode1), fxr, fxr->file1_offset);
476 501 if (error)
477 502 return error;
478 503
479 - error = filemap_write_and_wait_range(inode2->i_mapping,
480 - fxr->file2_offset,
481 - fxr->file2_offset + fxr->length - 1);
504 + error = xfs_exchange_range_flush(XFS_I(inode2), fxr, fxr->file2_offset);
482 505 if (error)
483 506 return error;
484 507
modified include/drm/drm_exec.h
@@ -73,13 +73,15 @@ drm_exec_obj(struct drm_exec *exec, unsigned long index)
73 73
74 74 /* Helper for drm_exec_for_each_locked_object(). Internal use only. */
75 75 #define __drm_exec_for_each_locked_object(exec, obj, __index) \
76 - for (unsigned long __index = 0; ((obj) = drm_exec_obj(exec, __index)); ++__index)
76 + for (unsigned long __index = 0; ((obj) = drm_exec_obj(exec, __index)); \
77 + ++__index)
77 78 /**
78 79 * drm_exec_for_each_locked_object - iterate over all the locked objects
79 80 * @exec: drm_exec object
80 81 * @obj: the current GEM object
81 82 *
82 - * Iterate over all the locked GEM objects inside the drm_exec object.
83 + * Iterate over all the explicitly locked GEM objects inside the drm_exec
84 + * container, except for the contended and implicit prelocked one.
83 85 */
84 86 #define drm_exec_for_each_locked_object(exec, obj) \
85 87 __drm_exec_for_each_locked_object(exec, obj, __UNIQUE_ID(drm_exec))
@@ -94,12 +96,13 @@ drm_exec_obj(struct drm_exec *exec, unsigned long index)
94 96 * @exec: drm_exec object
95 97 * @obj: the current GEM object
96 98 *
97 - * Iterate over all the locked GEM objects inside the drm_exec object in
98 - * reverse locking order. Note that the internal index may wrap around,
99 - * but that will be caught by drm_exec_obj(), returning a NULL object.
99 + * Iterate over all the explicitly locked GEM objects inside the drm_exec
100 + * container in reverse locking order. Note that the internal index may wrap
101 + * around, but that will be caught by drm_exec_obj(), returning a NULL object.
100 102 */
101 103 #define drm_exec_for_each_locked_object_reverse(exec, obj) \
102 - __drm_exec_for_each_locked_object_reverse(exec, obj, __UNIQUE_ID(drm_exec))
104 + __drm_exec_for_each_locked_object_reverse(exec, obj, \
105 + __UNIQUE_ID(drm_exec))
103 106
104 107 /**
105 108 * drm_exec_until_all_locked - loop until all GEM objects are locked
modified include/linux/can/core.h
@@ -17,6 +17,7 @@
17 17 #include <linux/can.h>
18 18 #include <linux/skbuff.h>
19 19 #include <linux/netdevice.h>
20 + #include <net/can.h>
20 21
21 22 #define DNAME(dev) ((dev) ? (dev)->name : "any")
22 23
@@ -58,7 +59,7 @@ extern void can_rx_unregister(struct net *net, struct net_device *dev,
58 59 void *data);
59 60
60 61 extern int can_send(struct sk_buff *skb, int loop);
61 - void can_set_skb_uid(struct sk_buff *skb);
62 + void can_set_skb_uid(struct can_skb_ext *csx);
62 63 void can_sock_destruct(struct sock *sk);
63 64
64 65 #endif /* !_CAN_CORE_H */
modified include/linux/can/skb.h
@@ -43,8 +43,10 @@ static inline struct can_skb_ext *can_skb_ext_add(struct sk_buff *skb)
43 43 struct can_skb_ext *csx = skb_ext_add(skb, SKB_EXT_CAN);
44 44
45 45 /* skb_ext_add() returns uninitialized space */
46 - if (csx)
46 + if (csx) {
47 47 csx->can_gw_hops = 0;
48 + csx->can_skb_uid = 0;
49 + }
48 50
49 51 return csx;
50 52 }
modified include/linux/console.h
@@ -615,6 +615,15 @@ extern bool nbcon_allow_unsafe_takeover(void);
615 615 extern bool nbcon_kdb_try_acquire(struct console *con,
616 616 struct nbcon_write_context *wctxt);
617 617 extern void nbcon_kdb_release(struct nbcon_write_context *wctxt);
618 + extern bool nbcon_write_context_is_braille(struct nbcon_write_context *wctxt);
619 + extern bool nbcon_braille_try_acquire(struct console *con,
620 + struct nbcon_write_context *wctxt);
621 + extern void nbcon_braille_release(struct nbcon_write_context *wctxt);
622 +
623 + static inline bool nbcon_is_braille(struct console *con)
624 + {
625 + return con && (con->flags & CON_BRL);
626 + }
618 627
619 628 /*
620 629 * Check if the given console is currently capable and allowed to print
@@ -678,8 +687,14 @@ static inline void nbcon_reacquire_nobuf(struct nbcon_write_context *wctxt) { }
678 687 static inline bool nbcon_kdb_try_acquire(struct console *con,
679 688 struct nbcon_write_context *wctxt) { return false; }
680 689 static inline void nbcon_kdb_release(struct nbcon_write_context *wctxt) { }
690 + static inline
691 + bool nbcon_write_context_is_braille(struct nbcon_write_context *wctxt) { return false; }
681 692 static inline bool console_is_usable(struct console *con, short flags,
682 693 bool use_atomic) { return false; }
694 + static inline bool nbcon_braille_try_acquire(struct console *con,
695 + struct nbcon_write_context *wctxt) { return false; }
696 + static inline void nbcon_braille_release(struct nbcon_write_context *wctxt) { }
697 + static inline bool nbcon_is_braille(struct console *con) { return false; }
683 698 #endif
684 699
685 700 extern int console_set_on_cmdline;
modified include/linux/fs.h
@@ -1978,6 +1978,8 @@ struct file_operations {
1978 1978 #define FOP_ASYNC_LOCK ((__force fop_flags_t)(1 << 6))
1979 1979 /* File system supports uncached read/write buffered IO */
1980 1980 #define FOP_DONTCACHE ((__force fop_flags_t)(1 << 7))
1981 + /* Never changes and is never removed, readdir of a directory takes no lock */
1982 + #define FOP_IMMUTABLE ((__force fop_flags_t)(1 << 8))
1981 1983
1982 1984 /* Wrap a directory iterator that needs exclusive inode access */
1983 1985 int wrap_directory_iterator(struct file *, struct dir_context *,
@@ -2296,6 +2298,7 @@ struct file_system_type {
2296 2298 #define FS_POWER_FREEZE 256 /* Always freeze on suspend/hibernate */
2297 2299 #define FS_USERNS_MOUNT_RESTRICTED 512 /* Restrict mount in userns if not already visible */
2298 2300 #define FS_USERNS_DELEGATABLE 1024 /* Can be mounted inside userns from outside */
2301 + #define FS_DISALLOW_NOTIFY 2048 /* No fsnotify marks on its objects */
2299 2302 #define FS_RENAME_DOES_D_MOVE 32768 /* FS will handle d_move() during rename() internally. */
2300 2303 int (*init_fs_context)(struct fs_context *);
2301 2304 const struct fs_parameter_spec *parameters;
modified include/linux/fsnotify_backend.h
@@ -566,6 +566,7 @@ struct fsnotify_mark_connector {
566 566 unsigned char prio; /* Highest priority group */
567 567 #define FSNOTIFY_CONN_FLAG_IS_WATCHED 0x01
568 568 #define FSNOTIFY_CONN_FLAG_HAS_IREF 0x02
569 + #define FSNOTIFY_CONN_FLAG_DESTROYING 0x04
569 570 unsigned short flags; /* flags [lock] */
570 571 union {
571 572 /* Object pointer [lock] */
modified include/linux/futex.h
@@ -23,28 +23,32 @@ struct task_struct;
23 23 * 01 : Shared futex (PTHREAD_PROCESS_SHARED)
24 24 * mapped on a file (reference on the underlying inode)
25 25 * 10 : Shared futex (PTHREAD_PROCESS_SHARED)
26 - * (but private mapping on an mm, and reference taken on it)
26 + * (but private mapping on an mm)
27 27 */
28 28
29 - #define FUT_OFF_INODE 1 /* We set bit 0 if key has a reference on inode */
30 - #define FUT_OFF_MMSHARED 2 /* We set bit 1 if key has a reference on mm */
29 + #define FUT_OFF_INODE 1 /* We set bit 0 if shared key identifies an inode */
30 + #define FUT_OFF_MMSHARED 2 /* We set bit 1 if shared key identifies an mm */
31 31
32 32 union futex_key {
33 + /* For FUT_OFF_INODE */
33 34 struct {
34 35 u64 i_seq;
35 36 unsigned long pgoff;
36 37 unsigned int offset;
37 38 /* unsigned int node; */
38 39 } shared;
40 +
41 + /* For FUT_OFF_MMSHARED or private */
39 42 struct {
40 43 union {
41 - struct mm_struct *mm;
42 - u64 __tmp;
44 + struct mm_struct *mm; /* for private */
45 + u64 mm_seq; /* for FUT_OFF_MMSHARED */
43 46 };
44 47 unsigned long address;
45 48 unsigned int offset;
46 49 /* unsigned int node; */
47 50 } private;
51 +
48 52 struct {
49 53 u64 ptr;
50 54 unsigned long word;
@@ -152,11 +156,10 @@ static inline void futex_set_vdso_cs_range(struct futex_mm_data *fd, unsigned in
152 156 static inline void futex_fixup_robust_unlock(struct pt_regs *regs) { }
153 157 #endif /* !CONFIG_FUTEX_ROBUST_UNLOCK */
154 158
155 -
156 - #if defined(CONFIG_FUTEX_PRIVATE_HASH) || defined(CONFIG_FUTEX_ROBUST_UNLOCK)
159 + #ifdef CONFIG_FUTEX
157 160 void futex_mm_init(struct mm_struct *mm);
158 161 #else
159 162 static inline void futex_mm_init(struct mm_struct *mm) { }
160 - #endif
163 + #endif /* !CONFIG_FUTEX */
161 164
162 165 #endif /* _LINUX_FUTEX_H */
modified include/linux/futex_types.h
@@ -85,10 +85,12 @@ struct futex_unlock_cs_ranges { };
85 85 * struct futex_mm_data - Futex related per MM data
86 86 * @phash: Futex private hash related data
87 87 * @unlock: Futex unlock VDSO critical sections
88 + * @unique_id: Unique ID of the MM, for FUT_OFF_MMSHARED futexes
88 89 */
89 90 struct futex_mm_data {
90 91 struct futex_mm_phash phash;
91 92 struct futex_unlock_cs_ranges unlock;
93 + atomic64_t unique_id;
92 94 };
93 95 #else /* CONFIG_FUTEX */
94 96 struct futex_sched_data { };
modified include/linux/io_uring_types.h
@@ -322,6 +322,8 @@ enum {
322 322 IO_RING_F_DRAIN_DISABLED = BIT(10),
323 323 IO_RING_F_COMPAT = BIT(11),
324 324 IO_RING_F_IOWQ_LIMITS_SET = BIT(12),
325 + /* restrictions were inherited from the task that created the ring */
326 + IO_RING_F_RESTRICT_INHERITED = BIT(13),
325 327 };
326 328
327 329 struct iou_ctx {};
modified include/linux/irq-entry-common.h
@@ -468,6 +468,25 @@ static inline void irqentry_exit_to_kernel_mode_preempt(struct pt_regs *regs,
468 468 irqentry_exit_cond_resched();
469 469 }
470 470
471 + /*
472 + * The deferred hrtimer rearm is the tail of the timer interrupt, moved to the
473 + * interrupt return path so that it runs after a possible reschedule. By now
474 + * irq_exit_rcu() has left lockdep's hardirq context. Re-enter it for the
475 + * rearm, so that the hrtimer base lock and the timekeeping sequence count are
476 + * not chained onto the locks held by the interrupted context, which would add
477 + * new lock chains for every lock stack an interrupt hits.
478 + *
479 + * The rearm on return to user mode needs no such annotation: no locks are
480 + * held there, so it uses the same lock chains as the rearm in hardirq
481 + * context.
482 + */
483 + static __always_inline void irqentry_hrtimer_rearm_deferred(void)
484 + {
485 + lockdep_hardirq_enter();
486 + hrtimer_rearm_deferred();
487 + lockdep_hardirq_exit();
488 + }
489 +
471 490 /**
472 491 * irqentry_exit_to_kernel_mode_after_preempt - Establish trace, lockdep and RCU state
473 492 * @regs: Pointer to current's pt_regs
@@ -491,7 +510,7 @@ irqentry_exit_to_kernel_mode_after_preempt(struct pt_regs *regs, irqentry_state_
491 510 */
492 511 if (state.exit_rcu) {
493 512 instrumentation_begin();
494 - hrtimer_rearm_deferred();
513 + irqentry_hrtimer_rearm_deferred();
495 514 /* Tell the tracer that IRET will enable interrupts */
496 515 trace_hardirqs_on_prepare();
497 516 lockdep_hardirqs_on_prepare();
@@ -502,7 +521,7 @@ irqentry_exit_to_kernel_mode_after_preempt(struct pt_regs *regs, irqentry_state_
502 521 }
503 522
504 523 instrumentation_begin();
505 - hrtimer_rearm_deferred();
524 + irqentry_hrtimer_rearm_deferred();
506 525 /* Covers both tracing and lockdep */
507 526 trace_hardirqs_on();
508 527 instrumentation_end();
modified include/linux/mount.h
@@ -52,7 +52,7 @@ enum mount_flags {
52 52 MNT_ATIME_MASK = MNT_NOATIME | MNT_NODIRATIME | MNT_RELATIME,
53 53
54 54 MNT_INTERNAL_FLAGS = MNT_INTERNAL | MNT_DOOMED |
55 - MNT_SYNC_UMOUNT | MNT_LOCKED
55 + MNT_SYNC_UMOUNT | MNT_LOCKED | MNT_UMOUNT
56 56 };
57 57
58 58 struct vfsmount {
modified include/linux/nsproxy.h
@@ -100,6 +100,7 @@ void exit_cred_namespaces(struct task_struct *tsk);
100 100 void switch_task_namespaces(struct task_struct *tsk, struct nsproxy *new);
101 101 int exec_task_namespaces(void);
102 102 void deactivate_nsproxy(struct nsproxy *ns);
103 + void nsproxy_free(struct nsproxy *ns);
103 104 int unshare_nsproxy_namespaces(unsigned long, struct nsproxy **,
104 105 struct cred *, struct fs_struct *);
105 106 int __init nsproxy_cache_init(void);
modified include/linux/nvme.h
@@ -1266,8 +1266,8 @@ enum {
1266 1266 NVME_ZRASF_ZONE_STATE_IMP_OPEN = 0x02,
1267 1267 NVME_ZRASF_ZONE_STATE_EXP_OPEN = 0x03,
1268 1268 NVME_ZRASF_ZONE_STATE_CLOSED = 0x04,
1269 - NVME_ZRASF_ZONE_STATE_READONLY = 0x05,
1270 - NVME_ZRASF_ZONE_STATE_FULL = 0x06,
1269 + NVME_ZRASF_ZONE_STATE_FULL = 0x05,
1270 + NVME_ZRASF_ZONE_STATE_READONLY = 0x06,
1271 1271 NVME_ZRASF_ZONE_STATE_OFFLINE = 0x07,
1272 1272 NVME_REPORT_ZONE_PARTIAL = 1,
1273 1273 };
modified include/linux/pci.h
@@ -467,6 +467,7 @@ struct pci_dev {
467 467
468 468 unsigned int is_busmaster:1; /* Is busmaster */
469 469 unsigned int no_msi:1; /* May not use MSI */
470 + unsigned int no_aer_anfe:1; /* Do not unmask ANFE */
470 471 unsigned int block_cfg_access:1; /* Config space access blocked */
471 472 unsigned int broken_parity_status:1; /* Generates false positive parity */
472 473 unsigned int irq_reroute_variant:2; /* Needs IRQ rerouting variant */
modified include/linux/power_supply.h
@@ -351,6 +351,16 @@ struct power_supply {
351 351 bool removing;
352 352 atomic_t use_cnt;
353 353 struct power_supply_battery_info *battery_info;
354 + /*
355 + * Held for read while ->external_power_changed() runs, and for write by
356 + * power_supply_unregister() when it publishes @removing, so that it
357 + * waits for an in-flight callback to finish. Without this a driver's
358 + * data, typically devm-allocated on its own device, can be freed while
359 + * the callback is still using it.
360 + * Must not be shared with extensions_sem: callbacks may read their own
361 + * properties, which takes that one for read.
362 + */
363 + struct rw_semaphore epc_sem;
354 364 struct rw_semaphore extensions_sem; /* protects "extensions" */
355 365 struct list_head extensions;
356 366 #ifdef CONFIG_THERMAL
@@ -414,9 +424,9 @@ struct power_supply_vbat_ri_table {
414 424 * @charge_voltage_max_uv: maintenance charging voltage that is usually a bit
415 425 * lower than the constant_charge_voltage_max_uv. We can apply this settings
416 426 * charge_current_max_ua until we get back up to this voltage.
417 - * @safety_timer_minutes: maintenance charging safety timer, with an expiry
418 - * time in minutes. We will only use maintenance charging in this setting
419 - * for a certain amount of time, then we will first move to the next
427 + * @charge_safety_timer_minutes: maintenance charging safety timer, with an
428 + * expiry time in minutes. We will only use maintenance charging in this
429 + * setting for a certain amount of time, then we will first move to the next
420 430 * maintenance charge current and voltage pair in respective array and wait
421 431 * for the next safety timer timeout, or, if we reached the last maintencance
422 432 * charging setting, disable charging until we reach
modified include/linux/sched/ext.h
@@ -207,6 +207,7 @@ struct sched_ext_entity {
207 207 s32 holding_cpu;
208 208 s32 selected_cpu;
209 209 s32 runnable_cpu; /* cpu @p is runnable on, -1 if not */
210 + u32 ops_qseq; /* protected by rq lock */
210 211 struct task_struct *kf_tasks[2]; /* see SCX_CALL_OP_TASK() */
211 212
212 213 struct list_head runnable_node; /* rq->scx.runnable_list */
modified include/linux/sched/signal.h
@@ -130,8 +130,8 @@ struct signal_struct {
130 130 * process will inherit a flag if they should look for a
131 131 * child_subreaper process at exit.
132 132 */
133 - unsigned int is_child_subreaper:1;
134 - unsigned int has_child_subreaper:1;
133 + bool is_child_subreaper;
134 + bool has_child_subreaper;
135 135 unsigned int autoreap:1;
136 136
137 137 #ifdef CONFIG_POSIX_TIMERS
modified include/linux/sched/user.h
@@ -23,11 +23,13 @@ struct user_struct {
23 23 struct hlist_node uidhash_node;
24 24 kuid_t uid;
25 25
26 - #if defined(CONFIG_PERF_EVENTS) || defined(CONFIG_BPF_SYSCALL) || \
27 - defined(CONFIG_NET) || defined(CONFIG_IO_URING) || \
26 + #if defined(CONFIG_NET) || defined(CONFIG_IO_URING) || \
28 27 defined(CONFIG_VFIO_PCI_ZDEV_KVM) || IS_ENABLED(CONFIG_IOMMUFD) || \
29 28 defined(CONFIG_SECRETMEM)
30 - atomic_long_t locked_vm;
29 + atomic_long_t locked_vm; /* pinned pages charged to RLIMIT_MEMLOCK */
30 + #endif
31 + #ifdef CONFIG_PERF_EVENTS
32 + atomic_long_t perf_mlock; /* perf buffer pages within perf_event_mlock_kb */
31 33 #endif
32 34 #ifdef CONFIG_WATCH_QUEUE
33 35 atomic_t nr_watches; /* The number of watches this user currently has */
modified include/linux/unicode.h
@@ -53,6 +53,7 @@ struct unicode_map {
53 53 unsigned int version;
54 54 const struct utf8data *ntab[UTF8_NMAX];
55 55 const struct utf8data_table *tables;
56 + struct rcu_head rcu;
56 57 };
57 58
58 59 int utf8_validate(const struct unicode_map *um, const struct qstr *str);
modified include/linux/virtio_net.h
@@ -111,48 +111,38 @@ static inline int __virtio_net_hdr_to_skb(struct sk_buff *skb,
111 111 p_off = nh_min_len + thlen;
112 112 if (!pskb_may_pull(skb, p_off))
113 113 return -EINVAL;
114 - } else {
114 + } else if (gso_type) {
115 115 /* gso packets without NEEDS_CSUM do not set transport_offset.
116 116 * probe and drop if does not match one of the above types.
117 117 */
118 - if (gso_type && skb->network_header) {
119 - struct flow_keys_basic keys;
120 -
121 - if (!skb->protocol) {
122 - __be16 protocol = dev_parse_header_protocol(skb);
123 -
124 - if (!protocol)
125 - virtio_net_hdr_set_proto(skb, hdr);
126 - else if (!virtio_net_hdr_match_proto(protocol,
127 - hdr_gso_type))
128 - return -EINVAL;
129 - else
130 - skb->protocol = protocol;
131 - }
118 + struct flow_keys_basic keys;
119 +
120 + if (!skb->protocol) {
121 + skb->protocol = dev_parse_header_protocol(skb);
122 + if (!skb->protocol)
123 + virtio_net_hdr_set_proto(skb, hdr);
124 + }
132 125 retry:
133 - if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys,
134 - NULL, 0, 0, 0,
135 - 0)) {
136 - /* UFO does not specify ipv4 or 6: try both */
137 - if (gso_type & SKB_GSO_UDP &&
138 - skb->protocol == htons(ETH_P_IP)) {
139 - skb->protocol = htons(ETH_P_IPV6);
140 - goto retry;
141 - }
142 - return -EINVAL;
126 + if (!skb_flow_dissect_flow_keys_basic(NULL, skb, &keys,
127 + NULL, 0, 0, 0,
128 + 0)) {
129 + /* UFO does not specify ipv4 or 6: try both */
130 + if (gso_type & SKB_GSO_UDP &&
131 + skb->protocol == htons(ETH_P_IP)) {
132 + skb->protocol = htons(ETH_P_IPV6);
133 + goto retry;
143 134 }
135 + return -EINVAL;
136 + }
144 137
145 - p_off = keys.control.thoff + thlen;
146 - if (!pskb_may_pull(skb, p_off) ||
147 - keys.basic.ip_proto != ip_proto)
148 - return -EINVAL;
138 + p_off = keys.control.thoff + thlen;
139 + if (!pskb_may_pull(skb, p_off) ||
140 + keys.basic.ip_proto != ip_proto ||
141 + !virtio_net_hdr_match_proto(keys.basic.n_proto,
142 + hdr_gso_type))
143 + return -EINVAL;
149 144
150 - skb_set_transport_header(skb, keys.control.thoff);
151 - } else if (gso_type) {
152 - p_off = nh_min_len + thlen;
153 - if (!pskb_may_pull(skb, p_off))
154 - return -EINVAL;
155 - }
145 + skb_set_transport_header(skb, keys.control.thoff);
156 146 }
157 147
158 148 if (hdr_gso_type != VIRTIO_NET_HDR_GSO_NONE) {
modified include/net/amt.h
@@ -231,10 +231,6 @@ struct amt_relay_headers {
231 231 };
232 232 } __packed;
233 233
234 - struct amt_skb_cb {
235 - struct amt_tunnel_list *tunnel;
236 - };
237 -
238 234 struct amt_tunnel_list {
239 235 struct list_head list;
240 236 /* Protect All resources under an amt_tunne_list */
modified include/net/bluetooth/rfcomm.h
@@ -207,6 +207,7 @@ struct rfcomm_dlc {
207 207 #define RFCOMM_AUTH_REJECT 7
208 208 #define RFCOMM_DEFER_SETUP 8
209 209 #define RFCOMM_ENC_DROP 9
210 + #define RFCOMM_CLOSED 10
210 211
211 212 /* Scheduling flags and events */
212 213 #define RFCOMM_SCHED_WAKEUP 31
modified include/net/can.h
@@ -17,12 +17,14 @@
17 17 * @can_framelen: cached echo CAN frame length for bql
18 18 * @can_gw_hops: can-gw CAN frame time-to-live counter
19 19 * @can_ext_flags: CAN skb extensions flags
20 + * @can_skb_uid: CAN skb UID for raw_rcv and isotp echo handling
20 21 */
21 22 struct can_skb_ext {
22 23 int can_iif;
23 24 u16 can_framelen;
24 25 u8 can_gw_hops;
25 26 u8 can_ext_flags;
27 + u32 can_skb_uid;
26 28 };
27 29
28 30 #endif /* _NET_CAN_H */
modified include/net/ip.h
@@ -74,6 +74,13 @@ static inline unsigned int ip_hdrlen(const struct sk_buff *skb)
74 74 return ip_hdr(skb)->ihl * 4;
75 75 }
76 76
77 + static inline int ip_check_csum_start(const struct sk_buff *skb)
78 + {
79 + if (unlikely(skb->csum_start < skb->network_header + ip_hdrlen(skb)))
80 + return -EINVAL;
81 + return 0;
82 + }
83 +
77 84 struct ipcm_cookie {
78 85 struct sockcm_cookie sockc;
79 86 __be32 addr;
modified include/net/mana/mana.h
@@ -377,7 +377,18 @@ struct mana_recv_buf_oob {
377 377 #define MANA_RXBUF_PAD (SKB_DATA_ALIGN(sizeof(struct skb_shared_info)) \
378 378 + ETH_HLEN)
379 379
380 - #define MANA_XDP_MTU_MAX (PAGE_SIZE - MANA_RXBUF_PAD - XDP_PACKET_HEADROOM)
380 + /* Headroom an RX buffer has to reserve while XDP is attached: the XDP program
381 + * needs XDP_PACKET_HEADROOM, and the TX path needs LL_RESERVED_SPACE() (see
382 + * mana_get_rxbuf_headroom()). LL_RESERVED_SPACE() grows with MAX_SKB_FRAGS and
383 + * exceeds XDP_PACKET_HEADROOM once CONFIG_MAX_SKB_FRAGS is 19 or more.
384 + */
385 + static inline u32 mana_xdp_headroom(struct net_device *ndev)
386 + {
387 + return max_t(u32, LL_RESERVED_SPACE(ndev), XDP_PACKET_HEADROOM);
388 + }
389 +
390 + #define MANA_XDP_MTU_MAX(ndev) \
391 + (PAGE_SIZE - MANA_RXBUF_PAD - mana_xdp_headroom(ndev))
381 392
382 393 struct mana_rxq {
383 394 struct gdma_queue *gdma_rq;
@@ -691,6 +702,7 @@ int mana_query_link_cfg(struct mana_port_context *apc);
691 702 int mana_set_bw_clamp(struct mana_port_context *apc, u32 speed,
692 703 int enable_clamping);
693 704 void mana_query_phy_stats(struct mana_port_context *apc);
705 + bool mana_single_rxbuf_per_page_forced(struct mana_port_context *apc, u32 mtu);
694 706 int mana_pre_alloc_rxbufs(struct mana_port_context *apc, int mtu, int num_queues);
695 707 void mana_pre_dealloc_rxbufs(struct mana_port_context *apc);
696 708 void mana_unmap_skb(struct sk_buff *skb, struct mana_port_context *apc);
modified include/net/strparser.h
@@ -91,11 +91,11 @@ static inline struct strp_msg *strp_msg(struct sk_buff *skb)
91 91 struct strparser {
92 92 struct sock *sk;
93 93
94 - u32 stopped : 1;
95 - u32 paused : 1;
96 - u32 aborted : 1;
97 - u32 interrupted : 1;
98 - u32 unrecov_intr : 1;
94 + u8 stopped;
95 + u8 paused;
96 + u8 aborted;
97 + u8 interrupted;
98 + u8 unrecov_intr;
99 99
100 100 struct sk_buff **skb_nextp;
101 101 struct sk_buff *skb_head;
modified io_uring/cancel.c
@@ -634,12 +634,11 @@ __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
634 634 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
635 635 io_run_task_work();
636 636 io_uring_drop_tctx_refs(current);
637 + /* only skip the sleep for local work this task may run */
637 638 xa_for_each(&tctx->xa, index, node) {
638 - if (io_local_work_pending(node->ctx)) {
639 - WARN_ON_ONCE(node->ctx->submitter_task &&
640 - node->ctx->submitter_task != current);
639 + if (io_local_work_pending(node->ctx) &&
640 + io_allowed_defer_tw_run(node->ctx))
641 641 goto end_wait;
642 - }
643 642 }
644 643 /*
645 644 * If we've seen completions, retry without waiting. This
modified io_uring/io_uring.c
@@ -2070,8 +2070,9 @@ int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
2070 2070
2071 2071 static void io_rings_free(struct io_ring_ctx *ctx)
2072 2072 {
2073 - io_free_region(ctx->user, &ctx->sq_region);
2074 - io_free_region(ctx->user, &ctx->ring_region);
2073 + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */
2074 + io_free_region(NULL, &ctx->sq_region);
2075 + io_free_region(NULL, &ctx->ring_region);
2075 2076 ctx->rings = NULL;
2076 2077 RCU_INIT_POINTER(ctx->rings_rcu, NULL);
2077 2078 ctx->sq_sqes = NULL;
@@ -2735,7 +2736,8 @@ static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2735 2736 rd.user_addr = p->cq_off.user_addr;
2736 2737 rd.flags |= IORING_MEM_REGION_TYPE_USER;
2737 2738 }
2738 - ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
2739 + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */
2740 + ret = io_create_region(NULL, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
2739 2741 if (ret)
2740 2742 return ret;
2741 2743 ctx->rings = rings = io_region_get_ptr(&ctx->ring_region);
@@ -2749,7 +2751,7 @@ static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
2749 2751 rd.user_addr = p->sq_off.user_addr;
2750 2752 rd.flags |= IORING_MEM_REGION_TYPE_USER;
2751 2753 }
2752 - ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES);
2754 + ret = io_create_region(NULL, &ctx->sq_region, &rd, IORING_OFF_SQES);
2753 2755 if (ret) {
2754 2756 io_rings_free(ctx);
2755 2757 return ret;
@@ -2960,7 +2962,8 @@ static void io_ctx_restriction_clone(struct io_ring_ctx *ctx,
2960 2962 if (dst->op_registered)
2961 2963 ctx->int_flags |= IO_RING_F_OP_RESTRICTED;
2962 2964 if (dst->reg_registered)
2963 - ctx->int_flags |= IO_RING_F_REG_RESTRICTED;
2965 + ctx->int_flags |= IO_RING_F_REG_RESTRICTED |
2966 + IO_RING_F_RESTRICT_INHERITED;
2964 2967 }
2965 2968
2966 2969 static __cold int io_uring_create(struct io_ctx_config *config)
modified io_uring/kbuf.c
@@ -459,7 +459,7 @@ static int io_remove_buffers_legacy(struct io_ring_ctx *ctx,
459 459 static void io_put_bl(struct io_ring_ctx *ctx, struct io_buffer_list *bl)
460 460 {
461 461 if (bl->flags & IOBL_BUF_RING)
462 - io_free_region(ctx->user, &bl->region);
462 + io_free_region(NULL, &bl->region);
463 463 else
464 464 io_remove_buffers_legacy(ctx, bl, -1U);
465 465
@@ -676,7 +676,7 @@ int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
676 676 rd.user_addr = reg.ring_addr;
677 677 rd.flags |= IORING_MEM_REGION_TYPE_USER;
678 678 }
679 - ret = io_create_region(ctx, &bl->region, &rd, mmap_offset);
679 + ret = io_create_region(NULL, &bl->region, &rd, mmap_offset);
680 680 if (ret)
681 681 goto fail;
682 682 br = io_region_get_ptr(&bl->region);
@@ -709,7 +709,7 @@ int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
709 709 if (!ret)
710 710 return 0;
711 711 fail:
712 - io_free_region(ctx->user, &bl->region);
712 + io_free_region(NULL, &bl->region);
713 713 kfree(bl);
714 714 return ret;
715 715 }
modified io_uring/memmap.c
@@ -204,7 +204,7 @@ done:
204 204 return 0;
205 205 }
206 206
207 - int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr,
207 + int io_create_region(struct user_struct *user, struct io_mapped_region *mr,
208 208 struct io_uring_region_desc *reg,
209 209 unsigned long mmap_offset)
210 210 {
@@ -230,8 +230,8 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr,
230 230 return -EOVERFLOW;
231 231
232 232 nr_pages = reg->size >> PAGE_SHIFT;
233 - if (ctx->user) {
234 - ret = __io_account_mem(ctx->user, nr_pages);
233 + if (user) {
234 + ret = __io_account_mem(user, nr_pages);
235 235 if (ret)
236 236 return ret;
237 237 }
@@ -240,7 +240,7 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr,
240 240 if (reg->flags & IORING_MEM_REGION_TYPE_USER)
241 241 ret = io_region_pin_pages(mr, reg);
242 242 else
243 - ret = io_region_allocate_pages(mr, reg, mmap_offset, ctx->user);
243 + ret = io_region_allocate_pages(mr, reg, mmap_offset, user);
244 244 if (ret)
245 245 goto out_free;
246 246
@@ -249,7 +249,7 @@ int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr,
249 249 goto out_free;
250 250 return 0;
251 251 out_free:
252 - io_free_region(ctx->user, mr);
252 + io_free_region(user, mr);
253 253 return ret;
254 254 }
255 255
modified io_uring/memmap.h
@@ -18,7 +18,7 @@ unsigned long io_uring_get_unmapped_area(struct file *file, unsigned long addr,
18 18 int io_uring_mmap(struct file *file, struct vm_area_struct *vma);
19 19
20 20 void io_free_region(struct user_struct *user, struct io_mapped_region *mr);
21 - int io_create_region(struct io_ring_ctx *ctx, struct io_mapped_region *mr,
21 + int io_create_region(struct user_struct *user, struct io_mapped_region *mr,
22 22 struct io_uring_region_desc *reg,
23 23 unsigned long mmap_offset);
24 24
modified io_uring/net.c
@@ -7,6 +7,7 @@
7 7 #include <linux/un.h>
8 8 #include <linux/compat.h>
9 9 #include <net/compat.h>
10 + #include <net/ipv6.h>
10 11 #include <linux/io_uring.h>
11 12
12 13 #include <uapi/linux/io_uring.h>
@@ -1741,7 +1742,8 @@ void io_connect_bpf_populate(struct io_uring_bpf_ctx *bctx, struct io_kiocb *req
1741 1742 case AF_INET6: {
1742 1743 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)ss;
1743 1744
1744 - if (conn->addr_len < (int)sizeof(*sin6))
1745 + /* The IPv6 stack accepts SIN6_LEN_RFC2133; port and addr are in it. */
1746 + if (conn->addr_len < SIN6_LEN_RFC2133)
1745 1747 break;
1746 1748 bctx->connect.port = sin6->sin6_port;
1747 1749 memcpy(bctx->connect.v6_addr, &sin6->sin6_addr,
modified io_uring/register.c
@@ -480,8 +480,9 @@ struct io_ring_ctx_rings {
480 480 static void io_register_free_rings(struct io_ring_ctx *ctx,
481 481 struct io_ring_ctx_rings *r)
482 482 {
483 - io_free_region(ctx->user, &r->sq_region);
484 - io_free_region(ctx->user, &r->ring_region);
483 + /* ring memory is not charged to RLIMIT_MEMLOCK, hence no user */
484 + io_free_region(NULL, &r->sq_region);
485 + io_free_region(NULL, &r->ring_region);
485 486 }
486 487
487 488 #define swap_old(ctx, o, n, field) \
@@ -529,7 +530,7 @@ static int io_register_resize_rings(struct io_ring_ctx *ctx, void __user *arg)
529 530 rd.user_addr = p->cq_off.user_addr;
530 531 rd.flags |= IORING_MEM_REGION_TYPE_USER;
531 532 }
532 - ret = io_create_region(ctx, &n.ring_region, &rd, IORING_OFF_CQ_RING);
533 + ret = io_create_region(NULL, &n.ring_region, &rd, IORING_OFF_CQ_RING);
533 534 if (ret)
534 535 return ret;
535 536
@@ -559,7 +560,7 @@ static int io_register_resize_rings(struct io_ring_ctx *ctx, void __user *arg)
559 560 rd.user_addr = p->sq_off.user_addr;
560 561 rd.flags |= IORING_MEM_REGION_TYPE_USER;
561 562 }
562 - ret = io_create_region(ctx, &n.sq_region, &rd, IORING_OFF_SQES);
563 + ret = io_create_region(NULL, &n.sq_region, &rd, IORING_OFF_SQES);
563 564 if (ret) {
564 565 io_register_free_rings(ctx, &n);
565 566 return ret;
@@ -730,7 +731,8 @@ static int io_register_mem_region(struct io_ring_ctx *ctx, void __user *uarg)
730 731 !(ctx->flags & IORING_SETUP_R_DISABLED))
731 732 return -EINVAL;
732 733
733 - ret = io_create_region(ctx, &region, &rd, IORING_MAP_OFF_PARAM_REGION);
734 + ret = io_create_region(ctx->user, &region, &rd,
735 + IORING_MAP_OFF_PARAM_REGION);
734 736 if (ret)
735 737 return ret;
736 738 if (copy_to_user(rd_uptr, &rd, sizeof(rd))) {
@@ -764,7 +766,14 @@ static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
764 766 if (ctx->submitter_task && ctx->submitter_task != current)
765 767 return -EEXIST;
766 768
767 - if ((ctx->int_flags & IO_RING_F_REG_RESTRICTED) && !(ctx->flags & IORING_SETUP_R_DISABLED)) {
769 + /*
770 + * A disabled ring is exempt from its own register restrictions, so
771 + * that the creator can set them up and then enable the ring. That
772 + * does not apply to restrictions inherited from the task.
773 + */
774 + if ((ctx->int_flags & IO_RING_F_REG_RESTRICTED) &&
775 + (!(ctx->flags & IORING_SETUP_R_DISABLED) ||
776 + (ctx->int_flags & IO_RING_F_RESTRICT_INHERITED))) {
768 777 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
769 778 if (!test_bit(opcode, ctx->restrictions.register_op))
770 779 return -EACCES;
modified io_uring/zcrx.c
@@ -432,7 +432,7 @@ static int io_allocate_rbuf_ring(struct io_ring_ctx *ctx,
432 432 mmap_offset = IORING_MAP_OFF_ZCRX_REGION;
433 433 mmap_offset += (u64)id << IORING_OFF_ZCRX_SHIFT;
434 434
435 - ret = io_create_region(ctx, &ifq->rq_region, rd, mmap_offset);
435 + ret = io_create_region(ctx->user, &ifq->rq_region, rd, mmap_offset);
436 436 if (ret < 0)
437 437 return ret;
438 438
modified ipc/namespace.c
@@ -96,7 +96,7 @@ fail_ipc:
96 96 fail_mq_sysctls:
97 97 retire_mq_sysctls(ns);
98 98 fail_mq_mount:
99 - mntput(ns->mq_mnt);
99 + kern_unmount(ns->mq_mnt);
100 100 fail_put:
101 101 put_user_ns(ns->user_ns);
102 102 ns_common_free(ns);
modified kernel/cgroup/cpuset.c
@@ -152,6 +152,12 @@ static cpumask_var_t isolated_cpus; /* CSCB */
152 152 */
153 153 static bool update_housekeeping; /* RWCS */
154 154
155 + /*
156 + * Set if "cpuset_v2_mode" mount option is used
157 + * Cached at bind time and not lock protected; accessed via {READ,WRITE}_ONCE
158 + */
159 + static bool cpuset_v2_mode;
160 +
155 161 /*
156 162 * Copy of isolated_cpus to be passed to housekeeping_update()
157 163 */
@@ -439,8 +445,7 @@ static inline bool cpuset_v2(void)
439 445 */
440 446 static inline bool is_in_v2_mode(void)
441 447 {
442 - return cpuset_v2() ||
443 - (cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE);
448 + return cpuset_v2() || READ_ONCE(cpuset_v2_mode);
444 449 }
445 450
446 451 /**
@@ -513,10 +518,26 @@ static void guarantee_active_cpus(struct task_struct *tsk,
513 518 rcu_read_lock();
514 519 cs = task_cs(tsk);
515 520
516 - while (!cpumask_intersects(cs->effective_cpus, pmask))
521 + while (!cpumask_intersects(cs->effective_cpus, pmask)) {
517 522 cs = parent_cs(cs);
518 -
523 + if (unlikely(!cs)) {
524 + /*
525 + * The top cpuset doesn't have any active cpu as a
526 + * consequence of a race between its caller and the cpu
527 + * hotplug operation where cpu_active_mask is updated
528 + * asynchronously before cpuset_handle_hotplug() is
529 + * being called to adjust the effective_cpus of the
530 + * affected cpusets. But we know the top cpuset's
531 + * effective_cpus is on its way to be identical to
532 + * cpu_active_mask minus the exclusive CPUs dedicated
533 + * to other valid cpuset partitions. Just pass back
534 + * the filtered cpu_active_mask in this case.
535 + */
536 + goto out_unlock;
537 + }
538 + }
519 539 cpumask_and(pmask, pmask, cs->effective_cpus);
540 + out_unlock:
520 541 rcu_read_unlock();
521 542 }
522 543
@@ -3732,6 +3753,8 @@ static void cpuset_bind(struct cgroup_subsys_state *root_css)
3732 3753 mutex_lock(&cpuset_mutex);
3733 3754 spin_lock_irq(&callback_lock);
3734 3755
3756 + WRITE_ONCE(cpuset_v2_mode,
3757 + !!(cpuset_cgrp_subsys.root->flags & CGRP_ROOT_CPUSET_V2_MODE));
3735 3758 if (is_in_v2_mode()) {
3736 3759 cpumask_copy(top_cpuset.cpus_allowed, cpu_possible_mask);
3737 3760 cpumask_copy(top_cpuset.effective_xcpus, cpu_possible_mask);
@@ -4044,15 +4067,16 @@ static void cpuset_handle_hotplug(void)
4044 4067 static cpumask_t new_cpus;
4045 4068 static nodemask_t new_mems;
4046 4069 bool cpus_updated, mems_updated;
4047 - bool on_dfl = is_in_v2_mode();
4070 + bool on_dfl;
4048 4071 struct tmpmasks tmp, *ptmp = NULL;
4049 4072
4050 - if (on_dfl && !alloc_tmpmasks(&tmp))
4051 - ptmp = &tmp;
4052 -
4053 4073 lockdep_assert_cpus_held();
4054 4074 mutex_lock(&cpuset_mutex);
4055 4075
4076 + on_dfl = is_in_v2_mode();
4077 + if (on_dfl && !alloc_tmpmasks(&tmp))
4078 + ptmp = &tmp;
4079 +
4056 4080 /* fetch the available cpus/mems and find out which changed how */
4057 4081 cpumask_copy(&new_cpus, cpu_active_mask);
4058 4082 new_mems = node_states[N_MEMORY];
modified kernel/dma/swiotlb.c
@@ -1844,10 +1844,10 @@ phys_addr_t default_swiotlb_base(void)
1844 1844 phys_addr_t default_swiotlb_limit(void)
1845 1845 {
1846 1846 #ifdef CONFIG_SWIOTLB_DYNAMIC
1847 - return io_tlb_default_mem.phys_limit;
1848 - #else
1849 - return io_tlb_default_mem.defpool.end - 1;
1847 + if (io_tlb_default_mem.can_grow)
1848 + return io_tlb_default_mem.phys_limit;
1850 1849 #endif
1850 + return io_tlb_default_mem.defpool.end - 1;
1851 1851 }
1852 1852
1853 1853 #ifdef CONFIG_DEBUG_FS
modified kernel/events/core.c
@@ -4639,6 +4639,7 @@ static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4639 4639
4640 4640 if (cpu_event) {
4641 4641 update_context_time(&cpuctx->ctx);
4642 + update_cgrp_time_from_cpuctx(cpuctx, false);
4642 4643 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4643 4644 rotate_ctx(&cpuctx->ctx, cpu_event);
4644 4645 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
@@ -7059,7 +7060,7 @@ static void perf_mmap_close(struct vm_area_struct *vma)
7059 7060 perf_pmu_output_stop(event);
7060 7061
7061 7062 /* now it's safe to free the pages */
7062 - atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
7063 + atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->perf_mlock);
7063 7064 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
7064 7065
7065 7066 /* this has to be the last one */
@@ -7242,11 +7243,11 @@ static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra,
7242 7243 /* Increase the limit linearly with more CPUs */
7243 7244 user_lock_limit *= num_online_cpus();
7244 7245
7245 - user_locked = atomic_long_read(&user->locked_vm);
7246 + user_locked = atomic_long_read(&user->perf_mlock);
7246 7247
7247 7248 /*
7248 7249 * sysctl_perf_event_mlock may have changed, so that
7249 - * user->locked_vm > user_lock_limit
7250 + * user->perf_mlock > user_lock_limit
7250 7251 */
7251 7252 if (user_locked > user_lock_limit)
7252 7253 user_locked = user_lock_limit;
@@ -7254,7 +7255,7 @@ static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra,
7254 7255
7255 7256 if (user_locked > user_lock_limit) {
7256 7257 /*
7257 - * charge locked_vm until it hits user_lock_limit;
7258 + * charge perf_mlock until it hits user_lock_limit;
7258 7259 * charge the rest from pinned_vm
7259 7260 */
7260 7261 *extra = user_locked - user_lock_limit;
@@ -7272,7 +7273,7 @@ static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long
7272 7273 {
7273 7274 struct user_struct *user = current_user();
7274 7275
7275 - atomic_long_add(user_extra, &user->locked_vm);
7276 + atomic_long_add(user_extra, &user->perf_mlock);
7276 7277 atomic64_add(extra, &vma->vm_mm->pinned_vm);
7277 7278 }
7278 7279
@@ -7281,7 +7282,7 @@ static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *
7281 7282 struct user_struct *user = rb->mmap_user;
7282 7283
7283 7284 atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked,
7284 - &user->locked_vm);
7285 + &user->perf_mlock);
7285 7286 atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm);
7286 7287 }
7287 7288
@@ -14394,23 +14395,18 @@ err:
14394 14395 }
14395 14396 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
14396 14397
14397 - static void __perf_pmu_remove(struct perf_event_context *ctx,
14398 - int cpu, struct pmu *pmu,
14399 - struct perf_event_groups *groups,
14398 + static void __perf_pmu_remove(struct perf_event_context *ctx, struct pmu *pmu,
14400 14399 struct list_head *events)
14401 14400 {
14402 - struct perf_event *event, *sibling;
14401 + struct perf_event *event, *tmp;
14402 +
14403 + list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
14404 + if (event->pmu_ctx->pmu != pmu)
14405 + continue;
14403 14406
14404 - perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
14405 14407 perf_remove_from_context(event, 0);
14406 14408 put_pmu_ctx(event->pmu_ctx);
14407 14409 list_add(&event->migrate_entry, events);
14408 -
14409 - for_each_sibling_event(sibling, event) {
14410 - perf_remove_from_context(sibling, 0);
14411 - put_pmu_ctx(sibling->pmu_ctx);
14412 - list_add(&sibling->migrate_entry, events);
14413 - }
14414 14410 }
14415 14411 }
14416 14412
@@ -14486,8 +14482,7 @@ void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
14486 14482 */
14487 14483 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
14488 14484
14489 - __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
14490 - __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
14485 + __perf_pmu_remove(src_ctx, pmu, &events);
14491 14486
14492 14487 if (!list_empty(&events)) {
14493 14488 /*
modified kernel/exit.c
@@ -1729,7 +1729,7 @@ static long do_wait(struct wait_opts *wo)
1729 1729 add_wait_queue(&current->signal->wait_chldexit, &wo->child_wait);
1730 1730
1731 1731 do {
1732 - set_current_state(TASK_INTERRUPTIBLE);
1732 + set_current_state(TASK_INTERRUPTIBLE | TASK_FREEZABLE);
1733 1733 retval = __do_wait(wo);
1734 1734 if (retval != -ERESTARTSYS)
1735 1735 break;
modified kernel/fork.c
@@ -1619,7 +1619,13 @@ static int copy_exec_state(u64 clone_flags, struct task_struct *tsk)
1619 1619 return task_exec_state_copy(tsk);
1620 1620 }
1621 1621
1622 - static int copy_fs(u64 clone_flags, struct task_struct *tsk, bool umh)
1622 + enum copy_fs_flags_t {
1623 + COPY_FS_UMH = (1 << 0),
1624 + COPY_FS_IDLE = (1 << 1),
1625 + };
1626 +
1627 + static int copy_fs(u64 clone_flags, struct task_struct *tsk,
1628 + enum copy_fs_flags_t flags)
1623 1629 {
1624 1630 struct fs_struct *fs;
1625 1631
@@ -1629,19 +1635,20 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk, bool umh)
1629 1635 * filesystem state, or be started from a non-initial mount
1630 1636 * namespace.
1631 1637 */
1632 - if (umh) {
1638 + if (flags & COPY_FS_UMH) {
1633 1639 if (clone_flags & (CLONE_NEWNS | CLONE_FS))
1634 1640 return -EINVAL;
1635 1641 if (current->nsproxy->mnt_ns != &init_mnt_ns)
1636 1642 return -EINVAL;
1637 1643 fs = userspace_init_fs;
1644 + } else if (flags & COPY_FS_IDLE) {
1645 + fs = &init_fs;
1638 1646 } else {
1639 1647 fs = current->fs;
1640 1648 VFS_WARN_ON_ONCE(current->fs != current->real_fs);
1641 1649 }
1642 1650
1643 1651 if (clone_flags & CLONE_FS) {
1644 - /* tsk->fs is already what we want */
1645 1652 read_seqlock_excl(&fs->seq);
1646 1653 /* "users" and "in_exec" locked for check_unsafe_exec() */
1647 1654 if (fs->in_exec) {
@@ -1650,6 +1657,7 @@ static int copy_fs(u64 clone_flags, struct task_struct *tsk, bool umh)
1650 1657 }
1651 1658 fs->users++;
1652 1659 read_sequnlock_excl(&fs->seq);
1660 + tsk->real_fs = tsk->fs = fs;
1653 1661 return 0;
1654 1662 }
1655 1663 tsk->real_fs = tsk->fs = copy_fs_struct(fs);
@@ -2299,7 +2307,9 @@ __latent_entropy struct task_struct *copy_process(
2299 2307 retval = copy_files(clone_flags, p, args->no_files);
2300 2308 if (retval)
2301 2309 goto bad_fork_cleanup_semundo;
2302 - retval = copy_fs(clone_flags, p, args->umh);
2310 + retval = copy_fs(clone_flags, p,
2311 + (args->umh ? COPY_FS_UMH : 0) |
2312 + (args->idle ? COPY_FS_IDLE : 0));
2303 2313 if (retval)
2304 2314 goto bad_fork_cleanup_files;
2305 2315 retval = copy_sighand(clone_flags, p);
@@ -2671,7 +2681,7 @@ struct task_struct * __init fork_idle(int cpu)
2671 2681 {
2672 2682 struct task_struct *task;
2673 2683 struct kernel_clone_args args = {
2674 - .flags = CLONE_VM,
2684 + .flags = CLONE_VM | CLONE_FS,
2675 2685 .fn = &idle_dummy,
2676 2686 .fn_arg = NULL,
2677 2687 .kthread = 1,
@@ -3317,14 +3327,17 @@ int ksys_unshare(unsigned long unshare_flags)
3317 3327 shm_init_task(current);
3318 3328 }
3319 3329
3330 + if (new_fs) {
3331 + new_fs = switch_fs_struct(new_fs);
3332 + if (new_fs)
3333 + free_fs_struct(no_free_ptr(new_fs));
3334 + }
3335 +
3320 3336 if (new_nsproxy) {
3321 3337 switch_task_namespaces(current, new_nsproxy);
3322 3338 new_nsproxy = NULL;
3323 3339 }
3324 3340
3325 - if (new_fs)
3326 - new_fs = switch_fs_struct(new_fs);
3327 -
3328 3341 if (new_fd) {
3329 3342 guard(task_lock)(current);
3330 3343 swap(current->files, new_fd);
@@ -3340,8 +3353,9 @@ int ksys_unshare(unsigned long unshare_flags)
3340 3353 perf_event_namespaces(current);
3341 3354
3342 3355 bad_unshare_cleanup_nsproxy:
3356 + /* never installed, so no active references to drop */
3343 3357 if (new_nsproxy)
3344 - put_nsproxy(new_nsproxy);
3358 + nsproxy_free(new_nsproxy);
3345 3359 bad_unshare_cleanup_cred:
3346 3360 if (new_cred)
3347 3361 put_cred(new_cred);
modified kernel/futex/core.c
@@ -439,45 +439,51 @@ struct hrtimer_sleeper *futex_setup_timer(ktime_t *time, struct hrtimer_sleeper
439 439 }
440 440
441 441 /*
442 - * Generate a machine wide unique identifier for this inode.
442 + * Generate a machine wide unique identifier for this object (inode or mm).
443 443 *
444 444 * This relies on u64 not wrapping in the life-time of the machine; which with
445 445 * 1ns resolution means almost 585 years.
446 - *
447 - * This further relies on the fact that a well formed program will not unmap
448 - * the file while it has a (shared) futex waiting on it. This mapping will have
449 - * a file reference which pins the mount and inode.
450 - *
451 - * If for some reason an inode gets evicted and read back in again, it will get
452 - * a new sequence number and will _NOT_ match, even though it is the exact same
453 - * file.
454 - *
455 - * It is important that futex_match() will never have a false-positive, esp.
456 - * for PI futexes that can mess up the state. The above argues that false-negatives
457 - * are only possible for malformed programs.
458 446 */
459 - static u64 get_inode_sequence_number(struct inode *inode)
447 + static u64 get_object_id(atomic64_t *object_seq)
460 448 {
461 - static atomic64_t i_seq;
449 + static atomic64_t last_assigned_seq;
462 450 u64 old;
463 451
464 - /* Does the inode already have a sequence number? */
465 - old = atomic64_read(&inode->i_sequence);
452 + /* Does the object already have a sequence number? */
453 + old = atomic64_read(object_seq);
466 454 if (likely(old))
467 455 return old;
468 456
469 457 for (;;) {
470 - u64 new = atomic64_inc_return(&i_seq);
458 + u64 new = atomic64_inc_return(&last_assigned_seq);
471 459 if (WARN_ON_ONCE(!new))
472 460 continue;
473 461
474 462 old = 0;
475 - if (!atomic64_try_cmpxchg_relaxed(&inode->i_sequence, &old, new))
463 + if (!atomic64_try_cmpxchg_relaxed(object_seq, &old, new))
476 464 return old;
477 465 return new;
478 466 }
479 467 }
480 468
469 + /*
470 + * This relies on the fact that a well formed program will not unmap
471 + * the file while it has a (shared) futex waiting on it. This mapping will have
472 + * a file reference which pins the mount and inode.
473 + *
474 + * If for some reason an inode gets evicted and read back in again, it will get
475 + * a new sequence number and will _NOT_ match, even though it is the exact same
476 + * file.
477 + *
478 + * It is important that futex_match() will never have a false-positive, esp.
479 + * for PI futexes that can mess up the state. The above argues that false-negatives
480 + * are only possible for malformed programs.
481 + */
482 + static u64 get_inode_sequence_number(struct inode *inode)
483 + {
484 + return get_object_id(&inode->i_sequence);
485 + }
486 +
481 487 /**
482 488 * get_futex_key() - Get parameters which are the keys for a futex
483 489 * @uaddr: virtual address of the futex
@@ -683,8 +689,8 @@ again:
683 689 goto out;
684 690 }
685 691
686 - key->both.offset |= FUT_OFF_MMSHARED; /* ref taken on mm */
687 - key->private.mm = mm;
692 + key->both.offset |= FUT_OFF_MMSHARED;
693 + key->private.mm_seq = get_object_id(&mm->futex.unique_id);
688 694 key->private.address = address;
689 695
690 696 } else {
@@ -2055,13 +2061,12 @@ static void futex_robust_unlock_init_mm(struct futex_mm_data *fd)
2055 2061 static inline void futex_robust_unlock_init_mm(struct futex_mm_data *fd) { }
2056 2062 #endif /* !CONFIG_FUTEX_ROBUST_UNLOCK */
2057 2063
2058 - #if defined(CONFIG_FUTEX_PRIVATE_HASH) || defined(CONFIG_FUTEX_ROBUST_UNLOCK)
2059 2064 void futex_mm_init(struct mm_struct *mm)
2060 2065 {
2066 + atomic64_set(&mm->futex.unique_id, 0);
2061 2067 futex_hash_init_mm(&mm->futex);
2062 2068 futex_robust_unlock_init_mm(&mm->futex);
2063 2069 }
2064 - #endif
2065 2070
2066 2071 int futex_hash_prctl(unsigned long arg2, unsigned long arg3, unsigned long arg4)
2067 2072 {
modified kernel/nsproxy.c
@@ -61,7 +61,7 @@ static inline struct nsproxy *create_nsproxy(void)
61 61 return nsproxy;
62 62 }
63 63
64 - static inline void nsproxy_free(struct nsproxy *ns)
64 + void nsproxy_free(struct nsproxy *ns)
65 65 {
66 66 put_mnt_ns(ns->mnt_ns);
67 67 put_uts_ns(ns->uts_ns);
modified kernel/pid_namespace.c
@@ -268,7 +268,7 @@ void zap_pid_ns_processes(struct pid_namespace *pid_ns)
268 268 * free_pid() will awaken this task.
269 269 */
270 270 for (;;) {
271 - set_current_state(TASK_INTERRUPTIBLE);
271 + set_current_state(TASK_IDLE | TASK_FREEZABLE);
272 272 if (pid_ns->pid_allocated == init_pids)
273 273 break;
274 274 schedule();
modified kernel/printk/nbcon.c
@@ -1887,6 +1887,7 @@ bool nbcon_device_try_acquire(struct console *con)
1887 1887
1888 1888 memset(ctxt, 0, sizeof(*ctxt));
1889 1889 ctxt->console = con;
1890 + /* Keep in sync with nbcon_braille_try_acquire(). */
1890 1891 ctxt->prio = NBCON_PRIO_NORMAL;
1891 1892
1892 1893 if (!nbcon_context_try_acquire(ctxt, false))
@@ -2002,3 +2003,82 @@ void nbcon_kdb_release(struct nbcon_write_context *wctxt)
2002 2003 */
2003 2004 __nbcon_atomic_flush_pending_con(ctxt->console, prb_next_reserve_seq(prb));
2004 2005 }
2006 +
2007 + /**
2008 + * nbcon_write_context_is_braille - Checks whether the nbcon write context
2009 + * is using Braille console
2010 + *
2011 + * @wctxt: checked nbcon write context
2012 + *
2013 + * Return: True when the write context is associated with a Braille console.
2014 + * Otherwise, return false.
2015 + *
2016 + * Context: Can be called in any context but only when Braille console is
2017 + * registered and the struct console could not disappear.
2018 + */
2019 + bool nbcon_write_context_is_braille(struct nbcon_write_context *wctxt)
2020 + {
2021 + struct nbcon_context *ctxt = &ACCESS_PRIVATE(wctxt, ctxt);
2022 + struct console *con = ctxt->console;
2023 +
2024 + return con && con->flags & CON_BRL;
2025 + }
2026 + EXPORT_SYMBOL_GPL(nbcon_write_context_is_braille);
2027 +
2028 + /**
2029 + * nbcon_braille_try_acquire - Try to acquire nbcon console for braille_write()
2030 + *
2031 + * @con: The nbcon console to acquire
2032 + * @wctxt: The nbcon write context to be used on success
2033 + *
2034 + * Context: braille_write() for emitting a single buffer on Braille console.
2035 + *
2036 + * Return: True if the console was acquired. False otherwise.
2037 + *
2038 + * Braille console is not registered as a proper printk consoles. Instead,
2039 + * it is integrated with the graphical virtual terminal.
2040 + *
2041 + * This function is going to synchronize the Braille write against other
2042 + * operations on the used serial port. The port can be used also for a user
2043 + * input but printk() won't emit the messages there directly. It means
2044 + * the other operations will get synchronized using nbcon_device_try_acquire().
2045 + */
2046 + bool nbcon_braille_try_acquire(struct console *con,
2047 + struct nbcon_write_context *wctxt)
2048 + {
2049 + struct nbcon_context *ctxt = &ACCESS_PRIVATE(wctxt, ctxt);
2050 + bool success;
2051 +
2052 + memset(ctxt, 0, sizeof(*ctxt));
2053 + ctxt->console = con;
2054 + /* Keep in sync with nbcon_device_try_acquire(). */
2055 + if (panic_on_this_cpu())
2056 + ctxt->prio = NBCON_PRIO_PANIC;
2057 + else
2058 + ctxt->prio = NBCON_PRIO_NORMAL;
2059 +
2060 + success = nbcon_context_try_acquire(ctxt, false);
2061 + /*
2062 + * Try hard in panic, otherwise the Braille console would
2063 + * miss a text on the related VT.
2064 + */
2065 + if (panic_on_this_cpu() && !success) {
2066 + ctxt->allow_unsafe_takeover = true;
2067 + success = nbcon_context_try_acquire(ctxt, false);
2068 + }
2069 +
2070 + return success;
2071 + }
2072 +
2073 + /**
2074 + * nbcon_braille_release - Release the nbcon console
2075 + *
2076 + * @wctxt: The nbcon write context initialized by a successful
2077 + * nbcon_braille_try_acquire()
2078 + */
2079 + void nbcon_braille_release(struct nbcon_write_context *wctxt)
2080 + {
2081 + struct nbcon_context *ctxt = &ACCESS_PRIVATE(wctxt, ctxt);
2082 +
2083 + nbcon_context_release(ctxt);
2084 + }
modified kernel/printk/printk.c
@@ -3862,7 +3862,7 @@ static int __init printk_set_kthreads_ready(void)
3862 3862
3863 3863 return 0;
3864 3864 }
3865 - early_initcall(printk_set_kthreads_ready);
3865 + subsys_initcall(printk_set_kthreads_ready);
3866 3866 #endif /* CONFIG_PRINTK */
3867 3867
3868 3868 static int __read_mostly keep_bootcon;
modified kernel/rcu/srcutree.c
@@ -704,7 +704,7 @@ void cleanup_srcu_struct(struct srcu_struct *ssp)
704 704 // Call srcu_barrier() before this cleanup_srcu_struct()
705 705 // to avoid triggering this WARN_ON().
706 706 if (WARN_ON(timer_delete_sync(&sdp->delay_work) &&
707 - rcu_segcblist_n_cbs(&sdp->srcu_cblist)) &&
707 + !rcu_segcblist_empty(&sdp->srcu_cblist)) &&
708 708 rcu_cpu_beenfullyonline(sdp->cpu))
709 709 queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);
710 710 flush_work(&sdp->work);
modified kernel/reboot.c
@@ -8,6 +8,7 @@
8 8 #define pr_fmt(fmt) "reboot: " fmt
9 9
10 10 #include <linux/atomic.h>
11 + #include <linux/console.h>
11 12 #include <linux/ctype.h>
12 13 #include <linux/export.h>
13 14 #include <linux/kexec.h>
@@ -94,6 +95,14 @@ void emergency_restart(void)
94 95 {
95 96 kmsg_dump(KMSG_DUMP_EMERG);
96 97 system_state = SYSTEM_RESTART;
98 +
99 + /*
100 + * NBCON kthreads won't be flushed and stopped properly in
101 + * the emergency restart. Move them to the atomic mode.
102 + */
103 + nbcon_cpu_emergency_enter();
104 + printk_trigger_flush();
105 +
97 106 machine_emergency_restart();
98 107 }
99 108 EXPORT_SYMBOL_GPL(emergency_restart);
modified kernel/sched/core.c
@@ -11327,17 +11327,16 @@ void sched_change_end(struct sched_change_ctx *ctx)
11327 11327 if (p->sched_class->switched_to)
11328 11328 p->sched_class->switched_to(rq, p);
11329 11329
11330 + /*
11331 + * Check if the task can preempt the current in case the class
11332 + * was upgraded. Note that none of the switch*_from() methods
11333 + * know the new class and none of the switch*_to() methods know
11334 + * the old class so we must resched here.
11335 + */
11336 + if (ctx->queued)
11337 + wakeup_preempt(rq, p, 0);
11338 +
11330 11339 if (ctx->running) {
11331 - /*
11332 - * If this was a class promotion; let the old class
11333 - * know it got preempted. Note that none of the
11334 - * switch*_from() methods know the new class and none
11335 - * of the switch*_to() methods know the old class.
11336 - */
11337 - if (sched_class_above(p->sched_class, ctx->class)) {
11338 - rq->next_class->wakeup_preempt(rq, p, 0);
11339 - rq->next_class = p->sched_class;
11340 - }
11341 11340 /*
11342 11341 * If this was a degradation in class; make sure to
11343 11342 * reschedule.
modified kernel/sched/ext/ext.c
@@ -1149,6 +1149,10 @@ void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq,
1149 1149
1150 1150 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
1151 1151
1152 + /* @dsq is being destroyed, see free_dsq_irq_workfn() */
1153 + if (unlikely(READ_ONCE(dsq->id) == SCX_DSQ_INVALID))
1154 + return;
1155 +
1152 1156 if (list_empty(&dru->node))
1153 1157 list_move_tail(&dru->node, &rq->scx.deferred_reenq_users);
1154 1158 WRITE_ONCE(dru->flags, dru->flags | reenq_flags);
@@ -2057,8 +2061,14 @@ void scx_do_enqueue_task(struct rq *rq, struct task_struct *p, u64 enq_flags,
2057 2061 if (unlikely(!SCX_HAS_OP(sch, enqueue)))
2058 2062 goto global;
2059 2063
2060 - /* DSQ bypass didn't trigger, enqueue on the BPF scheduler */
2061 - qseq = rq->scx.ops_qseq++ << SCX_OPSS_QSEQ_SHIFT;
2064 + /*
2065 + * DSQ bypass didn't trigger, enqueue on the BPF scheduler. Wrap the
2066 + * per-task qseq counter where the QSEQ field wraps and skip 0, which is
2067 + * what scx_bpf_dsq_insert() records for a task in NONE or DISPATCHING.
2068 + */
2069 + p->scx.ops_qseq = ((p->scx.ops_qseq + 1) &
2070 + (SCX_OPSS_QSEQ_MASK >> SCX_OPSS_QSEQ_SHIFT)) ?: 1;
2071 + qseq = (unsigned long)p->scx.ops_qseq << SCX_OPSS_QSEQ_SHIFT;
2062 2072
2063 2073 WARN_ON_ONCE(atomic_long_read(&p->scx.ops_state) != SCX_OPSS_NONE);
2064 2074 atomic_long_set(&p->scx.ops_state, SCX_OPSS_QUEUEING | qseq);
@@ -2123,8 +2133,8 @@ static void set_task_runnable(struct rq *rq, struct task_struct *p)
2123 2133 }
2124 2134
2125 2135 /*
2126 - * list_add_tail() must be used. scx_bypass() depends on tasks being
2127 - * appended to the runnable_list.
2136 + * list_add_tail() must be used. scx_bypass() and rq_offline_scx()
2137 + * depend on tasks being appended to the runnable_list.
2128 2138 */
2129 2139 list_add_tail(&p->scx.runnable_node, &rq->scx.runnable_list);
2130 2140
@@ -2152,6 +2162,13 @@ static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_
2152 2162 int sticky_cpu = p->scx.sticky_cpu;
2153 2163 u64 enq_flags = core_enq_flags | rq->scx.remote_activate_enq_flags;
2154 2164
2165 + /*
2166 + * An SCX-internal migration ends on arrival. Clear sticky_cpu so @p can
2167 + * leave custody when inserted into the destination DSQ.
2168 + */
2169 + if (sticky_cpu >= 0)
2170 + p->scx.sticky_cpu = -1;
2171 +
2155 2172 /*
2156 2173 * SCX_RQ_IN_WAKEUP promises a task_woken_scx() call once this enqueue
2157 2174 * returns. Only the core's wakeup path delivers one. The flags stashed
@@ -2190,9 +2207,6 @@ static void enqueue_task_scx(struct rq *rq, struct task_struct *p, int core_enq_
2190 2207 dl_server_start(&rq->ext_server);
2191 2208
2192 2209 scx_do_enqueue_task(rq, p, enq_flags, sticky_cpu);
2193 -
2194 - if (sticky_cpu >= 0)
2195 - p->scx.sticky_cpu = -1;
2196 2210 out:
2197 2211 rq->scx.flags &= ~SCX_RQ_IN_WAKEUP;
2198 2212
@@ -2393,11 +2407,14 @@ static void wakeup_preempt_scx(struct rq *rq, struct task_struct *p, int wake_fl
2393 2407 void scx_move_local_task_to_local_dsq(struct scx_sched *sch, struct task_struct *p,
2394 2408 u64 enq_flags, struct rq *dst_rq)
2395 2409 {
2396 - struct scx_dispatch_q *dst_dsq = scx_resolve_local_dsq(sch, dst_rq, p, &enq_flags);
2410 + struct scx_dispatch_q *dst_dsq;
2397 2411
2398 2412 lockdep_assert_rq_held(dst_rq);
2399 2413
2400 2414 WARN_ON_ONCE(p->scx.holding_cpu >= 0);
2415 + scx_wait_dispatching(p);
2416 +
2417 + dst_dsq = scx_resolve_local_dsq(sch, dst_rq, p, &enq_flags);
2401 2418
2402 2419 if (enq_flags & (SCX_ENQ_HEAD | SCX_ENQ_PREEMPT))
2403 2420 dsq_insert_head(dst_dsq, p);
@@ -2577,8 +2594,12 @@ static bool unlink_dsq_and_switch_rq_lock(struct task_struct *p,
2577 2594 switch_rq_lock(locked_rq, src_rq);
2578 2595
2579 2596 /* task_rq couldn't have changed if we're still the holding cpu */
2580 - return likely(p->scx.holding_cpu == cpu) &&
2581 - !WARN_ON_ONCE(src_rq != task_rq(p));
2597 + if (likely(p->scx.holding_cpu == cpu) && !WARN_ON_ONCE(src_rq != task_rq(p))) {
2598 + scx_wait_dispatching(p);
2599 + return true;
2600 + }
2601 +
2602 + return false;
2582 2603 }
2583 2604
2584 2605 static bool consume_remote_task(struct scx_sched *sch, struct rq *this_rq,
@@ -2621,6 +2642,8 @@ static struct rq *move_task_between_dsqs(struct scx_sched *sch,
2621 2642 lockdep_assert_held(&src_dsq->lock);
2622 2643 lockdep_assert_rq_held(src_rq);
2623 2644
2645 + scx_wait_dispatching(p);
2646 +
2624 2647 if (dst_dsq->id == SCX_DSQ_LOCAL) {
2625 2648 dst_rq = container_of(dst_dsq, struct rq, scx.local_dsq);
2626 2649 if (src_rq != dst_rq &&
@@ -3203,8 +3226,7 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3203 3226 /*
3204 3227 * If @p is runnable but we're about to enter a lower
3205 3228 * sched_class, %SCX_OPS_ENQ_LAST must be set. Tell
3206 - * ops.enqueue() that @p is the only one available for this cpu,
3207 - * which should trigger an explicit follow-up scheduling event.
3229 + * ops.enqueue() that @p is the only one available for this cpu.
3208 3230 * This doesn't apply if the baseline access on the CPU is lost.
3209 3231 *
3210 3232 * Under core scheduling, a pick dispatches only when nothing is
@@ -3216,6 +3238,16 @@ static void put_prev_task_scx(struct rq *rq, struct task_struct *p,
3216 3238 WARN_ON_ONCE(!sched_core_enabled(rq) &&
3217 3239 !(sch->ops.flags & SCX_OPS_ENQ_LAST));
3218 3240 scx_do_enqueue_task(rq, p, SCX_ENQ_LAST, -1);
3241 +
3242 + /*
3243 + * A task put on the local DSQ runs, as anywhere else.
3244 + * Here the insert can't reschedule on its own: the pick
3245 + * has settled on @next and @p is still curr, so
3246 + * resched_curr() would flag @p and __schedule() clears
3247 + * that right after the pick. Flag @next instead.
3248 + */
3249 + if (p->scx.dsq == &rq->scx.local_dsq)
3250 + set_tsk_need_resched(next);
3219 3251 } else {
3220 3252 scx_do_enqueue_task(rq, p, 0, -1);
3221 3253 }
@@ -3731,8 +3763,26 @@ static void rq_online_scx(struct rq *rq)
3731 3763
3732 3764 static void rq_offline_scx(struct rq *rq)
3733 3765 {
3766 + struct task_struct *p, *n;
3767 +
3734 3768 rq->scx.flags &= ~SCX_RQ_ONLINE;
3769 +
3770 + /* sched domain rebuilds call rq_offline with the CPU staying alive */
3771 + if (cpu_active(cpu_of(rq)))
3772 + return;
3773 +
3735 3774 scx_rescue_flush(rq);
3775 +
3776 + /*
3777 + * An offline CPU no longer calls ops.dispatch(). Re-enqueue its tasks
3778 + * onto the local DSQ so that they run here and balance_push() moves
3779 + * them off.
3780 + */
3781 + list_for_each_entry_safe_reverse(p, n, &rq->scx.runnable_list, scx.runnable_node) {
3782 + if (p->scx.dsq == &rq->scx.local_dsq)
3783 + continue;
3784 + guard(sched_change)(p, DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK);
3785 + }
3736 3786 }
3737 3787
3738 3788 static bool check_rq_for_timeouts(struct rq *rq)
@@ -4442,11 +4492,12 @@ static bool local_task_should_reenq(struct rq *rq, struct task_struct *p,
4442 4492 }
4443 4493
4444 4494 /*
4445 - * The dispatcher stores the final ops_state after dropping the DSQ lock, so @p
4446 - * can be found on a DSQ while still %SCX_OPSS_DISPATCHING. Reenqueueing @p
4447 - * before that store lands would have it clobber the new %SCX_OPSS_QUEUED.
4495 + * The dispatcher runs ops.dequeue() and stores the final ops_state after
4496 + * dropping the DSQ lock, so @p can be found on a DSQ while still
4497 + * %SCX_OPSS_DISPATCHING. Wait for the dispatch to finish before operating on
4498 + * @p.
4448 4499 */
4449 - void scx_reenq_wait_dispatching(struct task_struct *p)
4500 + void scx_wait_dispatching(struct task_struct *p)
4450 4501 {
4451 4502 if (unlikely(atomic_long_read_acquire(&p->scx.ops_state) == SCX_OPSS_DISPATCHING))
4452 4503 wait_ops_state(p, SCX_OPSS_DISPATCHING);
@@ -4495,7 +4546,7 @@ static u32 reenq_local(struct scx_sched *sch, struct rq *rq, u64 reenq_flags)
4495 4546 if (!local_task_should_reenq(rq, p, &reenq_flags, &reason))
4496 4547 continue;
4497 4548
4498 - scx_reenq_wait_dispatching(p);
4549 + scx_wait_dispatching(p);
4499 4550 scx_dispatch_dequeue(rq, p);
4500 4551
4501 4552 if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
@@ -4619,7 +4670,7 @@ static void reenq_user(struct rq *rq, struct scx_dispatch_q *dsq, u64 reenq_flag
4619 4670 }
4620 4671
4621 4672 /* @p is on @dsq, its rq and @dsq are locked */
4622 - scx_reenq_wait_dispatching(p);
4673 + scx_wait_dispatching(p);
4623 4674 dispatch_dequeue_locked(p, dsq);
4624 4675 raw_spin_unlock(&dsq->lock);
4625 4676
@@ -5143,8 +5194,8 @@ static void exit_dsq(struct scx_dispatch_q *dsq)
5143 5194 struct rq *rq = cpu_rq(cpu);
5144 5195
5145 5196 /*
5146 - * There must have been a RCU grace period since the last
5147 - * insertion and @dsq should be off the deferred list by now.
5197 + * free_dsq_irq_workfn() cancelled the reenqs before the grace
5198 + * period and schedule_dsq_reenq() queues nothing after that.
5148 5199 */
5149 5200 if (WARN_ON_ONCE(!list_empty(&dru->node))) {
5150 5201 guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
@@ -5168,8 +5219,26 @@ static void free_dsq_irq_workfn(struct irq_work *irq_work)
5168 5219 struct llist_node *to_free = llist_del_all(&dsqs_to_free);
5169 5220 struct scx_dispatch_q *dsq, *tmp_dsq;
5170 5221
5171 - llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node)
5222 + llist_for_each_entry_safe(dsq, tmp_dsq, to_free, free_node) {
5223 + s32 cpu;
5224 +
5225 + /*
5226 + * Cancel pending reenqs. Only a run_deferred() that started
5227 + * before the grace period can hold one, and it keeps IRQs off,
5228 + * so the grace period waits for it. After this sweep,
5229 + * schedule_dsq_reenq() sees the invalid id under the same lock
5230 + * and queues nothing.
5231 + */
5232 + for_each_possible_cpu(cpu) {
5233 + struct scx_dsq_pcpu *pcpu = per_cpu_ptr(dsq->pcpu, cpu);
5234 + struct rq *rq = cpu_rq(cpu);
5235 +
5236 + guard(raw_spinlock_irqsave)(&rq->scx.deferred_reenq_lock);
5237 + list_del_init(&pcpu->deferred_reenq_user.node);
5238 + }
5239 +
5172 5240 call_rcu(&dsq->rcu, free_dsq_rcufn);
5241 + }
5173 5242 }
5174 5243
5175 5244 static DEFINE_IRQ_WORK(free_dsq_irq_work, free_dsq_irq_workfn);
@@ -6040,15 +6109,12 @@ static void enable_bypass_dsp(struct scx_sched *sch)
6040 6109
6041 6110 /*
6042 6111 * When a sub-sched bypasses, its tasks are queued on the bypass DSQs of
6043 - * the nearest non-bypassing ancestor or root. As enable_bypass_dsp() is
6044 - * called iff @sch is not already bypassed due to an ancestor bypassing,
6045 - * we can assume that the parent is not bypassing and thus will be the
6046 - * host of the bypass DSQs.
6047 - *
6048 - * While the situation may change in the future, the following
6049 - * guarantees that the nearest non-bypassing ancestor or root has bypass
6050 - * dispatch enabled while a descendant is bypassing, which is all that's
6051 - * required.
6112 + * the nearest non-bypassing ancestor or root. The parent hosts them
6113 + * unless it is bypassing too. Then they sit further up and the parent
6114 + * consumes only its own bypass DSQs, empty until it leaves bypass and
6115 + * becomes the host. Either way the nearest non-bypassing ancestor or
6116 + * root has bypass dispatch enabled while a descendant is bypassing,
6117 + * which is all that's required.
6052 6118 *
6053 6119 * scx_bypass_dsp_enabled() test is used to determine whether to enter
6054 6120 * the bypass dispatch handling path from both bypassing and hosting
@@ -6157,34 +6223,45 @@ void scx_bypass(struct scx_sched *sch, bool bypass)
6157 6223 struct scx_sched *pos;
6158 6224 unsigned long flags;
6159 6225 int cpu;
6226 + bool changed;
6160 6227
6161 6228 raw_spin_lock_irqsave(&scx_bypass_lock, flags);
6162 6229
6163 6230 if (bypass) {
6164 - if (!inc_bypass_depth(sch))
6165 - goto unlock;
6166 -
6167 - enable_bypass_dsp(sch);
6231 + changed = inc_bypass_depth(sch);
6232 + if (changed)
6233 + enable_bypass_dsp(sch);
6168 6234 } else {
6169 - if (!dec_bypass_depth(sch))
6170 - goto unlock;
6235 + changed = dec_bypass_depth(sch);
6171 6236 }
6172 6237
6173 6238 /*
6174 6239 * Bypass state is propagated to all descendants - an scx_sched bypasses
6175 - * if itself or any of its ancestors are in bypass mode.
6240 + * if itself or any of its ancestors are in bypass mode. A descendant's
6241 + * depth is the sum of its own bypasses and its ancestors', so every
6242 + * call propagates whether or not @sch changed state. The descendants'
6243 + * claims are released below with @sch's, after their tasks have moved.
6176 6244 */
6177 6245 raw_spin_lock(&scx_sched_lock);
6178 6246 scx_for_each_descendant_pre(pos, sch) {
6179 6247 if (pos == sch)
6180 6248 continue;
6181 - if (bypass)
6182 - inc_bypass_depth(pos);
6183 - else
6249 + if (bypass) {
6250 + if (inc_bypass_depth(pos))
6251 + enable_bypass_dsp(pos);
6252 + } else {
6184 6253 dec_bypass_depth(pos);
6254 + }
6185 6255 }
6186 6256 raw_spin_unlock(&scx_sched_lock);
6187 6257
6258 + /*
6259 + * A descendant's depth is at least @sch's, so no bypass state changed
6260 + * unless @sch's did.
6261 + */
6262 + if (!changed)
6263 + goto unlock;
6264 +
6188 6265 /*
6189 6266 * No task property is changing. We just need to make sure all currently
6190 6267 * queued tasks are re-queued according to the new scx_bypassing()
@@ -6263,8 +6340,12 @@ void scx_bypass(struct scx_sched *sch, bool bypass)
6263 6340 }
6264 6341
6265 6342 /* disarming must come after moving all tasks out of the bypass DSQs */
6266 - if (!bypass)
6267 - scx_disable_bypass_dsp(sch);
6343 + if (!bypass) {
6344 + guard(raw_spinlock)(&scx_sched_lock);
6345 + scx_for_each_descendant_pre(pos, sch)
6346 + if (!pos->bypass_depth)
6347 + scx_disable_bypass_dsp(pos);
6348 + }
6268 6349 unlock:
6269 6350 raw_spin_unlock_irqrestore(&scx_bypass_lock, flags);
6270 6351 }
@@ -6947,9 +7028,9 @@ static void scx_dump_cpu(struct scx_sched *sch, struct seq_buf *s,
6947 7028 seq_buf_init(&ns, buf, avail);
6948 7029
6949 7030 dump_newline(&ns);
6950 - scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ops_qseq=%lu ksync=%lu",
7031 + scx_dump_line(&ns, "CPU %-4d: nr_run=%u flags=0x%x cpu_rel=%d ksync=%lu",
6951 7032 cpu, rq->scx.nr_running, rq->scx.flags, rq->scx.cpu_released,
6952 - rq->scx.ops_qseq, rq->scx.kick_sync);
7033 + rq->scx.kick_sync);
6953 7034 scx_rescue_dump(&ns, rq);
6954 7035 scx_dump_line(&ns, " curr=%s[%d] class=%ps",
6955 7036 rq->curr->comm, rq->curr->pid, rq->curr->sched_class);
modified kernel/sched/ext/idle.c
@@ -952,12 +952,43 @@ static bool is_bpf_migration_disabled(const struct task_struct *p)
952 952 return p->migration_disabled;
953 953 }
954 954
955 + static s32 select_cpu_restricted(struct task_struct *p, s32 prev_cpu,
956 + const struct cpumask *allowed, u64 flags,
957 + bool migration_disabled)
958 + {
959 + s32 cpu;
960 +
961 + if (migration_disabled)
962 + cpu = task_cpu(p);
963 + else
964 + cpu = cpumask_first(p->cpus_ptr);
965 +
966 + if (!cpumask_test_cpu(cpu, p->cpus_ptr))
967 + return -EBUSY;
968 +
969 + if (allowed && !cpumask_test_cpu(cpu, allowed))
970 + return -EBUSY;
971 +
972 + if (flags & SCX_PICK_IDLE_IN_NODE) {
973 + int node = scx_cpu_node_if_enabled(prev_cpu);
974 +
975 + if (scx_cpu_node_if_enabled(cpu) != node)
976 + return -EBUSY;
977 + }
978 +
979 + if (!scx_idle_test_and_clear_cpu(cpu))
980 + return -EBUSY;
981 +
982 + return cpu;
983 + }
984 +
955 985 static s32 select_cpu_from_kfunc(struct scx_sched *sch, struct task_struct *p,
956 986 s32 prev_cpu, u64 wake_flags,
957 987 const struct cpumask *allowed, u64 flags)
958 988 {
959 989 unsigned long irq_flags;
960 990 bool we_locked = false;
991 + bool migration_disabled;
961 992 s32 cpu;
962 993
963 994 if (!scx_cpu_valid(sch, prev_cpu, NULL))
@@ -994,20 +1025,17 @@ static s32 select_cpu_from_kfunc(struct scx_sched *sch, struct task_struct *p,
994 1025
995 1026 /*
996 1027 * This may also be called from ops.enqueue(), so we need to handle
997 - * per-CPU tasks as well. For these tasks, we can skip all idle CPU
998 - * selection optimizations and simply check whether the previously
999 - * used CPU is idle and within the allowed cpumask.
1028 + * per-CPU tasks as well. For these tasks, skip general idle CPU
1029 + * selection and validate the task's only usable CPU directly.
1000 1030 */
1001 - if (p->nr_cpus_allowed == 1 || is_bpf_migration_disabled(p)) {
1002 - if (cpumask_test_cpu(prev_cpu, allowed ?: p->cpus_ptr) &&
1003 - scx_idle_test_and_clear_cpu(prev_cpu))
1004 - cpu = prev_cpu;
1005 - else
1006 - cpu = -EBUSY;
1007 - } else {
1031 + migration_disabled = is_bpf_migration_disabled(p);
1032 +
1033 + if (p->nr_cpus_allowed == 1 || migration_disabled)
1034 + cpu = select_cpu_restricted(p, prev_cpu, allowed, flags,
1035 + migration_disabled);
1036 + else
1008 1037 cpu = scx_select_cpu_dfl(p, prev_cpu, wake_flags,
1009 1038 allowed ?: p->cpus_ptr, flags);
1010 - }
1011 1039
1012 1040 if (we_locked)
1013 1041 raw_spin_unlock_irqrestore(&p->pi_lock, irq_flags);
modified kernel/sched/ext/inlines.h
@@ -70,7 +70,13 @@ scx_dispatch_sched(struct scx_sched *sch, struct rq *rq,
70 70 #endif /* CONFIG_EXT_SUB_SCHED */
71 71 }
72 72
73 - if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !scx_rq_online(rq))
73 + /*
74 + * scx_rq_online() can't be used. Its cpu_active() test goes false
75 + * before CPU hotplug waits for an RCU grace period, and
76 + * rq_offline_scx() moves this CPU's tasks to the local DSQ only after
77 + * the wait. The grace period can depend on those tasks running.
78 + */
79 + if (unlikely(!SCX_HAS_OP(sch, dispatch)) || !(rq->scx.flags & SCX_RQ_ONLINE))
74 80 return SCX_DSP_NONE;
75 81
76 82 dspc->rq = rq;
modified kernel/sched/ext/internal.h
@@ -1774,8 +1774,9 @@ enum scx_enq_flags {
1774 1774 * %SCX_OPS_ENQ_LAST is specified, they're ops.enqueue()'d with the
1775 1775 * %SCX_ENQ_LAST flag set.
1776 1776 *
1777 - * The BPF scheduler is responsible for triggering a follow-up
1778 - * scheduling event. Otherwise, Execution may stall.
1777 + * If the task is queued on the local DSQ of the CPU it was running on,
1778 + * it continues to run. Otherwise, the CPU goes idle. A scheduler that
1779 + * wants a full dispatch cycle on the CPU should kick it.
1779 1780 */
1780 1781 SCX_ENQ_LAST = 1LLU << 41,
1781 1782
@@ -1998,6 +1999,11 @@ enum scx_ops_state {
1998 1999 * dequeue/requeue, the dispatcher can tell whether it still has a claim
1999 2000 * on the task being dispatched.
2000 2001 *
2002 + * QSEQ is generated from the per-task p->scx.ops_qseq counter so that
2003 + * it doesn't repeat across QUEUED instances of the same task even if
2004 + * the task moves between rqs. 0 is never used as a valid QSEQ since
2005 + * NONE and DISPATCHING map to this value.
2006 + *
2001 2007 * As some 32bit archs can't do 64bit store_release/load_acquire,
2002 2008 * p->scx.ops_state is atomic_long_t which leaves 30 bits for QSEQ on
2003 2009 * 32bit machines. The dispatch race window QSEQ protects is very narrow
@@ -2117,7 +2123,7 @@ void scx_kick_cpu(struct scx_sched *sch, s32 cpu, u64 flags);
2117 2123 u64 __scx_bpf_now(struct rq *rq);
2118 2124 void schedule_dsq_reenq(struct scx_sched *sch, struct scx_dispatch_q *dsq,
2119 2125 u64 reenq_flags, struct rq *locked_rq);
2120 - void scx_reenq_wait_dispatching(struct task_struct *p);
2126 + void scx_wait_dispatching(struct task_struct *p);
2121 2127 int __scx_init_task(struct scx_sched *sch, struct task_struct *p,
2122 2128 struct cgroup *cgrp, bool fork);
2123 2129 void scx_enable_task(struct scx_sched *sch, struct task_struct *p);
modified kernel/sched/ext/sub.c
@@ -585,10 +585,6 @@ void scx_rescue_flush(struct rq *rq)
585 585
586 586 lockdep_assert_rq_held(rq);
587 587
588 - /* sched domain rebuilds call rq_offline with the CPU staying alive */
589 - if (cpu_active(cpu_of(rq)))
590 - return;
591 -
592 588 /* end the current rescue */
593 589 if (rq->scx.rescue.curr)
594 590 scx_task_slice_ended(rq, rq->scx.rescue.curr);
@@ -801,7 +797,7 @@ void scx_reenq_reject(struct rq *rq)
801 797 if (WARN_ON_ONCE(p->migration_pending))
802 798 continue;
803 799
804 - scx_reenq_wait_dispatching(p);
800 + scx_wait_dispatching(p);
805 801 scx_dispatch_dequeue(rq, p);
806 802
807 803 if (WARN_ON_ONCE(p->scx.flags & SCX_TASK_REENQ_REASON_MASK))
modified kernel/sched/fair.c
@@ -6463,12 +6463,20 @@ place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
6463 6463 load = cfs_rq->sum_weight;
6464 6464 if (curr && curr->on_rq)
6465 6465 load += avg_vruntime_weight(cfs_rq, curr->h_load.weight);
6466 -
6467 - weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
6468 - lag *= load + weight;
6469 6466 if (WARN_ON_ONCE(!load))
6470 6467 load = 1;
6471 - lag = div64_long(lag, load);
6468 +
6469 + weight = avg_vruntime_weight(cfs_rq, se->h_load.weight);
6470 +
6471 + /*
6472 + * Rewrite, because the product (W + w_i)*vl'_i might
6473 + * overflow s64:
6474 + *
6475 + * vl_i = (W + w_i)*vl'_i / W
6476 + * = (W*vl'_i + w_i*vl'_i) / W
6477 + * = vl'_i + w_i*vl'_i/W
6478 + */
6479 + lag += div64_long(lag * weight, load);
6472 6480
6473 6481 /*
6474 6482 * A heavy entity (relative to the tree) will pull the
modified kernel/sched/sched.h
@@ -816,7 +816,6 @@ struct scx_rq {
816 816 #endif
817 817 struct list_head runnable_list; /* runnable tasks on this rq */
818 818 struct list_head ddsp_deferred_locals; /* deferred ddsps from enq */
819 - unsigned long ops_qseq;
820 819 /* both stashed across the activate_task() in move_remote_task_to_local_dsq() */
821 820 u64 remote_activate_enq_flags;
822 821 struct scx_sched *remote_activate_sch;
@@ -4222,8 +4221,9 @@ extern void balance_callbacks(struct rq *rq, struct balance_callback *head);
4222 4221 * after which it is enqueued again.
4223 4222 *
4224 4223 * Typically this must be called while holding task_rq_lock, since most/all
4225 - * properties are serialized under those locks. There is currently one
4226 - * exception to this rule in sched/ext which only holds rq->lock.
4224 + * properties are serialized under those locks. There are currently two
4225 + * exceptions to this rule in sched/ext which only hold rq->lock: scx_bypass()
4226 + * and rq_offline_scx().
4227 4227 */
4228 4228
4229 4229 /*
modified kernel/trace/Makefile
@@ -146,11 +146,12 @@ KASAN_SANITIZE_undefsyms_base.o := y
146 146
147 147 UNDEFINED_ALLOWLIST = __asan __gcov __kasan __kcsan __hwasan __sancov __sanitizer __tsan __ubsan __msan \
148 148 __aeabi_unwind_cpp __s390_indirect_jump __x86_indirect_thunk simple_ring_buffer \
149 - $(shell $(NM) -u $(obj)/undefsyms_base.o 2>/dev/null | awk '{print $$2}')
149 + current_thread_info_reg \
150 + $(shell $(NM) -u $(obj)/undefsyms_base.o 2>/dev/null | awk '$$2 {print $$2}')
150 151
151 152 quiet_cmd_check_undefined = NM $<
152 153 cmd_check_undefined = \
153 - undefsyms=$$($(NM) -u $< | grep -v $(addprefix -e , $(UNDEFINED_ALLOWLIST)) || true); \
154 + undefsyms=$$($(NM) -u $< | awk '$$2 {print $$2}' | grep -v $(addprefix -e , $(UNDEFINED_ALLOWLIST)) || true); \
154 155 if [ -n "$$undefsyms" ]; then \
155 156 echo "Unexpected symbols in $<:" >&2; \
156 157 echo "$$undefsyms" >&2; \
modified kernel/trace/ring_buffer.c
@@ -2380,6 +2380,9 @@ int ring_buffer_meta_seq_init(struct file *file, struct trace_buffer *buffer, in
2380 2380 struct seq_file *m;
2381 2381 int ret;
2382 2382
2383 + if (!cpumask_test_cpu(cpu, buffer->cpumask))
2384 + return -ENODEV;
2385 +
2383 2386 ret = seq_open(file, &rb_meta_seq_ops);
2384 2387 if (ret)
2385 2388 return ret;
@@ -2440,22 +2443,33 @@ static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2440 2443 unsigned long nr_pages, struct list_head *pages)
2441 2444 {
2442 2445 struct trace_buffer *buffer = cpu_buffer->buffer;
2446 + unsigned int subbuf_order = buffer->subbuf_order;
2443 2447 struct ring_buffer_cpu_meta *meta = NULL;
2444 2448 struct buffer_page *bpage, *tmp;
2445 - bool user_thread = current->mm != NULL;
2446 2449 struct ring_buffer_desc *desc = NULL;
2450 + bool user_thread = false;
2447 2451 long i;
2448 2452
2449 - /*
2450 - * Check if the available memory is there first.
2451 - * Note, si_mem_available() only gives us a rough estimate of available
2452 - * memory. It may not be accurate. But we don't care, we just want
2453 - * to prevent doing any allocation when it is obvious that it is
2454 - * not going to succeed.
2455 - */
2456 - i = si_mem_available();
2457 - if (i < nr_pages)
2458 - return -ENOMEM;
2453 + if (buffer->range_addr_start) {
2454 + meta = rb_range_meta(buffer, nr_pages, cpu_buffer->cpu);
2455 + } else if (buffer->remote) {
2456 + desc = ring_buffer_desc(buffer->remote->desc, cpu_buffer->cpu);
2457 + if (!desc || WARN_ON(desc->nr_page_va != (nr_pages + 1)))
2458 + return -EINVAL;
2459 + } else {
2460 + /*
2461 + * Check if the available memory is there first.
2462 + * Note, si_mem_available() only gives us a rough estimate of available
2463 + * memory. It may not be accurate. But we don't care, we just want
2464 + * to prevent doing any allocation when it is obvious that it is
2465 + * not going to succeed.
2466 + */
2467 + i = si_mem_available();
2468 + if (i < (nr_pages << subbuf_order))
2469 + return -ENOMEM;
2470 +
2471 + user_thread = current->mm != NULL;
2472 + }
2459 2473
2460 2474 /*
2461 2475 * If a user thread allocates too much, and si_mem_available()
@@ -2469,15 +2483,6 @@ static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2469 2483 if (user_thread)
2470 2484 set_current_oom_origin();
2471 2485
2472 - if (buffer->range_addr_start)
2473 - meta = rb_range_meta(buffer, nr_pages, cpu_buffer->cpu);
2474 -
2475 - if (buffer->remote) {
2476 - desc = ring_buffer_desc(buffer->remote->desc, cpu_buffer->cpu);
2477 - if (!desc || WARN_ON(desc->nr_page_va != (nr_pages + 1)))
2478 - return -EINVAL;
2479 - }
2480 -
2481 2486 for (i = 0; i < nr_pages; i++) {
2482 2487
2483 2488 bpage = alloc_cpu_page(cpu_buffer->cpu);
@@ -2513,12 +2518,11 @@ static int __rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer,
2513 2518 bpage->id = i + 1;
2514 2519 cpu_buffer->subbuf_ids[i + 1] = bpage;
2515 2520 } else {
2516 - bpage->page = alloc_cpu_data(cpu_buffer->cpu,
2517 - cpu_buffer->buffer->subbuf_order);
2521 + bpage->page = alloc_cpu_data(cpu_buffer->cpu, subbuf_order);
2518 2522 if (!bpage->page)
2519 2523 goto free_pages;
2520 2524 }
2521 - bpage->order = cpu_buffer->buffer->subbuf_order;
2525 + bpage->order = subbuf_order;
2522 2526
2523 2527 if (user_thread && fatal_signal_pending(current))
2524 2528 goto free_pages;
@@ -3627,10 +3631,8 @@ static void rb_inc_iter(struct ring_buffer_iter *iter)
3627 3631 /* Return the index into the sub-buffers for a given sub-buffer */
3628 3632 static int rb_meta_subbuf_idx(struct ring_buffer_cpu_meta *meta, void *subbuf)
3629 3633 {
3630 - void *subbuf_array;
3634 + void *subbuf_array = rb_subbufs_from_meta(meta);
3631 3635
3632 - subbuf_array = (void *)meta + sizeof(int) * meta->nr_subbufs;
3633 - subbuf_array = (void *)ALIGN((unsigned long)subbuf_array, meta->subbuf_size);
3634 3636 return (subbuf - subbuf_array) / meta->subbuf_size;
3635 3637 }
3636 3638
@@ -7997,12 +7999,8 @@ consume:
7997 7999 goto out;
7998 8000 }
7999 8001
8000 - /* Did the reader catch up with the writer? */
8001 - if (cpu_buffer->reader_page == cpu_buffer->commit_page)
8002 - goto out;
8003 -
8004 8002 reader = rb_get_reader_page(cpu_buffer);
8005 - if (WARN_ON(!reader))
8003 + if (!reader)
8006 8004 goto out;
8007 8005
8008 8006 /* Check if any events were dropped */
modified kernel/trace/trace.c
@@ -99,6 +99,12 @@ struct tracers {
99 99 struct tracer_flags *flags;
100 100 };
101 101
102 + /*
103 + * Tracers that do not define their own flags use these empty flags,
104 + * as tr->current_trace_flags must never be NULL.
105 + */
106 + static struct tracer_flags no_tracer_flags;
107 +
102 108 /*
103 109 * To prevent the comm cache from being overwritten when no
104 110 * tracing is active, only save the comm when a trace event
@@ -1318,7 +1324,12 @@ static int run_tracer_selftest(struct tracer *type)
1318 1324 tracing_reset_online_cpus(&tr->array_buffer);
1319 1325
1320 1326 tr->current_trace = type;
1321 - tr->current_trace_flags = type->flags ? : type->default_flags;
1327 + if (type->flags)
1328 + tr->current_trace_flags = type->flags;
1329 + else if (type->default_flags)
1330 + tr->current_trace_flags = type->default_flags;
1331 + else
1332 + tr->current_trace_flags = &no_tracer_flags;
1322 1333
1323 1334 #ifdef CONFIG_TRACER_MAX_TRACE
1324 1335 if (tracer_uses_snapshot(type)) {
@@ -5089,7 +5100,12 @@ int tracing_set_tracer(struct trace_array *tr, const char *buf)
5089 5100 return ret;
5090 5101 }
5091 5102
5092 - tr->current_trace_flags = t->flags ? : t->tracer->flags;
5103 + if (t->flags)
5104 + tr->current_trace_flags = t->flags;
5105 + else if (t->tracer->flags)
5106 + tr->current_trace_flags = t->tracer->flags;
5107 + else
5108 + tr->current_trace_flags = &no_tracer_flags;
5093 5109
5094 5110 if (trace->init) {
5095 5111 ret = tracer_init(trace, tr);
@@ -5881,7 +5897,7 @@ static int tracing_buffer_meta_open(struct inode *inode, struct file *filp)
5881 5897
5882 5898 ret = ring_buffer_meta_seq_init(filp, tr->array_buffer.buffer, cpu);
5883 5899 if (ret < 0)
5884 - __trace_array_put(tr);
5900 + trace_array_put(tr);
5885 5901 return ret;
5886 5902 }
5887 5903
@@ -9287,6 +9303,12 @@ static struct notifier_block trace_module_nb = {
9287 9303
9288 9304 static __init void tracer_init_tracefs_work_func(struct work_struct *work)
9289 9305 {
9306 + /*
9307 + * Do not attempt to initialize tracefs if tracing was disabled or
9308 + * failed to allocate
9309 + */
9310 + if (tracing_disabled)
9311 + return;
9290 9312
9291 9313 event_trace_init();
9292 9314
modified kernel/trace/trace_events_filter.c
@@ -482,18 +482,17 @@ predicate_parse(const char *str, int nr_parens, int nr_preds,
482 482 int len;
483 483 int N = 0;
484 484 int i;
485 -
486 - nr_preds += 2; /* For TRUE and FALSE */
485 + int nr_preds_alloc = nr_preds + 2; /* For TRUE and FALSE */
487 486
488 487 op_stack = kmalloc_objs(*op_stack, nr_parens);
489 488 if (!op_stack)
490 489 return ERR_PTR(-ENOMEM);
491 - prog_stack = kzalloc_objs(*prog_stack, nr_preds);
490 + prog_stack = kzalloc_objs(*prog_stack, nr_preds_alloc);
492 491 if (!prog_stack) {
493 492 parse_error(pe, -ENOMEM, 0);
494 493 goto out_free;
495 494 }
496 - inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL);
495 + inverts = kmalloc_array(nr_preds_alloc, sizeof(*inverts), GFP_KERNEL);
497 496 if (!inverts) {
498 497 parse_error(pe, -ENOMEM, 0);
499 498 goto out_free;
@@ -512,7 +511,7 @@ predicate_parse(const char *str, int nr_parens, int nr_preds,
512 511
513 512 switch (*next) {
514 513 case '(': /* #2 */
515 - if (top - op_stack > nr_parens) {
514 + if (top - op_stack >= nr_parens - 1) {
516 515 ret = -EINVAL;
517 516 goto out_free;
518 517 }
modified kernel/trace/trace_events_hist.c
@@ -289,7 +289,7 @@ static u64 hist_field_log2(struct hist_field *hist_field,
289 289
290 290 u64 val = hist_fn_call(operand, elt, buffer, rbe, event);
291 291
292 - return (u64) ilog2(roundup_pow_of_two(val));
292 + return order_base_2(val);
293 293 }
294 294
295 295 static u64 hist_field_bucket(struct hist_field *hist_field,
@@ -873,7 +873,7 @@ static u64 hist_field_timestamp(struct hist_field *hist_field,
873 873 struct hist_trigger_data *hist_data = hist_field->hist_data;
874 874 struct trace_array *tr = hist_data->event_file->tr;
875 875
876 - u64 ts = ring_buffer_event_time_stamp(buffer, rbe);
876 + u64 ts = tracing_event_time_stamp(buffer, rbe);
877 877
878 878 if (hist_data->attrs->ts_in_usecs && trace_clock_in_ns(tr))
879 879 ts = ns2usecs(ts);
@@ -2121,7 +2121,8 @@ static int init_var_ref(struct hist_field *ref_field,
2121 2121 ref_field->size = var_field->size;
2122 2122 ref_field->is_signed = var_field->is_signed;
2123 2123 ref_field->flags |= var_field->flags &
2124 - (HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS);
2124 + (HIST_FIELD_FL_TIMESTAMP | HIST_FIELD_FL_TIMESTAMP_USECS |
2125 + HIST_FIELD_FL_STACKTRACE);
2125 2126
2126 2127 if (system) {
2127 2128 ref_field->system = kstrdup(system, GFP_KERNEL);
@@ -3090,7 +3091,7 @@ create_field_var_hist(struct hist_trigger_data *target_hist_data,
3090 3091 key_field = hist_data->fields[i];
3091 3092 if (!first)
3092 3093 seq_buf_putc(&s, ',');
3093 - seq_buf_puts(&s, key_field->field->name);
3094 + expr_field_str(key_field, &s);
3094 3095 first = false;
3095 3096 }
3096 3097
@@ -3318,6 +3319,7 @@ static struct field_var *create_field_var(struct hist_trigger_data *hist_data,
3318 3319 ret = PTR_ERR(var);
3319 3320 goto err;
3320 3321 }
3322 + var->flags |= val->flags & HIST_FIELD_FL_STACKTRACE;
3321 3323
3322 3324 field_var = kzalloc_obj(struct field_var);
3323 3325 if (!field_var) {
@@ -3946,7 +3948,10 @@ static int check_synth_field(struct synth_event *event,
3946 3948 && field->is_dynamic)
3947 3949 return 0;
3948 3950
3949 - if (strstr(hist_field->type, "long[") && field->is_stack)
3951 + if (!!(hist_field->flags & HIST_FIELD_FL_STACKTRACE) != field->is_stack)
3952 + return -EINVAL;
3953 +
3954 + if (field->is_stack)
3950 3955 return 0;
3951 3956
3952 3957 if (strcmp(field->type, hist_field->type) != 0) {
@@ -4487,7 +4492,8 @@ static int create_var_field(struct hist_trigger_data *hist_data,
4487 4492 if (!ret && hist_data->fields[val_idx]->flags & HIST_FIELD_FL_EXECNAME)
4488 4493 update_var_execname(hist_data->fields[val_idx]);
4489 4494
4490 - if (!ret && hist_data->fields[val_idx]->flags &
4495 + if (!ret && !(hist_data->fields[val_idx]->flags & HIST_FIELD_FL_ALIAS) &&
4496 + hist_data->fields[val_idx]->flags &
4491 4497 (HIST_FIELD_FL_STRING | HIST_FIELD_FL_STACKTRACE))
4492 4498 hist_data->fields[val_idx]->var_str_idx = hist_data->n_var_str++;
4493 4499
@@ -5228,7 +5234,8 @@ static void hist_trigger_elt_update(struct hist_trigger_data *hist_data,
5228 5234 if (hist_field->flags & HIST_FIELD_FL_VAR) {
5229 5235 var_idx = hist_field->var.idx;
5230 5236
5231 - if (hist_field->flags &
5237 + if (!(hist_field->flags & HIST_FIELD_FL_ALIAS) &&
5238 + hist_field->flags &
5232 5239 (HIST_FIELD_FL_STRING | HIST_FIELD_FL_STACKTRACE)) {
5233 5240 unsigned int str_start, var_str_idx, idx;
5234 5241 char *str, *val_str;
modified kernel/trace/trace_probe.c
@@ -2287,7 +2287,6 @@ const char **traceprobe_expand_meta_args(int argc, const char *argv[],
2287 2287 int *new_argc, char *buf, int bufsize,
2288 2288 struct traceprobe_parse_context *ctx)
2289 2289 {
2290 - const struct btf_param *params = NULL;
2291 2290 int i, j, n, used, ret, args_idx = -1;
2292 2291 const char **new_argv __free(kfree) = NULL;
2293 2292
@@ -2305,7 +2304,7 @@ const char **traceprobe_expand_meta_args(int argc, const char *argv[],
2305 2304 if (args_idx != -1) {
2306 2305 /* $arg* requires BTF info */
2307 2306 trace_probe_log_err(0, NOSUP_BTFARG);
2308 - return (const char **)params;
2307 + return ERR_PTR(-EOPNOTSUPP);
2309 2308 }
2310 2309 *new_argc = argc;
2311 2310 return NULL;
modified kernel/trace/trace_snapshot.c
@@ -675,9 +675,12 @@ tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt,
675 675 if (iter->cpu_file != RING_BUFFER_ALL_CPUS)
676 676 return -EINVAL;
677 677 #endif
678 - if (tr->allocated_snapshot)
678 + if (tr->allocated_snapshot) {
679 679 ret = resize_buffer_duplicate_size(&tr->snapshot_buffer,
680 680 &tr->array_buffer, iter->cpu_file);
681 + if (ret < 0)
682 + return ret;
683 + }
681 684
682 685 ret = tracing_arm_snapshot_locked(tr);
683 686 if (ret)
modified kernel/trace/undefsyms_base.c
@@ -9,6 +9,7 @@
9 9
10 10 #include <linux/atomic.h>
11 11 #include <linux/string.h>
12 + #include <asm/local.h>
12 13 #include <asm/page.h>
13 14
14 15 void undefsyms_base(void *p, int n);
@@ -18,11 +19,13 @@ static char page[PAGE_SIZE] __aligned(PAGE_SIZE);
18 19 void undefsyms_base(void *p, int n)
19 20 {
20 21 char buffer[256] = { 0 };
21 -
22 22 u32 u = 0;
23 +
23 24 memset((char * volatile)page, 8, PAGE_SIZE);
24 25 memset((char * volatile)buffer, 8, sizeof(buffer));
25 26 memcpy((void * volatile)p, buffer, sizeof(buffer));
26 27 cmpxchg((u32 * volatile)&u, 0, 8);
28 + cmpxchg((unsigned long *)p, 0, 8);
29 + local_set((local_t *)p, 8);
27 30 WARN_ON(n == 0xdeadbeef);
28 31 }
modified kernel/watch_queue.c
@@ -101,7 +101,7 @@ static bool post_one_notification(struct watch_queue *wqueue,
101 101 struct pipe_inode_info *pipe = wqueue->pipe;
102 102 struct pipe_buffer *buf;
103 103 struct page *page;
104 - unsigned int head, tail, note, offset, len;
104 + unsigned int head, tail, note, offset, len, nr_notes;
105 105 bool done = false;
106 106
107 107 spin_lock_irq(&pipe->rd_wait.lock);
@@ -111,8 +111,10 @@ static bool post_one_notification(struct watch_queue *wqueue,
111 111 if (pipe_full(head, tail, pipe->ring_size))
112 112 goto lost;
113 113
114 - note = find_first_bit(wqueue->notes_bitmap, wqueue->nr_notes);
115 - if (note >= wqueue->nr_notes)
114 + /* Pairs with the smp_store_release() in watch_queue_set_size(). */
115 + nr_notes = smp_load_acquire(&wqueue->nr_notes);
116 + note = find_first_bit(wqueue->notes_bitmap, nr_notes);
117 + if (note >= nr_notes)
116 118 goto lost;
117 119
118 120 page = wqueue->notes[note / WATCH_QUEUE_NOTES_PER_PAGE];
@@ -297,7 +299,8 @@ long watch_queue_set_size(struct pipe_inode_info *pipe, unsigned int nr_notes)
297 299 wqueue->notes = pages;
298 300 wqueue->notes_bitmap = bitmap;
299 301 wqueue->nr_pages = nr_pages;
300 - wqueue->nr_notes = nr_notes;
302 + /* Pairs with the smp_load_acquire() in post_one_notification(). */
303 + smp_store_release(&wqueue->nr_notes, nr_notes);
301 304 return 0;
302 305
303 306 error_p:
modified kernel/workqueue.c
@@ -2290,7 +2290,7 @@ static bool is_chained_work(struct workqueue_struct *wq)
2290 2290 * Return %true iff I'm a worker executing a work item on @wq. If
2291 2291 * I'm @worker, it's safe to dereference it without locking.
2292 2292 */
2293 - return worker && worker->current_pwq->wq == wq;
2293 + return worker && worker->current_pwq && worker->current_pwq->wq == wq;
2294 2294 }
2295 2295
2296 2296 /*
@@ -6320,7 +6320,7 @@ bool current_is_workqueue_mem_reclaim(void)
6320 6320 {
6321 6321 struct worker *worker = current_wq_worker();
6322 6322
6323 - return worker &&
6323 + return worker && worker->current_pwq &&
6324 6324 ((worker->current_pwq->wq->flags &
6325 6325 (WQ_MEM_RECLAIM | __WQ_LEGACY)) == WQ_MEM_RECLAIM);
6326 6326 }
modified lib/Kconfig.debug
@@ -2906,6 +2906,21 @@ config LIVEUPDATE_TEST
2906 2906
2907 2907 If unsure, say N
2908 2908
2909 + config DIMLIB_KUNIT_TEST
2910 + tristate "KUnit test for the DIM library" if !KUNIT_ALL_TESTS
2911 + depends on KUNIT && NET
2912 + select DIMLIB
2913 + default KUNIT_ALL_TESTS
2914 + help
2915 + This builds the KUnit test for the Dynamic Interrupt Moderation
2916 + library (lib/dim/), which checks the rate statistics computed by
2917 + dim_calc_stats().
2918 +
2919 + For more information on KUnit and unit tests in general please refer
2920 + to the KUnit documentation in Documentation/dev-tools/kunit/.
2921 +
2922 + If unsure, say N.
2923 +
2909 2924 config CMDLINE_KUNIT_TEST
2910 2925 tristate "KUnit test for cmdline API" if !KUNIT_ALL_TESTS
2911 2926 depends on KUNIT
modified lib/crypto/arm64/poly1305-armv8.pl
@@ -375,7 +375,7 @@ poly1305_blocks_neon:
375 375 adc $h1,$h1,xzr
376 376 lsr $h2,x14,#24
377 377 adds $h1,$h1,x14,lsl#40
378 - adc $d2,$h2,xzr // can be partially reduced...
378 + adc $h2,$h2,xzr // preserve carry into top limb
379 379
380 380 ldp $d0,$d1,[$inp],#16 // load input
381 381 sub $len,$len,#16
modified lib/crypto/poly1305.c
@@ -78,7 +78,7 @@ void poly1305_final(struct poly1305_desc_ctx *desc, u8 *dst)
78 78 }
79 79
80 80 poly1305_emit(&desc->state.h, dst, desc->s);
81 - *desc = (struct poly1305_desc_ctx){};
81 + memzero_explicit(desc, sizeof(*desc));
82 82 }
83 83 EXPORT_SYMBOL(poly1305_final);
84 84
modified lib/crypto/tests/poly1305_kunit.c
@@ -55,16 +55,17 @@ static int poly1305_suite_init(struct kunit_suite *suite)
55 55 * - Using an all-one-bits r_key tests the key clamping.
56 56 * - Using an all-one-bits s_key tests carries in implementations of the
57 57 * addition mod 2**128 during finalization.
58 - * - Using all-one-bits message, and to a lesser extent r_key, tends to maximize
59 - * any intermediate accumulator values. This increases the chance of
60 - * detecting bugs that occur only in rare cases where the accumulator values
61 - * get very large, for example the bug fixed by commit 678cce4019d746da
62 - * ("crypto: x86/poly1305 - fix overflow during partial reduction").
58 + * - Using all-one-bits message and r_key results in large values for the
59 + * internal products of r_key by (accumulator + message block). This
60 + * increases the chance of detecting bugs that occur only in rare cases where
61 + * the sum of these internal products is very large, for example the bug fixed
62 + * by commit 678cce4019d7 ("crypto: x86/poly1305 - fix overflow during partial
63 + * reduction").
63 64 *
64 - * Accumulator overflow bugs may be specific to particular update lengths (in
65 - * blocks) and/or particular values of the previous acculumator. Note that the
66 - * accumulator starts at 0 which gives the lowest chance of an overflow. Thus,
67 - * a single all-one-bits test vector may be insufficient.
65 + * Bugs with the handling of large internal product sums may be specific to
66 + * particular update lengths (in blocks) and/or require that the accumulator
67 + * also have a large value. Note that the accumulator starts at 0. Thus, a
68 + * single all-one-bits test vector may be insufficient.
68 69 *
69 70 * Considering that, do the following test: continuously update a single
70 71 * Poly1305 context with all-one-bits data of varying lengths (0, 16, 32, ...,
@@ -141,10 +142,88 @@ static void test_poly1305_reduction_edge_cases(struct kunit *test)
141 142 }
142 143 }
143 144
145 + /*
146 + * Test that Poly1305 MACs are computed correctly when r_key=1, s_key=0, and the
147 + * message consists of all-ones blocks.
148 + *
149 + * With r_key=1 and s_key=0, Poly1305 degrades to the sum of the padded blocks
150 + * mod 2**130 - 5, then reduced mod 2**128. A padded all-ones block maps to
151 + * 2**128 + (2**128 - 1) = 2**129 - 1. Two such blocks sum to 2**130 - 2, which
152 + * is congruent to 3 mod 2**130 - 5. Thus, the expected MAC is just 3 *
153 + * floor(nblocks / 2), minus 1 if nblocks is odd, then reduced mod 2**128. If
154 + * nblocks == 1 this is 2**128 - 1, otherwise it's just a small integer.
155 + *
156 + * Inside the Poly1305 implementation in this case, the multiplication does
157 + * nothing and each block just adds 2**129 - 1 to the accumulator. Without the
158 + * multiplication to mix things up, this results in some interesting values
159 + * being reached where the limbs are at or near their maximum values, even after
160 + * (lazy) reduction. This can reproduce bugs that happen only in such cases.
161 + *
162 + * For example, this test case reproduces the bug fixed by commit 24f07e8c07a0
163 + * ("lib/crypto: arm64: Fix lost Poly1305 carry when resuming NEON state").
164 + *
165 + * However, reaching that bug required two consecutive updates: one with >= 8
166 + * blocks to cause NEON code to be used and leave the accumulator in base 2**26
167 + * with its limbs in a certain pattern, then one with an odd number of blocks >=
168 + * 9 to cause NEON to be used again, but first processing one block using scalar
169 + * code as a special case, triggering a conversion to base 2**64 where the carry
170 + * into the 2**128 bit was lost. To cover this and other similar edge cases
171 + * that may exist in other Poly1305 implementations, just test all possible
172 + * block-aligned splits between three poly1305_update() calls.
173 + */
174 + static void test_poly1305_split_update_carry(struct kunit *test)
175 + {
176 + static const u8 key[POLY1305_KEY_SIZE] = { 1 }; /* r_key=1, s_key=0 */
177 + /*
178 + * Use max_nblocks=66 so that it's a bit more than twice the AVX-512
179 + * threshold of 32 blocks.
180 + */
181 + const int max_nblocks = 66;
182 + u8 *data = alloc_buf(test, max_nblocks * POLY1305_BLOCK_SIZE);
183 + u8 expected_mac[POLY1305_DIGEST_SIZE];
184 + u8 actual_mac[POLY1305_DIGEST_SIZE];
185 + struct poly1305_desc_ctx ctx;
186 +
187 + KUNIT_ASSERT_LE(test, 3 * (max_nblocks / 2), U8_MAX);
188 +
189 + memset(data, 0xff, max_nblocks * POLY1305_BLOCK_SIZE);
190 +
191 + for (int nblocks = 0; nblocks <= max_nblocks; nblocks++) {
192 + size_t len = nblocks * POLY1305_BLOCK_SIZE;
193 +
194 + expected_mac[0] = 3 * (nblocks / 2) - (nblocks % 2);
195 + memset(&expected_mac[1], nblocks == 1 ? 0xff : 0,
196 + POLY1305_DIGEST_SIZE - 1);
197 + for (size_t part1_len = 0; part1_len <= len;
198 + part1_len += POLY1305_BLOCK_SIZE) {
199 + for (size_t part2_len = 0; part2_len <= len - part1_len;
200 + part2_len += POLY1305_BLOCK_SIZE) {
201 + size_t part3_len = len - part1_len - part2_len;
202 +
203 + poly1305_init(&ctx, key);
204 + poly1305_update(&ctx, data, part1_len);
205 + poly1305_update(&ctx, &data[part1_len],
206 + part2_len);
207 + poly1305_update(&ctx,
208 + &data[part1_len + part2_len],
209 + part3_len);
210 + poly1305_final(&ctx, actual_mac);
211 + KUNIT_ASSERT_MEMEQ_MSG(
212 + test, actual_mac, expected_mac,
213 + POLY1305_DIGEST_SIZE,
214 + "Failed with nblocks=%d, part1_len=%zu, part2_len=%zu, part3_len=%zu",
215 + nblocks, part1_len, part2_len,
216 + part3_len);
217 + }
218 + }
219 + }
220 + }
221 +
144 222 static struct kunit_case poly1305_test_cases[] = {
145 223 HASH_KUNIT_CASES,
146 224 KUNIT_CASE(test_poly1305_allones_keys_and_message),
147 225 KUNIT_CASE(test_poly1305_reduction_edge_cases),
226 + KUNIT_CASE(test_poly1305_split_update_carry),
148 227 KUNIT_CASE(benchmark_hash),
149 228 {},
150 229 };
modified lib/dim/Makefile
@@ -5,3 +5,5 @@
5 5 obj-$(CONFIG_DIMLIB) += dimlib.o
6 6
7 7 dimlib-y := dim.o net_dim.o rdma_dim.o
8 +
9 + obj-$(CONFIG_DIMLIB_KUNIT_TEST) += dim_kunit.o
modified lib/dim/dim.c
@@ -69,11 +69,15 @@ bool dim_calc_stats(const struct dim_sample *start,
69 69 if (!delta_us)
70 70 return false;
71 71
72 - curr_stats->ppms = DIV_ROUND_UP(npkts * USEC_PER_MSEC, delta_us);
73 - curr_stats->bpms = DIV_ROUND_UP(nbytes * USEC_PER_MSEC, delta_us);
72 + /* u32 * USEC_PER_MSEC overflows a 32-bit long */
73 + curr_stats->ppms = DIV_ROUND_UP_ULL((u64)npkts * USEC_PER_MSEC,
74 + delta_us);
75 + curr_stats->bpms = DIV_ROUND_UP_ULL((u64)nbytes * USEC_PER_MSEC,
76 + delta_us);
74 77 curr_stats->epms = DIV_ROUND_UP(DIM_NEVENTS * USEC_PER_MSEC,
75 78 delta_us);
76 - curr_stats->cpms = DIV_ROUND_UP(ncomps * USEC_PER_MSEC, delta_us);
79 + curr_stats->cpms = DIV_ROUND_UP_ULL((u64)ncomps * USEC_PER_MSEC,
80 + delta_us);
77 81 if (curr_stats->epms != 0)
78 82 curr_stats->cpe_ratio = DIV_ROUND_DOWN_ULL(
79 83 curr_stats->cpms * 100, curr_stats->epms);
added lib/dim/dim_kunit.c mode 100644
@@ -0,0 +1,126 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * KUnit tests for the Dynamic Interrupt Moderation library
4 + */
5 +
6 + #include <kunit/test.h>
7 + #include <linux/dim.h>
8 + #include <linux/ktime.h>
9 + #include <linux/module.h>
10 +
11 + struct dim_calc_stats_case {
12 + const char *name;
13 + u32 delta_us;
14 + u32 start_pkts, end_pkts;
15 + u32 start_bytes, end_bytes;
16 + u32 start_comps, end_comps;
17 + int ppms, bpms, cpms;
18 + };
19 +
20 + static const struct dim_calc_stats_case dim_calc_stats_cases[] = {
21 + {
22 + .name = "small",
23 + .delta_us = 1000,
24 + .end_pkts = 640, .end_bytes = 640 * 1500, .end_comps = 64,
25 + .ppms = 640, .bpms = 960000, .cpms = 64,
26 + },
27 + {
28 + .name = "round_up",
29 + .delta_us = 3000,
30 + .end_pkts = 10, .end_bytes = 10, .end_comps = 1,
31 + .ppms = 4, .bpms = 4, .cpms = 1,
32 + },
33 + {
34 + .name = "counter_wrap",
35 + .delta_us = 1000,
36 + .start_pkts = 0xffffff00, .end_pkts = 0x100,
37 + .start_bytes = 0xfffff000, .end_bytes = 0x1000,
38 + .start_comps = 0xfffffff0, .end_comps = 0x10,
39 + .ppms = 0x200, .bpms = 0x2000, .cpms = 0x20,
40 + },
41 + {
42 + /* 30 MB in 10 ms (24 Gbit/s): nbytes * 1000 exceeds 32 bits */
43 + .name = "many_bytes",
44 + .delta_us = 10000,
45 + .end_pkts = 20000, .end_bytes = 30000000, .end_comps = 64,
46 + .ppms = 2000, .bpms = 3000000, .cpms = 7,
47 + },
48 + {
49 + /* 4.3 MB in 16 ms (2.15 Gbit/s), just above the 32-bit limit */
50 + .name = "bytes_32bit_limit",
51 + .delta_us = 16000,
52 + .end_pkts = 2900, .end_bytes = 4300000, .end_comps = 64,
53 + .ppms = 182, .bpms = 268750, .cpms = 4,
54 + },
55 + {
56 + /* 5 MB in 40 ms: a 1 Gbit/s link at line rate */
57 + .name = "gigabit",
58 + .delta_us = 40000,
59 + .end_pkts = 3300, .end_bytes = 5000000, .end_comps = 64,
60 + .ppms = 83, .bpms = 125000, .cpms = 2,
61 + },
62 + {
63 + /* 5 million packets and completions in 2 s */
64 + .name = "many_packets",
65 + .delta_us = 2000000,
66 + .end_pkts = 5000000, .end_bytes = 5000000, .end_comps = 5000000,
67 + .ppms = 2500, .bpms = 2500, .cpms = 2500,
68 + },
69 + };
70 +
71 + static void dim_calc_stats_case_desc(const struct dim_calc_stats_case *t,
72 + char *desc)
73 + {
74 + strscpy(desc, t->name, KUNIT_PARAM_DESC_SIZE);
75 + }
76 +
77 + KUNIT_ARRAY_PARAM(dim_calc_stats, dim_calc_stats_cases,
78 + dim_calc_stats_case_desc);
79 +
80 + static void dim_calc_stats_test(struct kunit *test)
81 + {
82 + const struct dim_calc_stats_case *t = test->param_value;
83 + struct dim_sample start = {}, end = {};
84 + struct dim_stats stats = {};
85 +
86 + dim_update_sample_with_comps(0, t->start_pkts, t->start_bytes,
87 + t->start_comps, &start);
88 + dim_update_sample_with_comps(DIM_NEVENTS, t->end_pkts, t->end_bytes,
89 + t->end_comps, &end);
90 + /* dim_update_sample() stamps ktime_get(); use fixed times instead */
91 + start.time = ktime_set(1000, 0);
92 + end.time = ktime_add_us(start.time, t->delta_us);
93 +
94 + KUNIT_ASSERT_TRUE(test, dim_calc_stats(&start, &end, &stats));
95 + KUNIT_EXPECT_EQ(test, stats.ppms, t->ppms);
96 + KUNIT_EXPECT_EQ(test, stats.bpms, t->bpms);
97 + KUNIT_EXPECT_EQ(test, stats.cpms, t->cpms);
98 + KUNIT_EXPECT_EQ(test, stats.epms,
99 + (int)DIV_ROUND_UP(DIM_NEVENTS * USEC_PER_MSEC,
100 + t->delta_us));
101 + }
102 +
103 + static void dim_calc_stats_no_time_test(struct kunit *test)
104 + {
105 + struct dim_sample sample = {};
106 + struct dim_stats stats = {};
107 +
108 + dim_update_sample_with_comps(0, 100, 1000, 10, &sample);
109 + KUNIT_EXPECT_FALSE(test, dim_calc_stats(&sample, &sample, &stats));
110 + }
111 +
112 + static struct kunit_case dim_test_cases[] = {
113 + KUNIT_CASE_PARAM(dim_calc_stats_test, dim_calc_stats_gen_params),
114 + KUNIT_CASE(dim_calc_stats_no_time_test),
115 + {}
116 + };
117 +
118 + static struct kunit_suite dim_test_suite = {
119 + .name = "dim",
120 + .test_cases = dim_test_cases,
121 + };
122 +
123 + kunit_test_suite(dim_test_suite);
124 +
125 + MODULE_DESCRIPTION("KUnit tests for the DIM library");
126 + MODULE_LICENSE("GPL");
modified mm/mremap.c
@@ -1037,6 +1037,7 @@ static void vrm_stat_account(struct vma_remap_struct *vrm,
1037 1037 }
1038 1038
1039 1039 static bool __check_map_count_against_split(struct mm_struct *mm,
1040 + bool pre_split,
1040 1041 bool before_unmaps)
1041 1042 {
1042 1043 const int sys_map_count = get_sysctl_max_map_count();
@@ -1088,26 +1089,42 @@ static bool __check_map_count_against_split(struct mm_struct *mm,
1088 1089 * Therefore we must check to ensure we have headroom of 2 additional
1089 1090 * VMAs.
1090 1091 */
1091 - return map_count + 2 <= sys_map_count;
1092 + map_count += 2;
1093 +
1094 + /* If pre-split, the -1 observed above doesn't apply. */
1095 + if (pre_split)
1096 + map_count++;
1097 +
1098 + return map_count <= sys_map_count;
1099 + }
1100 +
1101 + static bool needs_pre_split(struct vma_remap_struct *vrm)
1102 + {
1103 + /*
1104 + * An MREMAP_DONTUNMAP of a mlock()'d VMA needs to unlock the
1105 + * source VMA, so split in this case.
1106 + */
1107 + return (vrm->flags & MREMAP_DONTUNMAP) &&
1108 + vma_test(vrm->vma, VMA_LOCKED_BIT);
1092 1109 }
1093 1110
1094 1111 /* Do we violate the map count limit if we split VMAs when moving the VMA? */
1095 - static bool check_map_count_against_split(void)
1112 + static bool check_map_count_against_split(struct vma_remap_struct *vrm)
1096 1113 {
1097 1114 return __check_map_count_against_split(current->mm,
1098 - /*before_unmaps=*/false);
1115 + needs_pre_split(vrm), /*before_unmaps=*/false);
1099 1116 }
1100 1117
1101 1118 /* Do we violate the map count limit if we split VMAs prior to early unmaps? */
1102 - static bool check_map_count_against_split_early(void)
1119 + static bool check_map_count_against_split_early(struct vma_remap_struct *vrm)
1103 1120 {
1104 1121 return __check_map_count_against_split(current->mm,
1105 - /*before_unmaps=*/true);
1122 + vrm->flags & MREMAP_DONTUNMAP, /*before_unmaps=*/true);
1106 1123 }
1107 1124
1108 1125 /*
1109 - * Perform checks before attempting to write a VMA prior to it being
1110 - * moved.
1126 + * Perform checks and preparation before attempting to write a VMA prior to it
1127 + * being moved.
1111 1128 */
1112 1129 static unsigned long prep_move_vma(struct vma_remap_struct *vrm)
1113 1130 {
@@ -1116,19 +1133,17 @@ static unsigned long prep_move_vma(struct vma_remap_struct *vrm)
1116 1133 unsigned long old_addr = vrm->addr;
1117 1134 unsigned long old_len = vrm->old_len;
1118 1135 vm_flags_t dummy = vma->vm_flags;
1136 + const bool split_before = vma->vm_start != old_addr;
1137 + const bool split_after = vma->vm_end != old_addr + old_len;
1119 1138
1120 - /*
1121 - * We'd prefer to avoid failure later on in do_munmap: we copy a VMA,
1122 - * which may not merge, then (if MREMAP_DONTUNMAP is not set) unmap the
1123 - * source, which may split, causing a net increase of 2 mappings.
1124 - */
1125 - if (!check_map_count_against_split())
1139 + /* Avoid failure later on. */
1140 + if (!check_map_count_against_split(vrm))
1126 1141 return -ENOMEM;
1127 1142
1128 1143 if (vma->vm_ops && vma->vm_ops->may_split) {
1129 - if (vma->vm_start != old_addr)
1144 + if (split_before)
1130 1145 err = vma->vm_ops->may_split(vma, old_addr);
1131 - if (!err && vma->vm_end != old_addr + old_len)
1146 + if (!err && split_after)
1132 1147 err = vma->vm_ops->may_split(vma, old_addr + old_len);
1133 1148 if (err)
1134 1149 return err;
@@ -1146,6 +1161,21 @@ static unsigned long prep_move_vma(struct vma_remap_struct *vrm)
1146 1161 if (err)
1147 1162 return err;
1148 1163
1164 + /*
1165 + * To account mlock()'d pages correctly in the MREMAP_DONTUNMAP
1166 + * case perform any split ahead of time for an mlock()'d VMA.
1167 + */
1168 + if (needs_pre_split(vrm)) {
1169 + VMA_ITERATOR(vmi, vma->vm_mm, old_addr);
1170 +
1171 + if (split_before)
1172 + err = split_vma(&vmi, vma, old_addr, 1);
1173 + if (!err && split_after)
1174 + err = split_vma(&vmi, vma, old_addr + old_len, 0);
1175 + vrm->vmi_needs_invalidate = true;
1176 + return err;
1177 + }
1178 +
1149 1179 return 0;
1150 1180 }
1151 1181
@@ -1275,7 +1305,8 @@ static int copy_vma_and_data(struct vma_remap_struct *vrm,
1275 1305 PAGETABLE_MOVE(pmc, NULL, NULL, vrm->addr, vrm->new_addr, vrm->old_len);
1276 1306
1277 1307 new_vma = copy_vma(&vma, vrm->new_addr, vrm->new_len, new_pgoff,
1278 - new_anon_pgoff, &pmc.need_rmap_locks);
1308 + new_anon_pgoff, &pmc.need_rmap_locks,
1309 + vrm->flags & MREMAP_DONTUNMAP);
1279 1310 if (!new_vma) {
1280 1311 vrm_uncharge(vrm);
1281 1312 *new_vma_ptr = NULL;
@@ -1335,6 +1366,9 @@ static void dontunmap_complete(struct vma_remap_struct *vrm,
1335 1366 unsigned long old_start = vma->vm_start;
1336 1367 unsigned long old_end = vma->vm_end;
1337 1368
1369 + /* Self-merge is disallowed. */
1370 + VM_WARN_ON_ONCE(new_vma == vma);
1371 +
1338 1372 /* We always clear VMA_LOCKED[ONFAULT]_BIT on the old VMA. */
1339 1373 vma_clear_flags_mask(vma, VMA_LOCKED_MASK);
1340 1374
@@ -1342,7 +1376,7 @@ static void dontunmap_complete(struct vma_remap_struct *vrm,
1342 1376 * anon_vma links of the old vma is no longer needed after its page
1343 1377 * table has been moved.
1344 1378 */
1345 - if (new_vma != vma && start == old_start && end == old_end) {
1379 + if (start == old_start && end == old_end) {
1346 1380 const pgoff_t pgoff_unfaulted = vma->vm_start >> PAGE_SHIFT;
1347 1381
1348 1382 unlink_anon_vmas(vma);
@@ -2002,7 +2036,7 @@ static unsigned long do_mremap(struct vma_remap_struct *vrm)
2002 2036 return -EINTR;
2003 2037 vrm->mmap_locked = true;
2004 2038
2005 - if (!check_map_count_against_split_early()) {
2039 + if (!check_map_count_against_split_early(vrm)) {
2006 2040 mmap_write_unlock(mm);
2007 2041 return -ENOMEM;
2008 2042 }
modified mm/pgtable-generic.c
@@ -438,12 +438,30 @@ static void kernel_pgtable_work_func(struct work_struct *work)
438 438 __pagetable_free(pt);
439 439 }
440 440
441 + static void schedule_kernel_pgtable_free(void)
442 + {
443 + schedule_work(&kernel_pgtable_work.work);
444 + }
445 +
441 446 void pagetable_free_kernel(struct ptdesc *pt)
442 447 {
443 448 spin_lock(&kernel_pgtable_work.lock);
444 449 list_add(&pt->pt_list, &kernel_pgtable_work.list);
445 450 spin_unlock(&kernel_pgtable_work.lock);
446 451
447 - schedule_work(&kernel_pgtable_work.work);
452 + /*
453 + * The workqueue may not exist yet while the system is booting.
454 + * kernel_pgtable_drain_early() schedules the work once it does.
455 + */
456 + if (system_state != SYSTEM_BOOTING)
457 + schedule_kernel_pgtable_free();
458 + }
459 +
460 + static int __init kernel_pgtable_drain_early(void)
461 + {
462 + /* Free the kernel page tables queued while booting. */
463 + schedule_kernel_pgtable_free();
464 + return 0;
448 465 }
466 + core_initcall(kernel_pgtable_drain_early);
449 467 #endif
modified mm/vma.c
@@ -634,8 +634,8 @@ out_free_vma:
634 634 * Split a vma into two pieces at address 'addr', a new vma is allocated
635 635 * either for the first part or the tail.
636 636 */
637 - static int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
638 - unsigned long addr, int new_below)
637 + int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
638 + unsigned long addr, int new_below)
639 639 {
640 640 if (vma->vm_mm->map_count >= get_sysctl_max_map_count())
641 641 return -ENOMEM;
@@ -1943,7 +1943,7 @@ static int vma_link(struct mm_struct *mm, struct vm_area_struct *vma)
1943 1943 */
1944 1944 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1945 1945 unsigned long addr, unsigned long len, pgoff_t pgoff,
1946 - pgoff_t anon_pgoff, bool *need_rmap_locks)
1946 + pgoff_t anon_pgoff, bool *need_rmap_locks, bool keep_source)
1947 1947 {
1948 1948 struct vm_area_struct *vma = *vmap;
1949 1949 unsigned long old_vma_start = vma->vm_start;
@@ -1981,6 +1981,21 @@ struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
1981 1981 vmg.pgoff = pgoff;
1982 1982 vmg.anon_pgoff = anon_pgoff;
1983 1983 vmg.next = vma_iter_next_rewind(&vmi, NULL);
1984 +
1985 + /*
1986 + * If the original VMA is kept (MREMAP_DONTUNMAP), the source and
1987 + * destination VMA must be treated distinctly.
1988 + *
1989 + * A merge violates this, so in this case disallow a self-merge.
1990 + */
1991 + if (can_self_merge && keep_source) {
1992 + if (vmg.prev == vma)
1993 + vmg.prev = NULL;
1994 + if (vmg.next == vma)
1995 + vmg.next = NULL;
1996 + can_self_merge = false;
1997 + }
1998 +
1984 1999 new_vma = vma_merge_copied_range(&vmg);
1985 2000
1986 2001 if (new_vma) {
modified mm/vma.h
@@ -535,7 +535,7 @@ void unlink_file_vma_batch_add(struct unlink_vma_file_batch *vb,
535 535
536 536 struct vm_area_struct *copy_vma(struct vm_area_struct **vmap,
537 537 unsigned long addr, unsigned long len, pgoff_t pgoff,
538 - pgoff_t anon_pgoff, bool *need_rmap_locks);
538 + pgoff_t anon_pgoff, bool *need_rmap_locks, bool keep_source);
539 539
540 540 struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *vma);
541 541
@@ -556,6 +556,11 @@ int do_brk_flags(struct vma_iterator *vmi, struct vm_area_struct *brkvma,
556 556 unsigned long unmapped_area(struct vm_unmapped_area_info *info);
557 557 unsigned long unmapped_area_topdown(struct vm_unmapped_area_info *info);
558 558
559 + #ifdef CONFIG_MMU
560 + int split_vma(struct vma_iterator *vmi, struct vm_area_struct *vma,
561 + unsigned long addr, int new_below);
562 + #endif
563 +
559 564 static inline bool vma_wants_manual_pte_write_upgrade(struct vm_area_struct *vma)
560 565 {
561 566 /*
modified net/bluetooth/hci_core.c
@@ -4115,9 +4115,11 @@ static int hci_send_cmd_sync(struct hci_dev *hdev, struct sk_buff *skb)
4115 4115
4116 4116 bt_dev_dbg(hdev, "skb %p", skb);
4117 4117
4118 + hci_dev_lock(hdev);
4118 4119 kfree_skb(hdev->sent_cmd);
4119 4120
4120 4121 hdev->sent_cmd = skb_clone(skb, GFP_KERNEL);
4122 + hci_dev_unlock(hdev);
4121 4123 if (!hdev->sent_cmd) {
4122 4124 skb_queue_head(&hdev->cmd_q, skb);
4123 4125 queue_work(hdev->workqueue, &hdev->cmd_work);
@@ -4138,8 +4140,10 @@ static int hci_send_cmd_sync(struct hci_dev *hdev, struct sk_buff *skb)
4138 4140
4139 4141 if (READ_ONCE(hdev->req_status) == HCI_REQ_PEND &&
4140 4142 !hci_dev_test_and_set_flag(hdev, HCI_CMD_PENDING)) {
4143 + hci_dev_lock(hdev);
4141 4144 kfree_skb(hdev->req_skb);
4142 4145 hdev->req_skb = skb_get(hdev->sent_cmd);
4146 + hci_dev_unlock(hdev);
4143 4147 }
4144 4148
4145 4149 return err;
modified net/bluetooth/hci_sock.c
@@ -1223,8 +1223,10 @@ static int hci_sock_bind(struct socket *sock, struct sockaddr_unsized *addr,
1223 1223 */
1224 1224 hdev = hci_pi(sk)->hdev;
1225 1225 if (hdev && hci_dev_test_flag(hdev, HCI_UNREGISTER)) {
1226 + write_lock(&hci_sk_list.lock);
1226 1227 hci_pi(sk)->hdev = NULL;
1227 1228 sk->sk_state = BT_OPEN;
1229 + write_unlock(&hci_sk_list.lock);
1228 1230 hci_dev_put(hdev);
1229 1231 }
1230 1232 hdev = NULL;
modified net/bluetooth/hci_sync.c
@@ -32,8 +32,10 @@ static void hci_cmd_sync_complete(struct hci_dev *hdev, u8 result, u16 opcode,
32 32 WRITE_ONCE(hdev->req_status, HCI_REQ_DONE);
33 33
34 34 /* Free the request command so it is not used as response */
35 + hci_dev_lock(hdev);
35 36 kfree_skb(hdev->req_skb);
36 37 hdev->req_skb = NULL;
38 + hci_dev_unlock(hdev);
37 39
38 40 if (skb) {
39 41 struct sock *sk = hci_skb_sk(skb);
@@ -3064,15 +3066,21 @@ static int hci_le_set_ext_scan_param_sync(struct hci_dev *hdev, u8 type,
3064 3066 */
3065 3067 if (hci_dev_test_flag(hdev, HCI_PA_SYNC)) {
3066 3068 struct hci_cp_le_add_to_accept_list *sent;
3069 + bdaddr_t bdaddr;
3067 3070
3071 + hci_dev_lock(hdev);
3068 3072 sent = hci_sent_cmd_data(hdev, HCI_OP_LE_ADD_TO_ACCEPT_LIST);
3073 + if (sent)
3074 + bacpy(&bdaddr, &sent->bdaddr);
3075 + hci_dev_unlock(hdev);
3076 +
3069 3077 if (sent) {
3070 3078 struct hci_conn *conn;
3071 3079
3072 3080 rcu_read_lock();
3073 3081
3074 3082 conn = hci_conn_hash_lookup_ba(hdev, PA_LINK,
3075 - &sent->bdaddr);
3083 + &bdaddr);
3076 3084 if (conn) {
3077 3085 struct bt_iso_qos *qos = &conn->iso_qos;
3078 3086
modified net/bluetooth/iso.c
@@ -61,6 +61,7 @@ enum {
61 61 BT_SK_BIG_SYNC,
62 62 BT_SK_PA_SYNC,
63 63 BT_SK_KILLED,
64 + BT_SK_CONNECTING,
64 65 };
65 66
66 67 struct iso_pinfo {
@@ -350,6 +351,9 @@ static int __iso_chan_add(struct iso_conn *conn, struct sock *sk,
350 351 return -EBUSY;
351 352 }
352 353
354 + if (iso_pi(sk)->conn)
355 + return -EISCONN;
356 +
353 357 if (!conn->hcon) {
354 358 BT_ERR("conn->hcon missing");
355 359 return -EIO;
@@ -410,6 +414,11 @@ static int iso_connect_bis(struct sock *sk)
410 414 hci_dev_lock(hdev);
411 415 lock_sock(sk);
412 416
417 + if (iso_pi(sk)->conn) {
418 + err = -EISCONN;
419 + goto unlock;
420 + }
421 +
413 422 if (!bis_capable(hdev)) {
414 423 err = -EOPNOTSUPP;
415 424 goto unlock;
@@ -562,6 +571,13 @@ static int iso_connect_cis(struct sock *sk)
562 571
563 572 lockdep_assert_held(&hcon->hdev->lock);
564 573
574 + /* The socket lock keeps the current attachment and its hcon stable. */
575 + if (iso_pi(sk)->conn && iso_pi(sk)->conn->hcon != hcon) {
576 + hci_conn_drop(hcon);
577 + err = -EISCONN;
578 + goto unlock;
579 + }
580 +
565 581 conn = iso_conn_add(hcon);
566 582 if (!conn) {
567 583 hci_conn_drop(hcon);
@@ -1269,17 +1285,26 @@ static int iso_sock_connect(struct socket *sock, struct sockaddr_unsized *addr,
1269 1285 addr->sa_family != AF_BLUETOOTH)
1270 1286 return -EINVAL;
1271 1287
1272 - if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND)
1273 - return -EBADFD;
1288 + lock_sock(sk);
1274 1289
1275 - if (sk->sk_type != SOCK_SEQPACKET)
1276 - return -EINVAL;
1290 + if ((sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) ||
1291 + test_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags)) {
1292 + err = -EBADFD;
1293 + goto done;
1294 + }
1295 +
1296 + if (sk->sk_type != SOCK_SEQPACKET) {
1297 + err = -EINVAL;
1298 + goto done;
1299 + }
1277 1300
1278 1301 /* Check if the address type is of LE type */
1279 - if (!bdaddr_type_is_le(sa->iso_bdaddr_type))
1280 - return -EINVAL;
1302 + if (!bdaddr_type_is_le(sa->iso_bdaddr_type)) {
1303 + err = -EINVAL;
1304 + goto done;
1305 + }
1281 1306
1282 - lock_sock(sk);
1307 + set_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags);
1283 1308
1284 1309 bacpy(&iso_pi(sk)->dst, &sa->iso_bdaddr);
1285 1310 iso_pi(sk)->dst_type = sa->iso_bdaddr_type;
@@ -1291,16 +1316,18 @@ static int iso_sock_connect(struct socket *sock, struct sockaddr_unsized *addr,
1291 1316 else
1292 1317 err = iso_connect_bis(sk);
1293 1318
1294 - if (err)
1295 - return err;
1296 -
1297 1319 lock_sock(sk);
1298 1320
1321 + clear_bit(BT_SK_CONNECTING, &iso_pi(sk)->flags);
1322 + if (err)
1323 + goto done;
1324 +
1299 1325 if (!test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
1300 1326 err = bt_sock_wait_state(sk, BT_CONNECTED,
1301 1327 sock_sndtimeo(sk, flags & O_NONBLOCK));
1302 1328 }
1303 1329
1330 + done:
1304 1331 release_sock(sk);
1305 1332 return err;
1306 1333 }
@@ -1340,6 +1367,11 @@ static int iso_listen_bis(struct sock *sk)
1340 1367 hci_dev_lock(hdev);
1341 1368 lock_sock(sk);
1342 1369
1370 + if (sk->sk_state != BT_BOUND || iso_pi(sk)->conn) {
1371 + err = -EBADFD;
1372 + goto unlock;
1373 + }
1374 +
1343 1375 /* Fail if user set invalid QoS */
1344 1376 if (iso_pi(sk)->qos_user_set && !check_bcast_qos(&iso_pi(sk)->qos)) {
1345 1377 iso_pi(sk)->qos = default_qos;
modified net/bluetooth/mgmt.c
@@ -1495,7 +1495,7 @@ static void cmd_complete_rsp(struct mgmt_pending_cmd *cmd, void *data)
1495 1495 return;
1496 1496 }
1497 1497
1498 - cmd_status_rsp(cmd, data);
1498 + cmd_status_rsp(cmd, &match->mgmt_status);
1499 1499 }
1500 1500
1501 1501 static int generic_cmd_complete(struct mgmt_pending_cmd *cmd, u8 status)
modified net/bluetooth/rfcomm/core.c
@@ -62,10 +62,9 @@ static void rfcomm_make_uih(struct sk_buff *skb, u8 addr);
62 62
63 63 static void rfcomm_process_connect(struct rfcomm_session *s);
64 64
65 - static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src,
66 - bdaddr_t *dst,
67 - u8 sec_level,
68 - int *err);
65 + static struct socket *rfcomm_session_connect(bdaddr_t *src, bdaddr_t *dst,
66 + u8 sec_level, int *err);
67 + static struct rfcomm_session *rfcomm_session_add(struct socket *sock, int state);
69 68 static struct rfcomm_session *rfcomm_session_get(bdaddr_t *src, bdaddr_t *dst);
70 69 static struct rfcomm_session *rfcomm_session_del(struct rfcomm_session *s);
71 70
@@ -365,28 +364,17 @@ static int rfcomm_check_channel(u8 channel)
365 364 return channel < 1 || channel > 30;
366 365 }
367 366
368 - static int __rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst, u8 channel)
367 + static int __rfcomm_dlc_open(struct rfcomm_dlc *d, struct rfcomm_session *s,
368 + u8 channel)
369 369 {
370 - struct rfcomm_session *s;
371 - int err = 0;
372 370 u8 dlci;
373 371
374 - BT_DBG("dlc %p state %ld %pMR -> %pMR channel %d",
375 - d, d->state, src, dst, channel);
376 -
377 - if (rfcomm_check_channel(channel))
378 - return -EINVAL;
372 + BT_DBG("dlc %p state %ld session %p channel %d",
373 + d, d->state, s, channel);
379 374
380 375 if (d->state != BT_OPEN && d->state != BT_CLOSED)
381 376 return 0;
382 377
383 - s = rfcomm_session_get(src, dst);
384 - if (!s) {
385 - s = rfcomm_session_create(src, dst, d->sec_level, &err);
386 - if (!s)
387 - return err;
388 - }
389 -
390 378 dlci = __dlci(__session_dir(s), channel);
391 379
392 380 /* Check if DLCI already exists */
@@ -421,14 +409,84 @@ static int __rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst,
421 409
422 410 int rfcomm_dlc_open(struct rfcomm_dlc *d, bdaddr_t *src, bdaddr_t *dst, u8 channel)
423 411 {
424 - int r;
412 + struct rfcomm_session *s;
413 + struct socket *sock;
414 + int err;
415 +
416 + BT_DBG("dlc %p state %ld %pMR -> %pMR channel %d",
417 + d, d->state, src, dst, channel);
418 +
419 + if (rfcomm_check_channel(channel))
420 + return -EINVAL;
425 421
426 422 rfcomm_lock();
427 423
428 - r = __rfcomm_dlc_open(d, src, dst, channel);
424 + clear_bit(RFCOMM_CLOSED, &d->flags);
429 425
426 + /* Do not page the remote device for a DLC that cannot be opened
427 + * anyway. __rfcomm_dlc_open() looks at the state again once the
428 + * lock has been re-acquired below.
429 + */
430 + if (d->state != BT_OPEN && d->state != BT_CLOSED) {
431 + rfcomm_unlock();
432 + return 0;
433 + }
434 +
435 + s = rfcomm_session_get(src, dst);
436 + if (s) {
437 + err = __rfcomm_dlc_open(d, s, channel);
438 + rfcomm_unlock();
439 + return err;
440 + }
430 441 rfcomm_unlock();
431 - return r;
442 +
443 + /* There is no session for this pair yet. kernel_connect() ends up in
444 + * l2cap_chan_connect(), which takes hdev->lock, and the HCI event
445 + * path takes rfcomm_mutex while holding hdev->lock, so the socket has
446 + * to be connected with rfcomm_mutex released.
447 + */
448 + sock = rfcomm_session_connect(src, dst, d->sec_level, &err);
449 + if (!sock)
450 + return err;
451 +
452 + rfcomm_lock();
453 +
454 + /* The DLC may have been closed while the socket was connecting. It
455 + * was not on a session, so rfcomm_dlc_close() could only mark it;
456 + * attaching it now would leave it with no owner.
457 + */
458 + if (test_bit(RFCOMM_CLOSED, &d->flags)) {
459 + rfcomm_unlock();
460 + sock_release(sock);
461 + return -ECONNRESET;
462 + }
463 +
464 + /* Another opener may have added a session for the same pair in the
465 + * meantime; that one is used and this socket is dropped.
466 + */
467 + s = rfcomm_session_get(src, dst);
468 + if (!s) {
469 + s = rfcomm_session_add(sock, BT_BOUND);
470 + if (s) {
471 + s->initiator = 1;
472 + sock = NULL;
473 + }
474 + }
475 +
476 + err = s ? __rfcomm_dlc_open(d, s, channel) : -ENOMEM;
477 +
478 + rfcomm_unlock();
479 +
480 + if (sock)
481 + sock_release(sock);
482 +
483 + /* Over an existing ACL link the connection can complete before the
484 + * session reaches the list, and that wakeup is then lost, so let
485 + * krfcommd look at the socket state now.
486 + */
487 + rfcomm_schedule();
488 +
489 + return err;
432 490 }
433 491
434 492 static void __rfcomm_dlc_disconn(struct rfcomm_dlc *d)
@@ -508,8 +566,14 @@ int rfcomm_dlc_close(struct rfcomm_dlc *d, int err)
508 566 rfcomm_lock();
509 567
510 568 s = d->session;
511 - if (!s)
569 + if (!s) {
570 + /* Not on a session yet: rfcomm_dlc_open() may be connecting a
571 + * socket for it with rfcomm_mutex released. Leave a mark so
572 + * that it does not attach the DLC once it holds the lock again.
573 + */
574 + set_bit(RFCOMM_CLOSED, &d->flags);
512 575 goto no_session;
576 + }
513 577
514 578 /* after waiting on the mutex check the session still exists
515 579 * then check the dlc still exists
@@ -757,12 +821,12 @@ static struct rfcomm_session *rfcomm_session_close(struct rfcomm_session *s,
757 821 return rfcomm_session_del(s);
758 822 }
759 823
760 - static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src,
761 - bdaddr_t *dst,
762 - u8 sec_level,
763 - int *err)
824 + /* Creates the L2CAP socket a new session will run on and starts connecting
825 + * it. Must be called with rfcomm_mutex released.
826 + */
827 + static struct socket *rfcomm_session_connect(bdaddr_t *src, bdaddr_t *dst,
828 + u8 sec_level, int *err)
764 829 {
765 - struct rfcomm_session *s = NULL;
766 830 struct sockaddr_l2 addr;
767 831 struct socket *sock;
768 832 struct sock *sk;
@@ -792,24 +856,16 @@ static struct rfcomm_session *rfcomm_session_create(bdaddr_t *src,
792 856 l2cap_pi(sk)->chan->mode = L2CAP_MODE_ERTM;
793 857 release_sock(sk);
794 858
795 - s = rfcomm_session_add(sock, BT_BOUND);
796 - if (!s) {
797 - *err = -ENOMEM;
798 - goto failed;
799 - }
800 -
801 - s->initiator = 1;
802 -
803 859 bacpy(&addr.l2_bdaddr, dst);
804 860 addr.l2_family = AF_BLUETOOTH;
805 861 addr.l2_psm = cpu_to_le16(L2CAP_PSM_RFCOMM);
806 862 addr.l2_cid = 0;
807 863 addr.l2_bdaddr_type = BDADDR_BREDR;
808 864 *err = kernel_connect(sock, (struct sockaddr_unsized *)&addr, sizeof(addr), O_NONBLOCK);
809 - if (*err == 0 || *err == -EINPROGRESS)
810 - return s;
865 + if (*err && *err != -EINPROGRESS)
866 + goto failed;
811 867
812 - return rfcomm_session_del(s);
868 + return sock;
813 869
814 870 failed:
815 871 sock_release(sock);
modified net/bluetooth/rfcomm/sock.c
@@ -48,8 +48,11 @@ static void rfcomm_sock_kill(struct sock *sk);
48 48 static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb)
49 49 {
50 50 struct sock *sk = d->owner;
51 - if (!sk)
51 +
52 + if (!sk) {
53 + kfree_skb(skb);
52 54 return;
55 + }
53 56
54 57 atomic_add(skb->len, &sk->sk_rmem_alloc);
55 58 skb_queue_tail(&sk->sk_receive_queue, skb);
modified net/bluetooth/rfcomm/tty.c
@@ -128,7 +128,7 @@ static void rfcomm_dev_shutdown(struct tty_port *port)
128 128 {
129 129 struct rfcomm_dev *dev = container_of(port, struct rfcomm_dev, port);
130 130
131 - if (dev->tty_dev->parent)
131 + if (dev->tty_dev && dev->tty_dev->parent)
132 132 device_move(dev->tty_dev, NULL, DPM_ORDER_DEV_LAST);
133 133
134 134 /* close the dlc */
modified net/bluetooth/sco.c
@@ -84,12 +84,14 @@ static void sco_conn_free(struct kref *ref)
84 84 if (conn->sk)
85 85 sco_pi(conn->sk)->conn = NULL;
86 86
87 - if (conn->hcon) {
88 - conn->hcon->sco_data = NULL;
89 - hci_conn_drop(conn->hcon);
90 - }
87 + /* hcon->sco_data is cleared and the association's reference on the
88 + * sco_conn is dropped in sco_conn_del() under hdev->lock, and the
89 + * hci_conn is now owned by the socket (held in __sco_chan_add() and
90 + * dropped in sco_chan_del()/sco_sock_destruct()), so there is nothing
91 + * left to release towards hcon here.
92 + */
91 93
92 - /* Ensure no more work items will run since hci_conn has been dropped */
94 + /* Ensure no more work items will run before the connection is freed */
93 95 disable_delayed_work_sync(&conn->timeout_work);
94 96
95 97 kfree(conn);
@@ -188,25 +190,19 @@ static void sco_sock_clear_timer(struct sock *sk)
188 190 }
189 191
190 192 /* ---- SCO connections ---- */
191 - /* Consumes a reference on @hcon, which the returned sco_conn owns until it is
192 - * freed. On failure (NULL return) the reference is left for the caller to drop.
193 + /* Returns a new reference the caller must drop with sco_conn_put(). The
194 + * hcon->sco_data association holds its own reference on the sco_conn for the
195 + * connection's lifetime; it is dropped in sco_conn_del() under hdev->lock.
196 + * @hcon is not consumed: the hci_conn reference is taken and owned by the
197 + * socket in __sco_chan_add().
193 198 */
194 199 static struct sco_conn *sco_conn_add(struct hci_conn *hcon)
195 200 {
196 201 struct sco_conn *conn = hcon->sco_data;
197 202
198 203 conn = sco_conn_hold_unless_zero(conn);
199 - if (conn) {
200 - if (!conn->hcon) {
201 - sco_conn_lock(conn);
202 - conn->hcon = hcon;
203 - sco_conn_unlock(conn);
204 - } else {
205 - /* conn already owns a reference on hcon */
206 - hci_conn_drop(hcon);
207 - }
204 + if (conn)
208 205 return conn;
209 - }
210 206
211 207 conn = kzalloc_obj(struct sco_conn);
212 208 if (!conn)
@@ -227,7 +223,10 @@ static struct sco_conn *sco_conn_add(struct hci_conn *hcon)
227 223
228 224 BT_DBG("hcon %p conn %p", hcon, conn);
229 225
230 - return conn;
226 + /* kref_init() above set the association reference owned by
227 + * hcon->sco_data; hand the caller its own reference.
228 + */
229 + return sco_conn_hold(conn);
231 230 }
232 231
233 232 /* Delete channel.
@@ -242,6 +241,19 @@ static void sco_chan_del(struct sock *sk, int err)
242 241 BT_DBG("sk %p, conn %p, err %d", sk, conn, err);
243 242
244 243 if (conn) {
244 + struct hci_conn *hcon;
245 +
246 + sco_conn_lock(conn);
247 + hcon = conn->hcon;
248 + sco_conn_unlock(conn);
249 +
250 + /* Drop the socket's hci_conn reference BEFORE clearing
251 + * conn->sk, so sco_conn_del() on another CPU cannot free
252 + * the hci_conn while we still hold a pointer to it.
253 + */
254 + if (hcon)
255 + hci_conn_drop(hcon);
256 +
245 257 sco_conn_lock(conn);
246 258 conn->sk = NULL;
247 259 sco_conn_unlock(conn);
@@ -266,6 +278,13 @@ static void sco_conn_del(struct hci_conn *hcon, int err)
266 278
267 279 BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);
268 280
281 + /* Detach from the hci_conn and drop the association's reference.
282 + * The caller holds hdev->lock, which serialises this against the
283 + * read of hcon->sco_data in sco_recv_scodata().
284 + */
285 + hcon->sco_data = NULL;
286 + sco_conn_put(conn);
287 +
269 288 sco_conn_lock(conn);
270 289 sk = sco_sock_hold(conn);
271 290 sco_conn_unlock(conn);
@@ -290,6 +309,11 @@ static void __sco_chan_add(struct sco_conn *conn, struct sock *sk,
290 309 sco_pi(sk)->conn = sco_conn_hold(conn);
291 310 conn->sk = sk;
292 311
312 + /* The socket owns an hci_conn reference for as long as it stays
313 + * attached; it is dropped in sco_chan_del()/sco_sock_destruct().
314 + */
315 + hci_conn_hold(conn->hcon);
316 +
293 317 if (parent)
294 318 bt_accept_enqueue(parent, sk, true);
295 319 }
@@ -371,6 +395,7 @@ static int sco_connect(struct sock *sk)
371 395 if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) {
372 396 release_sock(sk);
373 397 sco_conn_put(conn);
398 + hci_conn_drop(hcon);
374 399 err = -EBADFD;
375 400 goto unlock;
376 401 }
@@ -379,9 +404,13 @@ static int sco_connect(struct sock *sk)
379 404 sco_conn_put(conn);
380 405 if (err) {
381 406 release_sock(sk);
407 + hci_conn_drop(hcon);
382 408 goto unlock;
383 409 }
384 410
411 + /* __sco_chan_add() took its own hci_conn reference; drop ours. */
412 + hci_conn_drop(hcon);
413 +
385 414 /* Update source addr of the socket */
386 415 bacpy(&sco_pi(sk)->src, &hcon->src);
387 416
@@ -495,9 +524,25 @@ static struct sock *sco_get_sock_listen(bdaddr_t *src)
495 524
496 525 static void sco_sock_destruct(struct sock *sk)
497 526 {
527 + struct sco_conn *conn = sco_pi(sk)->conn;
528 +
498 529 BT_DBG("sk %p", sk);
499 530
500 - sco_conn_put(sco_pi(sk)->conn);
531 + /* If the channel was not already torn down via sco_chan_del(), drop
532 + * the socket's own references here.
533 + */
534 + if (conn) {
535 + struct hci_conn *hcon;
536 +
537 + sco_conn_lock(conn);
538 + hcon = conn->hcon;
539 + sco_conn_unlock(conn);
540 +
541 + if (hcon)
542 + hci_conn_drop(hcon);
543 + sco_pi(sk)->conn = NULL;
544 + sco_conn_put(conn);
545 + }
501 546
502 547 skb_queue_purge(&sk->sk_receive_queue);
503 548 skb_queue_purge(&sk->sk_write_queue);
@@ -1511,12 +1556,10 @@ static void sco_connect_cfm(struct hci_conn *hcon, __u8 status)
1511 1556 if (!status) {
1512 1557 struct sco_conn *conn;
1513 1558
1514 - conn = sco_conn_add(hci_conn_hold(hcon));
1559 + conn = sco_conn_add(hcon);
1515 1560 if (conn) {
1516 1561 sco_conn_ready(conn);
1517 1562 sco_conn_put(conn);
1518 - } else {
1519 - hci_conn_drop(hcon);
1520 1563 }
1521 1564 } else
1522 1565 sco_conn_del(hcon, bt_to_errno(status));
modified net/bridge/br_multicast.c
@@ -81,6 +81,10 @@ __br_multicast_add_group(struct net_bridge_mcast *brmctx,
81 81 bool blocked);
82 82 static void br_multicast_find_del_pg(struct net_bridge *br,
83 83 struct net_bridge_port_group *pg);
84 + static void __br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
85 + struct net_bridge_port_group *pg,
86 + struct net_bridge_port_group __rcu **pp,
87 + bool sg_del_exclude_ports);
84 88 static void __br_multicast_stop(struct net_bridge_mcast *brmctx);
85 89
86 90 static int br_mc_disabled_update(struct net_device *dev, bool value,
@@ -458,7 +462,7 @@ static void br_multicast_sg_del_exclude_ports(struct net_bridge_mdb_entry *sgmp)
458 462 for (pp = &sgmp->ports;
459 463 (p = mlock_dereference(*pp, sgmp->br)) != NULL;) {
460 464 if (!(p->flags & MDB_PG_FLAGS_PERMANENT))
461 - br_multicast_del_pg(sgmp, p, pp);
465 + __br_multicast_del_pg(sgmp, p, pp, false);
462 466 else
463 467 pp = &p->next;
464 468 }
@@ -799,9 +803,10 @@ static void br_multicast_destroy_port_group(struct net_bridge_mcast_gc *gc)
799 803 kfree_rcu(pg, rcu);
800 804 }
801 805
802 - void br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
803 - struct net_bridge_port_group *pg,
804 - struct net_bridge_port_group __rcu **pp)
806 + static void __br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
807 + struct net_bridge_port_group *pg,
808 + struct net_bridge_port_group __rcu **pp,
809 + bool sg_del_exclude_ports)
805 810 {
806 811 struct net_bridge *br = pg->key.port->br;
807 812 struct net_bridge_group_src *ent;
@@ -820,7 +825,8 @@ void br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
820 825 if (!br_multicast_is_star_g(&mp->addr)) {
821 826 rhashtable_remove_fast(&br->sg_port_tbl, &pg->rhnode,
822 827 br_sg_port_rht_params);
823 - br_multicast_sg_del_exclude_ports(mp);
828 + if (sg_del_exclude_ports)
829 + br_multicast_sg_del_exclude_ports(mp);
824 830 } else {
825 831 br_multicast_star_g_handle_mode(pg, MCAST_INCLUDE);
826 832 }
@@ -832,6 +838,13 @@ void br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
832 838 mod_timer(&mp->timer, jiffies);
833 839 }
834 840
841 + void br_multicast_del_pg(struct net_bridge_mdb_entry *mp,
842 + struct net_bridge_port_group *pg,
843 + struct net_bridge_port_group __rcu **pp)
844 + {
845 + __br_multicast_del_pg(mp, pg, pp, true);
846 + }
847 +
835 848 static void br_multicast_find_del_pg(struct net_bridge *br,
836 849 struct net_bridge_port_group *pg)
837 850 {
modified net/bridge/netfilter/nf_conntrack_bridge.c
@@ -39,9 +39,13 @@ static int nf_br_ip_fragment(struct net *net, struct sock *sk,
39 39 int err = 0;
40 40
41 41 /* for offloaded checksums cleanup checksum before fragmentation */
42 - if (skb->ip_summed == CHECKSUM_PARTIAL &&
43 - (err = skb_checksum_help(skb)))
44 - goto blackhole;
42 + if (skb->ip_summed == CHECKSUM_PARTIAL) {
43 + err = ip_check_csum_start(skb);
44 + if (!err)
45 + err = skb_checksum_help(skb);
46 + if (err)
47 + goto blackhole;
48 + }
45 49
46 50 iph = ip_hdr(skb);
47 51
modified net/can/af_can.c
@@ -641,13 +641,10 @@ static int can_rcv_filter(struct can_dev_rcv_lists *dev_rcv_lists, struct sk_buf
641 641 return matches;
642 642 }
643 643
644 - void can_set_skb_uid(struct sk_buff *skb)
644 + void can_set_skb_uid(struct can_skb_ext *csx)
645 645 {
646 - /* create non-zero unique skb identifier together with *skb */
647 - while (!(skb->hash))
648 - skb->hash = atomic_inc_return(&skbcounter);
649 -
650 - skb->sw_hash = 1;
646 + while (!(csx->can_skb_uid))
647 + csx->can_skb_uid = atomic_inc_return(&skbcounter);
651 648 }
652 649 EXPORT_SYMBOL(can_set_skb_uid);
653 650
@@ -662,8 +659,6 @@ static void can_receive(struct sk_buff *skb, struct net_device *dev)
662 659 atomic_long_inc(&pkg_stats->rx_frames);
663 660 atomic_long_inc(&pkg_stats->rx_frames_delta);
664 661
665 - can_set_skb_uid(skb);
666 -
667 662 rcu_read_lock();
668 663
669 664 /* deliver the packet to sockets listening on all devices */
@@ -687,8 +682,10 @@ static void can_receive(struct sk_buff *skb, struct net_device *dev)
687 682 static int can_rcv(struct sk_buff *skb, struct net_device *dev,
688 683 struct packet_type *pt, struct net_device *orig_dev)
689 684 {
685 + struct can_skb_ext *csx = can_skb_ext_find(skb);
686 +
690 687 if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
691 - !can_skb_ext_find(skb) || !can_is_can_skb(skb))) {
688 + !csx || !can_is_can_skb(skb))) {
692 689 pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d\n",
693 690 dev->type, skb->len);
694 691
@@ -696,6 +693,14 @@ static int can_rcv(struct sk_buff *skb, struct net_device *dev,
696 693 return NET_RX_DROP;
697 694 }
698 695
696 + /* create unshared CAN skb_extension for netem/mirred skb clones */
697 + csx = skb_ext_add(skb, SKB_EXT_CAN);
698 + if (unlikely(!csx)) {
699 + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM);
700 + return NET_RX_DROP;
701 + }
702 +
703 + can_set_skb_uid(csx);
699 704 can_receive(skb, dev);
700 705 return NET_RX_SUCCESS;
701 706 }
@@ -703,8 +708,10 @@ static int can_rcv(struct sk_buff *skb, struct net_device *dev,
703 708 static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
704 709 struct packet_type *pt, struct net_device *orig_dev)
705 710 {
711 + struct can_skb_ext *csx = can_skb_ext_find(skb);
712 +
706 713 if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
707 - !can_skb_ext_find(skb) || !can_is_canfd_skb(skb))) {
714 + !csx || !can_is_canfd_skb(skb))) {
708 715 pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d\n",
709 716 dev->type, skb->len);
710 717
@@ -712,6 +719,14 @@ static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
712 719 return NET_RX_DROP;
713 720 }
714 721
722 + /* create unshared CAN skb_extension for netem/mirred skb clones */
723 + csx = skb_ext_add(skb, SKB_EXT_CAN);
724 + if (unlikely(!csx)) {
725 + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM);
726 + return NET_RX_DROP;
727 + }
728 +
729 + can_set_skb_uid(csx);
715 730 can_receive(skb, dev);
716 731 return NET_RX_SUCCESS;
717 732 }
@@ -719,8 +734,10 @@ static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
719 734 static int canxl_rcv(struct sk_buff *skb, struct net_device *dev,
720 735 struct packet_type *pt, struct net_device *orig_dev)
721 736 {
737 + struct can_skb_ext *csx = can_skb_ext_find(skb);
738 +
722 739 if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
723 - !can_skb_ext_find(skb) || !can_is_canxl_skb(skb))) {
740 + !csx || !can_is_canxl_skb(skb))) {
724 741 pr_warn_once("PF_CAN: dropped non conform CAN XL skbuff: dev type %d, len %d\n",
725 742 dev->type, skb->len);
726 743
@@ -728,6 +745,14 @@ static int canxl_rcv(struct sk_buff *skb, struct net_device *dev,
728 745 return NET_RX_DROP;
729 746 }
730 747
748 + /* create unshared CAN skb_extension for netem/mirred skb clones */
749 + csx = skb_ext_add(skb, SKB_EXT_CAN);
750 + if (unlikely(!csx)) {
751 + kfree_skb_reason(skb, SKB_DROP_REASON_NOMEM);
752 + return NET_RX_DROP;
753 + }
754 +
755 + can_set_skb_uid(csx);
731 756 can_receive(skb, dev);
732 757 return NET_RX_SUCCESS;
733 758 }
modified net/can/gw.c
@@ -527,6 +527,9 @@ static void can_can_gw_rcv(struct sk_buff *skb, void *data)
527 527 /* put the incremented hop counter in the cloned skb */
528 528 ncsx->can_gw_hops = csx->can_gw_hops + 1;
529 529
530 + /* force a new CAN UID generation for the routed frame */
531 + ncsx->can_skb_uid = 0;
532 +
530 533 /* first processing of this CAN frame -> adjust to private hop limit */
531 534 if (gwj->limit_hops && ncsx->can_gw_hops == 1)
532 535 ncsx->can_gw_hops = max_hops - gwj->limit_hops + 1;
modified net/can/isotp.c
@@ -891,7 +891,7 @@ static void isotp_send_cframe(struct isotp_sock *so)
891 891 csx->can_iif = dev->ifindex;
892 892
893 893 /* set uid in tx skb to identify CF echo frames */
894 - can_set_skb_uid(skb);
894 + can_set_skb_uid(csx);
895 895
896 896 cf = (struct canfd_frame *)skb->data;
897 897 skb_put_zero(skb, so->ll.mtu);
@@ -917,7 +917,7 @@ static void isotp_send_cframe(struct isotp_sock *so)
917 917 pr_notice_once("can-isotp: cfecho is %08X != 0\n", old_cfecho);
918 918
919 919 /* set consecutive frame echo tag */
920 - WRITE_ONCE(so->cfecho, skb->hash);
920 + WRITE_ONCE(so->cfecho, csx->can_skb_uid);
921 921
922 922 /* send frame with local echo enabled */
923 923 can_send_ret = can_send(skb, 1);
@@ -969,18 +969,22 @@ static void isotp_rcv_echo(struct sk_buff *skb, void *data)
969 969 {
970 970 struct sock *sk = (struct sock *)data;
971 971 struct isotp_sock *so = isotp_sk(sk);
972 + struct can_skb_ext *csx = can_skb_ext_find(skb);
972 973
973 974 /* only handle my own local echo CF/SF skb's (no FF!) */
974 975 if (skb->sk != sk)
975 976 return;
976 977
978 + if (WARN_ON_ONCE(!csx))
979 + return;
980 +
977 981 /* unlike isotp_rcv_fc()/isotp_rcv_cf(), not already under so->rx_lock
978 982 * (no isotp_rcv() caller here), so take it ourselves
979 983 */
980 984 spin_lock(&so->rx_lock);
981 985
982 986 /* so->cfecho may since belong to a new transfer; recheck under lock */
983 - if (READ_ONCE(so->cfecho) != skb->hash)
987 + if (READ_ONCE(so->cfecho) != csx->can_skb_uid)
984 988 goto out_unlock;
985 989
986 990 /* cancel local echo timeout */
@@ -1222,7 +1226,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
1222 1226 csx->can_iif = dev->ifindex;
1223 1227
1224 1228 /* set uid in tx skb to identify CF echo frames */
1225 - can_set_skb_uid(skb);
1229 + can_set_skb_uid(csx);
1226 1230
1227 1231 so->tx.len = size;
1228 1232 so->tx.idx = 0;
@@ -1261,7 +1265,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
1261 1265 cf->data[ae] |= size;
1262 1266
1263 1267 /* set CF echo tag for isotp_rcv_echo() (SF-mode) */
1264 - WRITE_ONCE(so->cfecho, skb->hash);
1268 + WRITE_ONCE(so->cfecho, csx->can_skb_uid);
1265 1269 } else {
1266 1270 /* send first frame */
1267 1271
@@ -1278,7 +1282,7 @@ static int isotp_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
1278 1282 so->txfc.bs = 0;
1279 1283
1280 1284 /* set CF echo tag for isotp_rcv_echo() (CF-mode) */
1281 - WRITE_ONCE(so->cfecho, skb->hash);
1285 + WRITE_ONCE(so->cfecho, csx->can_skb_uid);
1282 1286 } else {
1283 1287 /* standard flow control check */
1284 1288 new_state = ISOTP_WAIT_FIRST_FC;
modified net/can/raw.c
@@ -77,7 +77,7 @@ MODULE_ALIAS("can-proto-1");
77 77
78 78 struct uniqframe {
79 79 const struct sk_buff *skb;
80 - u32 hash;
80 + u32 can_skb_uid;
81 81 unsigned int join_rx_count;
82 82 };
83 83
@@ -133,12 +133,16 @@ static void raw_rcv(struct sk_buff *oskb, void *data)
133 133 enum skb_drop_reason reason;
134 134 struct sockaddr_can *addr;
135 135 struct sk_buff *skb;
136 + struct can_skb_ext *csx = can_skb_ext_find(oskb);
136 137 unsigned int *pflags;
137 138
138 139 /* check the received tx sock reference */
139 140 if (!ro->recv_own_msgs && oskb->sk == sk)
140 141 return;
141 142
143 + if (WARN_ON_ONCE(!csx))
144 + return;
145 +
142 146 /* make sure to not pass oversized frames to the socket */
143 147 if (!ro->fd_frames && can_is_canfd_skb(oskb))
144 148 return;
@@ -165,7 +169,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data)
165 169
166 170 /* eliminate multiple filter matches for the same skb */
167 171 if (this_cpu_ptr(ro->uniq)->skb == oskb &&
168 - this_cpu_ptr(ro->uniq)->hash == oskb->hash) {
172 + this_cpu_ptr(ro->uniq)->can_skb_uid == csx->can_skb_uid) {
169 173 if (!ro->join_filters)
170 174 return;
171 175
@@ -175,7 +179,7 @@ static void raw_rcv(struct sk_buff *oskb, void *data)
175 179 return;
176 180 } else {
177 181 this_cpu_ptr(ro->uniq)->skb = oskb;
178 - this_cpu_ptr(ro->uniq)->hash = oskb->hash;
182 + this_cpu_ptr(ro->uniq)->can_skb_uid = csx->can_skb_uid;
179 183 this_cpu_ptr(ro->uniq)->join_rx_count = 1;
180 184 /* drop first frame to check all enabled filters? */
181 185 if (ro->join_filters && ro->count > 1)
modified net/core/dev.c
@@ -10364,13 +10364,15 @@ EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
10364 10364
10365 10365 u8 dev_xdp_sb_prog_count(struct net_device *dev)
10366 10366 {
10367 + struct bpf_prog *prog;
10367 10368 u8 count = 0;
10368 10369 int i;
10369 10370
10370 - for (i = 0; i < __MAX_XDP_MODE; i++)
10371 - if (dev->xdp_state[i].prog &&
10372 - !dev->xdp_state[i].prog->aux->xdp_has_frags)
10371 + for (i = 0; i < __MAX_XDP_MODE; i++) {
10372 + prog = dev_xdp_prog(dev, i);
10373 + if (prog && !prog->aux->xdp_has_frags)
10373 10374 count++;
10375 + }
10374 10376 return count;
10375 10377 }
10376 10378
@@ -10750,11 +10752,12 @@ static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
10750 10752 bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
10751 10753 err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
10752 10754 xdp_link->flags, new_prog);
10755 + if (!err)
10756 + old_prog = xchg(&link->prog, new_prog);
10753 10757 netdev_unlock_ops(xdp_link->dev);
10754 10758 if (err)
10755 10759 goto out_unlock;
10756 10760
10757 - old_prog = xchg(&link->prog, new_prog);
10758 10761 bpf_prog_put(old_prog);
10759 10762
10760 10763 out_unlock:
modified net/core/flow_dissector.c
@@ -1023,6 +1023,8 @@ u32 bpf_flow_dissect(struct bpf_prog *prog, struct bpf_flow_dissector *ctx,
1023 1023
1024 1024 result = bpf_prog_run_pin_on_cpu(prog, ctx);
1025 1025
1026 + /* bpf_flow_keys offsets are u16: do not let @hlen be truncated. */
1027 + hlen = min_t(int, hlen, U16_MAX);
1026 1028 flow_keys->nhoff = clamp_t(u16, flow_keys->nhoff, nhoff, hlen);
1027 1029 flow_keys->thoff = clamp_t(u16, flow_keys->thoff,
1028 1030 flow_keys->nhoff, hlen);
@@ -1071,6 +1073,7 @@ bool __skb_flow_dissect(const struct net *net,
1071 1073 int mpls_lse = 0;
1072 1074 int num_hdrs = 0;
1073 1075 u8 ip_proto = 0;
1076 + u32 thoff;
1074 1077 bool ret;
1075 1078
1076 1079 if (!data) {
@@ -1692,7 +1695,13 @@ out_good:
1692 1695 ret = true;
1693 1696
1694 1697 out:
1695 - key_control->thoff = min_t(u16, nhoff, skb ? skb->len : hlen);
1698 + thoff = min_t(u32, nhoff, skb ? skb->len : hlen);
1699 + if (unlikely(thoff > U16_MAX)) {
1700 + /* Cannot be represented in key_control->thoff. */
1701 + thoff = U16_MAX;
1702 + ret = false;
1703 + }
1704 + key_control->thoff = thoff;
1696 1705 key_basic->n_proto = proto;
1697 1706 key_basic->ip_proto = ip_proto;
1698 1707
modified net/core/skbuff.c
@@ -3633,8 +3633,12 @@ __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3633 3633 pos = copy;
3634 3634 }
3635 3635
3636 - if (!skb_frags_readable(skb))
3636 + if (!skb_frags_readable(skb)) {
3637 + /* Don't hand the caller a buffer with stale bytes in it. */
3638 + if (len > 0)
3639 + memset(to, 0, len);
3637 3640 return 0;
3641 + }
3638 3642
3639 3643 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3640 3644 int end;
modified net/devlink/core.c
@@ -112,13 +112,19 @@ rel_put:
112 112 return;
113 113
114 114 reschedule_work:
115 - schedule_delayed_work(&rel->nested_in.notify_work, 1);
115 + /* The work may have been queued again meanwhile, which took its own
116 + * reference. Drop ours in that case.
117 + */
118 + if (!schedule_delayed_work(&rel->nested_in.notify_work, 1))
119 + __devlink_rel_put(rel);
116 120 }
117 121
118 122 static void devlink_rel_nested_in_notify_work_schedule(struct devlink_rel *rel)
119 123 {
120 124 __devlink_rel_get(rel);
121 - schedule_delayed_work(&rel->nested_in.notify_work, 0);
125 + /* The pending work holds a reference already, drop the new one. */
126 + if (!schedule_delayed_work(&rel->nested_in.notify_work, 0))
127 + __devlink_rel_put(rel);
122 128 }
123 129
124 130 static struct devlink_rel *devlink_rel_alloc(void)
modified net/ipv4/af_inet.c
@@ -161,7 +161,7 @@ void inet_sock_destruct(struct sock *sk)
161 161 WARN_ON_ONCE(sk->sk_wmem_queued);
162 162 WARN_ON_ONCE(sk->sk_forward_alloc);
163 163
164 - kfree(rcu_dereference_protected(inet->inet_opt, 1));
164 + kfree_rcu(rcu_dereference_protected(inet->inet_opt, 1), rcu);
165 165 dst_release(rcu_dereference_protected(sk->sk_dst_cache, 1));
166 166 dst_release(rcu_dereference_protected(sk->sk_rx_dst, 1));
167 167 psp_sk_assoc_free(sk);
modified net/ipv4/cipso_ipv4.c
@@ -2287,6 +2287,14 @@ int cipso_v4_skbuff_delattr(struct sk_buff *skb)
2287 2287 new_hdr_len - new_hdr_len_actual);
2288 2288
2289 2289 opt->optlen -= hdr_len_delta;
2290 + if (opt->srr > opt->cipso)
2291 + opt->srr -= cipso_len;
2292 + if (opt->rr > opt->cipso)
2293 + opt->rr -= cipso_len;
2294 + if (opt->ts > opt->cipso)
2295 + opt->ts -= cipso_len;
2296 + if (opt->router_alert > opt->cipso)
2297 + opt->router_alert -= cipso_len;
2290 2298 opt->cipso = 0;
2291 2299 opt->is_changed = 1;
2292 2300 if (hdr_len_delta != 0) {
modified net/ipv4/fib_semantics.c
@@ -542,6 +542,9 @@ size_t fib_nlmsg_size(struct fib_info *fi)
542 542 struct fib_nh_common *nhc = fib_info_nhc(fi, i);
543 543 size_t nhsize;
544 544
545 + if (!nhc)
546 + break;
547 +
545 548 nhsize = fib_nexthop_nlmsg_size(nhc, nhs != 1);
546 549
547 550 if (nhs != 1)
modified net/ipv4/fib_trie.c
@@ -1079,8 +1079,6 @@ void fib_alias_hw_flags_set(struct net *net, const struct fib_rt_info *fri)
1079 1079
1080 1080 err = fib_dump_info(skb, 0, 0, RTM_NEWROUTE, fri, 0);
1081 1081 if (err < 0) {
1082 - /* -EMSGSIZE implies BUG in fib_nlmsg_size() */
1083 - WARN_ON(err == -EMSGSIZE);
1084 1082 kfree_skb(skb);
1085 1083 goto errout;
1086 1084 }
modified net/ipv4/ip_output.c
@@ -771,9 +771,13 @@ int ip_do_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
771 771 int err = 0;
772 772
773 773 /* for offloaded checksums cleanup checksum before fragmentation */
774 - if (skb->ip_summed == CHECKSUM_PARTIAL &&
775 - (err = skb_checksum_help(skb)))
776 - goto fail;
774 + if (skb->ip_summed == CHECKSUM_PARTIAL) {
775 + err = ip_check_csum_start(skb);
776 + if (!err)
777 + err = skb_checksum_help(skb);
778 + if (err)
779 + goto fail;
780 + }
777 781
778 782 /*
779 783 * Point into the IP datagram header.
modified net/ipv4/route.c
@@ -1082,6 +1082,8 @@ static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu)
1082 1082
1083 1083 for (nhsel = 0; nhsel < fib_info_num_path(res.fi); nhsel++) {
1084 1084 nhc = fib_info_nhc(res.fi, nhsel);
1085 + if (!nhc)
1086 + break;
1085 1087 update_or_create_fnhe(nhc, fl4->daddr, 0, mtu, lock,
1086 1088 jiffies + net->ipv4.ip_rt_mtu_expires);
1087 1089 }
@@ -3168,6 +3170,9 @@ int fib_dump_info_fnhe(struct sk_buff *skb, struct netlink_callback *cb,
3168 3170 struct fnhe_hash_bucket *bucket;
3169 3171 int err;
3170 3172
3173 + if (!nhc)
3174 + break;
3175 +
3171 3176 if (nhc->nhc_flags & RTNH_F_DEAD)
3172 3177 continue;
3173 3178
modified net/ipv4/tcp.c
@@ -1908,6 +1908,8 @@ static bool can_map_frag(const skb_frag_t *frag)
1908 1908
1909 1909 if (skb_frag_size(frag) != PAGE_SIZE || skb_frag_off(frag))
1910 1910 return false;
1911 + if (skb_frag_is_net_iov(frag))
1912 + return false;
1911 1913
1912 1914 page = skb_frag_page(frag);
1913 1915
modified net/ipv4/tcp_ipv4.c
@@ -1209,7 +1209,7 @@ static int tcp_v4_send_synack(const struct sock *sk, struct dst_entry *dst,
1209 1209 */
1210 1210 static void tcp_v4_reqsk_destructor(struct request_sock *req)
1211 1211 {
1212 - kfree(rcu_dereference_protected(inet_rsk(req)->ireq_opt, 1));
1212 + kfree_rcu(rcu_dereference_protected(inet_rsk(req)->ireq_opt, 1), rcu);
1213 1213 }
1214 1214
1215 1215 #ifdef CONFIG_TCP_MD5SIG
modified net/ipv6/calipso.c
@@ -1318,7 +1318,7 @@ static int calipso_skbuff_setattr(struct sk_buff *skb,
1318 1318 struct ipv6hdr *ip6_hdr;
1319 1319 struct ipv6_opt_hdr *hop;
1320 1320 unsigned char buf[CALIPSO_MAX_BUFFER];
1321 - int len_delta, new_end, pad, payload;
1321 + int len_delta, new_end, pad;
1322 1322 unsigned int start, end;
1323 1323
1324 1324 ip6_hdr = ipv6_hdr(skb);
@@ -1357,8 +1357,8 @@ static int calipso_skbuff_setattr(struct sk_buff *skb,
1357 1357 sizeof(*ip6_hdr) + start);
1358 1358 skb_reset_network_header(skb);
1359 1359 ip6_hdr = ipv6_hdr(skb);
1360 - payload = ntohs(ip6_hdr->payload_len);
1361 - ip6_hdr->payload_len = htons(payload + len_delta);
1360 + /* 0 above IPV6_MAXPLEN (BIG TCP), the real length otherwise */
1361 + ipv6_set_payload_len(ip6_hdr, skb->len - sizeof(*ip6_hdr));
1362 1362 }
1363 1363
1364 1364 hop = (struct ipv6_opt_hdr *)(ip6_hdr + 1);
modified net/ipv6/ip6_gre.c
@@ -923,7 +923,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb,
923 923 {
924 924 struct ip_tunnel_info *tun_info = NULL;
925 925 struct ip6_tnl *t = netdev_priv(dev);
926 - struct dst_entry *dst = skb_dst(skb);
927 926 IP_TUNNEL_DECLARE_FLAGS(flags) = { };
928 927 bool truncate = false;
929 928 int encap_limit = -1;
@@ -1058,12 +1057,6 @@ static netdev_tx_t ip6erspan_tunnel_xmit(struct sk_buff *skb,
1058 1057 gre_build_header(skb, 8, flags, proto, 0,
1059 1058 htonl(atomic_fetch_inc(&t->o_seqno)));
1060 1059
1061 - /* TooBig packet may have updated dst->dev's mtu */
1062 - if (!t->parms.collect_md && dst) {
1063 - mtu = READ_ONCE(dst_dev(dst)->mtu);
1064 - if (dst_mtu(dst) > mtu)
1065 - dst->ops->update_pmtu(dst, NULL, skb, mtu, false);
1066 - }
1067 1060 err = ip6_tnl_xmit(skb, dev, dsfield, &fl6, encap_limit, &mtu,
1068 1061 NEXTHDR_GRE);
1069 1062 if (err != 0) {
modified net/ipv6/route.c
@@ -6509,8 +6509,6 @@ void fib6_info_hw_flags_set(struct net *net, struct fib6_info *f6i,
6509 6509 err = rt6_fill_node(net, skb, f6i, NULL, NULL, NULL, 0, RTM_NEWROUTE, 0,
6510 6510 0, 0, RT_DEL_REASON_UNSPEC);
6511 6511 if (err < 0) {
6512 - /* -EMSGSIZE implies BUG in rt6_nlmsg_size() */
6513 - WARN_ON(err == -EMSGSIZE);
6514 6512 kfree_skb(skb);
6515 6513 goto errout;
6516 6514 }
modified net/mac80211/airtime.c
@@ -632,6 +632,22 @@ static bool ieee80211_fill_rate_info(struct ieee80211_hw *hw,
632 632 if (!ri || !sband)
633 633 return false;
634 634
635 + /*
636 + * ieee80211_get_rate_duration() only handles these widths. Drivers
637 + * may also report e.g. HE/EHT RU allocations, which cannot be used
638 + * to estimate airtime here.
639 + */
640 + switch (ri->bw) {
641 + case RATE_INFO_BW_20:
642 + case RATE_INFO_BW_40:
643 + case RATE_INFO_BW_80:
644 + case RATE_INFO_BW_160:
645 + case RATE_INFO_BW_320:
646 + break;
647 + default:
648 + return false;
649 + }
650 +
635 651 stat->bw = ri->bw;
636 652 stat->nss = ri->nss;
637 653 stat->rate_idx = ri->mcs;
@@ -770,6 +786,8 @@ u32 ieee80211_rate_expected_tx_airtime(struct ieee80211_hw *hw,
770 786 return ieee80211_calc_rx_airtime(hw, &stat, len) * 1024;
771 787
772 788 duration = ieee80211_get_rate_duration(hw, &stat, &overhead);
789 + if (!duration)
790 + return 0;
773 791
774 792 /*
775 793 * Assume that HT/VHT transmission on any AC except VO will
modified net/netfilter/xt_CHECKSUM.c
@@ -15,6 +15,7 @@
15 15
16 16 #include <linux/netfilter_ipv4/ip_tables.h>
17 17 #include <linux/netfilter_ipv6/ip6_tables.h>
18 + #include <net/ip.h>
18 19
19 20 MODULE_LICENSE("GPL");
20 21 MODULE_AUTHOR("Michael S. Tsirkin <mst@redhat.com>");
@@ -25,8 +26,11 @@ MODULE_ALIAS("ip6t_CHECKSUM");
25 26 static unsigned int
26 27 checksum_tg(struct sk_buff *skb, const struct xt_action_param *par)
27 28 {
28 - if (skb->ip_summed == CHECKSUM_PARTIAL && !skb_is_gso(skb))
29 + if (skb->ip_summed == CHECKSUM_PARTIAL && !skb_is_gso(skb)) {
30 + if (xt_family(par) == NFPROTO_IPV4 && ip_check_csum_start(skb))
31 + return NF_DROP;
29 32 skb_checksum_help(skb);
33 + }
30 34
31 35 return XT_CONTINUE;
32 36 }
modified net/netlink/af_netlink.c
@@ -464,7 +464,7 @@ netlink_unlock_table(void)
464 464
465 465 struct netlink_compare_arg
466 466 {
467 - possible_net_t pnet;
467 + u64 net_cookie;
468 468 u32 portid;
469 469 };
470 470
@@ -479,14 +479,14 @@ static inline int netlink_compare(struct rhashtable_compare_arg *arg,
479 479 const struct netlink_sock *nlk = ptr;
480 480
481 481 return nlk->portid != x->portid ||
482 - !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
482 + sock_net(&nlk->sk)->net_cookie != x->net_cookie;
483 483 }
484 484
485 485 static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
486 486 struct net *net, u32 portid)
487 487 {
488 488 memset(arg, 0, sizeof(*arg));
489 - write_pnet(&arg->pnet, net);
489 + arg->net_cookie = net->net_cookie;
490 490 arg->portid = portid;
491 491 }
492 492
@@ -1363,6 +1363,8 @@ retry:
1363 1363 if (netlink_is_kernel(sk))
1364 1364 return netlink_unicast_kernel(sk, skb, ssk);
1365 1365
1366 + skb_reset_network_header(skb);
1367 + skb_reset_mac_header(skb);
1366 1368 if (sk_filter(sk, skb)) {
1367 1369 err = skb->len;
1368 1370 kfree_skb(skb);
@@ -1497,6 +1499,8 @@ static void do_one_broadcast(struct sock *sk,
1497 1499 goto out;
1498 1500 }
1499 1501
1502 + skb_reset_network_header(p->skb2);
1503 + skb_reset_mac_header(p->skb2);
1500 1504 if (sk_filter(sk, p->skb2)) {
1501 1505 kfree_skb(p->skb2);
1502 1506 p->skb2 = NULL;
modified net/openvswitch/actions.c
@@ -358,7 +358,12 @@ static void set_ip_addr(struct sk_buff *skb, struct iphdr *nh,
358 358 static void update_ipv6_checksum(struct sk_buff *skb, u8 l4_proto,
359 359 __be32 addr[4], const __be32 new_addr[4])
360 360 {
361 - int transport_len = skb->len - skb_transport_offset(skb);
361 + int transport_len;
362 +
363 + if (l4_proto == NEXTHDR_FRAGMENT)
364 + return;
365 +
366 + transport_len = skb->len - skb_transport_offset(skb);
362 367
363 368 if (l4_proto == NEXTHDR_TCP) {
364 369 if (likely(transport_len >= sizeof(struct tcphdr)))
modified net/openvswitch/datapath.c
@@ -1532,6 +1532,12 @@ static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1532 1532 return -ENODEV;
1533 1533 }
1534 1534
1535 + /*
1536 + * Not needed for safety. Stops every spin_unlock_bh() in
1537 + * ovs_flow_stats_get() from running the softirq backlog.
1538 + */
1539 + local_bh_disable();
1540 +
1535 1541 ti = rcu_dereference(dp->table.ti);
1536 1542 for (;;) {
1537 1543 struct sw_flow *flow;
@@ -1552,6 +1558,8 @@ static int ovs_flow_cmd_dump(struct sk_buff *skb, struct netlink_callback *cb)
1552 1558 cb->args[0] = bucket;
1553 1559 cb->args[1] = obj;
1554 1560 }
1561 +
1562 + local_bh_enable();
1555 1563 rcu_read_unlock();
1556 1564 return skb->len;
1557 1565 }
modified net/packet/af_packet.c
@@ -1911,7 +1911,8 @@ static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1911 1911
1912 1912 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1913 1913
1914 - skb_push(skb, skb->data - skb_mac_header(skb));
1914 + if (dev_has_header(dev))
1915 + skb_push(skb, skb->data - skb_mac_header(skb));
1915 1916
1916 1917 /*
1917 1918 * The SOCK_PACKET socket receives _all_ frames.
@@ -1942,8 +1943,7 @@ static void packet_parse_headers(struct sk_buff *skb, struct socket *sock)
1942 1943 /* On TX skb->data is the L2 header; anchor it for all socket types. */
1943 1944 skb_reset_mac_header(skb);
1944 1945
1945 - if ((!skb->protocol || skb->protocol == htons(ETH_P_ALL)) &&
1946 - sock->type == SOCK_RAW)
1946 + if (!skb->protocol && sock->type == SOCK_RAW)
1947 1947 skb->protocol = dev_parse_header_protocol(skb);
1948 1948
1949 1949 skb_probe_transport_header(skb);
@@ -2613,7 +2613,8 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2613 2613 struct page *page;
2614 2614 int err;
2615 2615
2616 - skb->protocol = proto;
2616 + if (proto != htons(ETH_P_ALL))
2617 + skb->protocol = proto;
2617 2618 skb->dev = dev;
2618 2619 skb->priority = sockc->priority;
2619 2620 skb->mark = sockc->mark;
@@ -2677,8 +2678,6 @@ static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2677 2678 if (unlikely(!skb->len))
2678 2679 return -EINVAL;
2679 2680
2680 - packet_parse_headers(skb, sock);
2681 -
2682 2681 return tp_len;
2683 2682 }
2684 2683
@@ -2918,9 +2917,13 @@ tpacket_error:
2918 2917 tp_len = -EINVAL;
2919 2918 goto tpacket_error;
2920 2919 }
2921 - virtio_net_hdr_set_proto(skb, &vnet_hdr);
2922 2920 }
2923 2921
2922 + packet_parse_headers(skb, po->sk.sk_socket);
2923 +
2924 + if (has_vnet_hdr)
2925 + virtio_net_hdr_set_proto(skb, &vnet_hdr);
2926 +
2924 2927 uarg = kmalloc(sizeof(*uarg), GFP_KERNEL);
2925 2928 if (unlikely(!uarg)) {
2926 2929 if (likely(len_sum > 0))
@@ -3121,7 +3124,8 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
3121 3124 goto out_free;
3122 3125 }
3123 3126
3124 - skb->protocol = proto;
3127 + if (proto != htons(ETH_P_ALL))
3128 + skb->protocol = proto;
3125 3129 skb->dev = dev;
3126 3130 skb->priority = sockc.priority;
3127 3131 skb->mark = sockc.mark;
@@ -3130,16 +3134,18 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
3130 3134 if (unlikely(extra_len == 4))
3131 3135 skb->no_fcs = 1;
3132 3136
3133 - packet_parse_headers(skb, sock);
3134 -
3135 3137 if (vnet_hdr_sz) {
3136 3138 err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
3137 3139 if (err)
3138 3140 goto out_free;
3139 3141 len += vnet_hdr_sz;
3140 - virtio_net_hdr_set_proto(skb, &vnet_hdr);
3141 3142 }
3142 3143
3144 + packet_parse_headers(skb, sock);
3145 +
3146 + if (vnet_hdr_sz)
3147 + virtio_net_hdr_set_proto(skb, &vnet_hdr);
3148 +
3143 3149 err = packet_xmit(po, skb);
3144 3150
3145 3151 if (unlikely(err != 0)) {
modified net/rds/rdma_transport.c
@@ -52,7 +52,7 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
52 52 {
53 53 /* this can be null in the listening path */
54 54 struct rds_connection *conn = cm_id->context;
55 - struct rds_transport *trans;
55 + struct rds_transport *trans = &rds_ib_transport;
56 56 int ret = 0;
57 57 int *err;
58 58 u8 len;
@@ -60,9 +60,6 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
60 60 rdsdebug("conn %p id %p handling event %u (%s)\n", conn, cm_id,
61 61 event->event, rdma_event_msg(event->event));
62 62
63 - if (cm_id->device->node_type == RDMA_NODE_IB_CA)
64 - trans = &rds_ib_transport;
65 -
66 63 /* Prevent shutdown from tearing down the connection
67 64 * while we're executing. */
68 65 if (conn) {
@@ -82,16 +79,47 @@ static int rds_rdma_cm_event_handler_cmn(struct rdma_cm_id *cm_id,
82 79
83 80 switch (event->event) {
84 81 case RDMA_CM_EVENT_CONNECT_REQUEST:
82 + /* Only the IB transport is supported, but RDS listens on
83 + * every RDMA device: reject a request that arrived on any
84 + * other kind. A non-zero return has rdma_cm destroy the
85 + * request's id, which is what we want here and only here.
86 + */
87 + if (cm_id->device->node_type != RDMA_NODE_IB_CA) {
88 + ret = 1;
89 + break;
90 + }
85 91 ret = trans->cm_handle_connect(cm_id, event, isv6);
86 92 break;
87 93
88 94 case RDMA_CM_EVENT_ADDR_RESOLVED:
89 95 if (conn) {
96 + /* The address resolved to a device RDS has no
97 + * transport for. Do not go on to resolve a route:
98 + * an iWARP route leaves cm_id->route.path_rec
99 + * unset, which the ROUTE_RESOLVED case below
100 + * dereferences. Drop the connection instead; the
101 + * id is still ic->i_cm_id, so return 0 and let the
102 + * shutdown destroy it.
103 + */
104 + if (cm_id->device->node_type != RDMA_NODE_IB_CA) {
105 + rds_conn_drop(conn);
106 + break;
107 + }
90 108 rdma_set_service_type(cm_id, conn->c_tos);
91 109 rdma_set_min_rnr_timer(cm_id, IB_RNR_TIMER_000_32);
92 - /* XXX do we need to clean up if this fails? */
93 110 ret = rdma_resolve_route(cm_id,
94 111 RDS_RDMA_RESOLVE_TIMEOUT_MS);
112 + if (ret) {
113 + /* A non-zero return has the rdma_cm destroy
114 + * the id, but it is still ic->i_cm_id, which
115 + * the connection's shutdown would then
116 + * disconnect and destroy again. Drop the
117 + * connection and keep the id for that
118 + * shutdown.
119 + */
120 + rds_conn_drop(conn);
121 + ret = 0;
122 + }
95 123 }
96 124 break;
97 125
modified net/sched/act_api.c
@@ -372,9 +372,10 @@ static int __tcf_action_put(struct tc_action *p, bool bind)
372 372 {
373 373 struct tcf_idrinfo *idrinfo = p->idrinfo;
374 374
375 - if (refcount_dec_and_mutex_lock(&p->tcfa_refcnt, &idrinfo->lock)) {
376 - if (bind)
377 - atomic_dec(&p->tcfa_bindcnt);
375 + mutex_lock(&idrinfo->lock);
376 + if (bind)
377 + atomic_dec(&p->tcfa_bindcnt);
378 + if (refcount_dec_and_test(&p->tcfa_refcnt)) {
378 379 idr_remove(&idrinfo->action_idr, p->tcfa_index);
379 380 mutex_unlock(&idrinfo->lock);
380 381
@@ -382,9 +383,7 @@ static int __tcf_action_put(struct tc_action *p, bool bind)
382 383 return 1;
383 384 }
384 385
385 - if (bind)
386 - atomic_dec(&p->tcfa_bindcnt);
387 -
386 + mutex_unlock(&idrinfo->lock);
388 387 return 0;
389 388 }
390 389
modified net/sched/cls_route.c
@@ -434,6 +434,12 @@ static int route4_set_parms(struct net *net, struct tcf_proto *tp,
434 434 if (handle && (!fold || nhandle == (handle & ~0x7F00)))
435 435 nhandle |= handle & 0x7F00;
436 436
437 + if (fold && !tb[TCA_ROUTE4_TO] && !tb[TCA_ROUTE4_FROM] &&
438 + !tb[TCA_ROUTE4_IIF] && nhandle != fold->handle) {
439 + NL_SET_ERR_MSG(extack, "Routing attributes required");
440 + return -EINVAL;
441 + }
442 +
437 443 if (handle && !fold && nhandle != handle) {
438 444 NL_SET_ERR_MSG_FMT(extack,
439 445 "Handle mismatch constructed: %x (expected: %x)",
modified net/sched/em_text.c
@@ -58,6 +58,9 @@ static int em_text_change(struct net *net, void *data, int len,
58 58 if (len < sizeof(*conf) || len < (sizeof(*conf) + conf->pattern_len))
59 59 return -EINVAL;
60 60
61 + if (!memchr(conf->algo, '\0', sizeof(conf->algo)))
62 + return -EINVAL;
63 +
61 64 if (conf->from_layer > conf->to_layer)
62 65 return -EINVAL;
63 66
modified net/sctp/socket.c
@@ -1786,6 +1786,18 @@ static int sctp_sendmsg_check_sflags(struct sctp_association *asoc,
1786 1786 return 1;
1787 1787 }
1788 1788
1789 + static int sctp_sendmsg_check_stream(struct sctp_association *asoc,
1790 + struct sctp_sndrcvinfo *sinfo)
1791 + {
1792 + if (unlikely(sinfo->sinfo_stream >= asoc->stream.outcnt))
1793 + return -EINVAL;
1794 +
1795 + if (unlikely(!SCTP_SO(&asoc->stream, sinfo->sinfo_stream)->ext))
1796 + return sctp_stream_init_ext(&asoc->stream, sinfo->sinfo_stream);
1797 +
1798 + return 0;
1799 + }
1800 +
1789 1801 static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
1790 1802 struct msghdr *msg, size_t msg_len,
1791 1803 struct sctp_transport *transport,
@@ -1800,16 +1812,9 @@ static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
1800 1812 long timeo;
1801 1813 int err;
1802 1814
1803 - if (sinfo->sinfo_stream >= asoc->stream.outcnt) {
1804 - err = -EINVAL;
1815 + err = sctp_sendmsg_check_stream(asoc, sinfo);
1816 + if (err)
1805 1817 goto err;
1806 - }
1807 -
1808 - if (unlikely(!SCTP_SO(&asoc->stream, sinfo->sinfo_stream)->ext)) {
1809 - err = sctp_stream_init_ext(&asoc->stream, sinfo->sinfo_stream);
1810 - if (err)
1811 - goto err;
1812 - }
1813 1818
1814 1819 if (sp->disable_fragments && msg_len > asoc->frag_point) {
1815 1820 err = -EMSGSIZE;
@@ -1830,10 +1835,9 @@ static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
1830 1835 err = sctp_wait_for_sndbuf(asoc, transport, &timeo, msg_len);
1831 1836 if (err)
1832 1837 goto err;
1833 - if (unlikely(sinfo->sinfo_stream >= asoc->stream.outcnt)) {
1834 - err = -EINVAL;
1838 + err = sctp_sendmsg_check_stream(asoc, sinfo);
1839 + if (err)
1835 1840 goto err;
1836 - }
1837 1841 }
1838 1842
1839 1843 if (sctp_state(asoc, CLOSED)) {
@@ -1848,6 +1852,11 @@ static int sctp_sendmsg_to_asoc(struct sctp_association *asoc,
1848 1852 err = -ESRCH;
1849 1853 goto err;
1850 1854 }
1855 + err = sctp_sendmsg_check_stream(asoc, sinfo);
1856 + if (err) {
1857 + err = -ESRCH;
1858 + goto err;
1859 + }
1851 1860 } else {
1852 1861 wait_connect = true;
1853 1862 }
@@ -7569,11 +7578,7 @@ static int sctp_getsockopt_pr_streamstatus(struct sock *sk, int len,
7569 7578 /* Not allocated yet, means all stats are 0 */
7570 7579 params.sprstat_abandoned_unsent = 0;
7571 7580 params.sprstat_abandoned_sent = 0;
7572 - retval = 0;
7573 - goto out;
7574 - }
7575 -
7576 - if (policy == SCTP_PR_SCTP_ALL) {
7581 + } else if (policy == SCTP_PR_SCTP_ALL) {
7577 7582 params.sprstat_abandoned_unsent = 0;
7578 7583 params.sprstat_abandoned_sent = 0;
7579 7584 for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
modified net/smc/af_smc.c
@@ -2784,6 +2784,7 @@ int smc_getname(struct socket *sock, struct sockaddr *addr,
2784 2784 int peer)
2785 2785 {
2786 2786 struct smc_sock *smc;
2787 + int rc = -EBADF;
2787 2788
2788 2789 if (peer && (sock->sk->sk_state != SMC_ACTIVE) &&
2789 2790 (sock->sk->sk_state != SMC_APPCLOSEWAIT1))
@@ -2791,7 +2792,11 @@ int smc_getname(struct socket *sock, struct sockaddr *addr,
2791 2792
2792 2793 smc = smc_sk(sock->sk);
2793 2794
2794 - return smc->clcsock->ops->getname(smc->clcsock, addr, peer);
2795 + mutex_lock(&smc->clcsock_release_lock);
2796 + if (smc->clcsock)
2797 + rc = smc->clcsock->ops->getname(smc->clcsock, addr, peer);
2798 + mutex_unlock(&smc->clcsock_release_lock);
2799 + return rc;
2795 2800 }
2796 2801
2797 2802 int smc_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
modified net/strparser/strparser.c
@@ -505,12 +505,16 @@ void strp_unpause(struct strparser *strp)
505 505 EXPORT_SYMBOL_GPL(strp_unpause);
506 506
507 507 /* strp must already be stopped so that strp_recv will no longer be called.
508 - * Note that strp_done is not called with the lower socket held.
508 + * Note that strp_done must not be called with the lower socket held.
509 509 */
510 510 void strp_done(struct strparser *strp)
511 511 {
512 512 WARN_ON(!strp->stopped);
513 513
514 + lock_sock(strp->sk);
515 + /* sync with pending strp_recv */
516 + release_sock(strp->sk);
517 +
514 518 cancel_delayed_work_sync(&strp->msg_timer_work);
515 519 cancel_work_sync(&strp->work);
516 520
modified net/tipc/node.c
@@ -2421,8 +2421,11 @@ static struct tipc_node *tipc_node_find_by_name(struct net *net,
2421 2421 }
2422 2422 }
2423 2423 tipc_node_read_unlock(n);
2424 - if (found_node)
2424 + if (found_node) {
2425 + if (!kref_get_unless_zero(&found_node->kref))
2426 + found_node = NULL;
2425 2427 break;
2428 + }
2426 2429 }
2427 2430 rcu_read_unlock();
2428 2431
@@ -2507,6 +2510,7 @@ out:
2507 2510 tipc_node_read_unlock(node);
2508 2511 tipc_bearer_xmit(net, bearer_id, &xmitq, &node->links[bearer_id].maddr,
2509 2512 NULL);
2513 + tipc_node_put(node);
2510 2514 return res;
2511 2515 }
2512 2516
@@ -2558,12 +2562,14 @@ int tipc_nl_node_get_link(struct sk_buff *skb, struct genl_info *info)
2558 2562 link = node->links[bearer_id].link;
2559 2563 if (!link) {
2560 2564 tipc_node_read_unlock(node);
2565 + tipc_node_put(node);
2561 2566 err = -EINVAL;
2562 2567 goto err_free;
2563 2568 }
2564 2569
2565 2570 err = __tipc_nl_add_link(net, &msg, link, 0);
2566 2571 tipc_node_read_unlock(node);
2572 + tipc_node_put(node);
2567 2573 if (err)
2568 2574 goto err_free;
2569 2575 }
@@ -2634,11 +2640,13 @@ int tipc_nl_node_reset_link_stats(struct sk_buff *skb, struct genl_info *info)
2634 2640 if (!link) {
2635 2641 spin_unlock_bh(&le->lock);
2636 2642 tipc_node_read_unlock(node);
2643 + tipc_node_put(node);
2637 2644 return -EINVAL;
2638 2645 }
2639 2646 tipc_link_reset_stats(link);
2640 2647 spin_unlock_bh(&le->lock);
2641 2648 tipc_node_read_unlock(node);
2649 + tipc_node_put(node);
2642 2650 return 0;
2643 2651 }
2644 2652
modified net/tipc/topsrv.c
@@ -55,7 +55,7 @@
55 55 /**
56 56 * struct tipc_topsrv - TIPC server structure
57 57 * @conn_idr: identifier set of connection
58 - * @idr_lock: protect the connection identifier set
58 + * @idr_lock: protect the connection identifier set and listener
59 59 * @idr_in_use: amount of allocated identifier entry
60 60 * @net: network namespace instance
61 61 * @awork: accept work item
@@ -218,6 +218,10 @@ static struct tipc_conn *tipc_conn_lookup(struct tipc_topsrv *s, int conid)
218 218 struct tipc_conn *con;
219 219
220 220 spin_lock_bh(&s->idr_lock);
221 + if (!s->listener) {
222 + spin_unlock_bh(&s->idr_lock);
223 + return NULL;
224 + }
221 225 con = idr_find(&s->conn_idr, conid);
222 226 if (!connected(con) || !kref_get_unless_zero(&con->kref))
223 227 con = NULL;
@@ -301,10 +305,20 @@ static void tipc_conn_send_to_sock(struct tipc_conn *con)
301 305 static void tipc_conn_send_work(struct work_struct *work)
302 306 {
303 307 struct tipc_conn *con = container_of(work, struct tipc_conn, swork);
308 + struct tipc_topsrv *srv;
309 +
310 + srv = con->server;
311 + spin_lock_bh(&srv->idr_lock);
312 + if (!srv->listener) {
313 + spin_unlock_bh(&srv->idr_lock);
314 + goto out;
315 + }
316 + spin_unlock_bh(&srv->idr_lock);
304 317
305 318 if (connected(con))
306 319 tipc_conn_send_to_sock(con);
307 320
321 + out:
308 322 conn_put(con);
309 323 }
310 324
@@ -334,8 +348,14 @@ void tipc_topsrv_queue_evt(struct net *net, int conid,
334 348 list_add_tail(&e->list, &con->outqueue);
335 349 spin_unlock_bh(&con->outqueue_lock);
336 350
337 - if (queue_work(srv->send_wq, &con->swork))
338 - return;
351 + spin_lock_bh(&srv->idr_lock);
352 + if (srv->listener) {
353 + if (queue_work(srv->send_wq, &con->swork)) {
354 + spin_unlock_bh(&srv->idr_lock);
355 + return;
356 + }
357 + }
358 + spin_unlock_bh(&srv->idr_lock);
339 359 err:
340 360 conn_put(con);
341 361 }
@@ -346,14 +366,20 @@ err:
346 366 */
347 367 static void tipc_conn_write_space(struct sock *sk)
348 368 {
369 + struct tipc_topsrv *srv;
349 370 struct tipc_conn *con;
350 371
351 372 read_lock_bh(&sk->sk_callback_lock);
352 373 con = sk->sk_user_data;
353 374 if (connected(con)) {
354 - conn_get(con);
355 - if (!queue_work(con->server->send_wq, &con->swork))
356 - conn_put(con);
375 + srv = con->server;
376 + spin_lock_bh(&srv->idr_lock);
377 + if (srv->listener) {
378 + conn_get(con);
379 + if (!queue_work(srv->send_wq, &con->swork))
380 + conn_put(con);
381 + }
382 + spin_unlock_bh(&srv->idr_lock);
357 383 }
358 384 read_unlock_bh(&sk->sk_callback_lock);
359 385 }
@@ -418,8 +444,17 @@ static int tipc_conn_rcv_from_sock(struct tipc_conn *con)
418 444 static void tipc_conn_recv_work(struct work_struct *work)
419 445 {
420 446 struct tipc_conn *con = container_of(work, struct tipc_conn, rwork);
447 + struct tipc_topsrv *srv;
421 448 int count = 0;
422 449
450 + srv = con->server;
451 + spin_lock_bh(&srv->idr_lock);
452 + if (!srv->listener) {
453 + spin_unlock_bh(&srv->idr_lock);
454 + goto out;
455 + }
456 + spin_unlock_bh(&srv->idr_lock);
457 +
423 458 while (connected(con)) {
424 459 if (tipc_conn_rcv_from_sock(con))
425 460 break;
@@ -430,6 +465,7 @@ static void tipc_conn_recv_work(struct work_struct *work)
430 465 count = 0;
431 466 }
432 467 }
468 + out:
433 469 conn_put(con);
434 470 }
435 471
@@ -438,6 +474,7 @@ static void tipc_conn_recv_work(struct work_struct *work)
438 474 */
439 475 static void tipc_conn_data_ready(struct sock *sk)
440 476 {
477 + struct tipc_topsrv *srv;
441 478 struct tipc_conn *con;
442 479
443 480 trace_sk_data_ready(sk);
@@ -445,9 +482,14 @@ static void tipc_conn_data_ready(struct sock *sk)
445 482 read_lock_bh(&sk->sk_callback_lock);
446 483 con = sk->sk_user_data;
447 484 if (connected(con)) {
448 - conn_get(con);
449 - if (!queue_work(con->server->rcv_wq, &con->rwork))
450 - conn_put(con);
485 + srv = con->server;
486 + spin_lock_bh(&srv->idr_lock);
487 + if (srv->listener) {
488 + conn_get(con);
489 + if (!queue_work(srv->rcv_wq, &con->rwork))
490 + conn_put(con);
491 + }
492 + spin_unlock_bh(&srv->idr_lock);
451 493 }
452 494 read_unlock_bh(&sk->sk_callback_lock);
453 495 }
@@ -503,8 +545,12 @@ static void tipc_topsrv_listener_data_ready(struct sock *sk)
503 545
504 546 read_lock_bh(&sk->sk_callback_lock);
505 547 srv = sk->sk_user_data;
506 - if (srv)
507 - queue_work(srv->rcv_wq, &srv->awork);
548 + if (srv) {
549 + spin_lock_bh(&srv->idr_lock);
550 + if (srv->listener)
551 + queue_work(srv->rcv_wq, &srv->awork);
552 + spin_unlock_bh(&srv->idr_lock);
553 + }
508 554 read_unlock_bh(&sk->sk_callback_lock);
509 555 }
510 556
@@ -700,23 +746,27 @@ static void tipc_topsrv_stop(struct net *net)
700 746 struct tipc_conn *con;
701 747 int id;
702 748
749 + spin_lock_bh(&srv->idr_lock);
750 + srv->listener = NULL;
751 + spin_unlock_bh(&srv->idr_lock);
752 + tipc_topsrv_work_stop(srv);
753 +
703 754 spin_lock_bh(&srv->idr_lock);
704 755 for (id = 0; srv->idr_in_use; id++) {
705 756 con = idr_find(&srv->conn_idr, id);
706 757 if (con) {
707 - conn_get(con);
708 758 spin_unlock_bh(&srv->idr_lock);
709 759 tipc_conn_close(con);
710 - conn_put(con);
711 760 spin_lock_bh(&srv->idr_lock);
761 + continue;
712 762 }
763 + spin_unlock_bh(&srv->idr_lock);
764 + spin_lock_bh(&srv->idr_lock);
713 765 }
714 766 __module_get(lsock->ops->owner);
715 767 __module_get(lsock->sk->sk_prot_creator->owner);
716 - srv->listener = NULL;
717 768 spin_unlock_bh(&srv->idr_lock);
718 769
719 - tipc_topsrv_work_stop(srv);
720 770 sock_release(lsock);
721 771 idr_destroy(&srv->conn_idr);
722 772 kfree(srv);
modified net/vmw_vsock/af_vsock.c
@@ -1048,6 +1048,8 @@ static void vsock_sk_destruct(struct sock *sk)
1048 1048 {
1049 1049 struct vsock_sock *vsk = vsock_sk(sk);
1050 1050
1051 + /* Socket buffers may remain in the queue in VMCI datagram mode */
1052 + __skb_queue_purge(&sk->sk_receive_queue);
1051 1053 /* Flush MSG_ZEROCOPY leftovers. */
1052 1054 __skb_queue_purge(&sk->sk_error_queue);
1053 1055
@@ -1834,23 +1836,22 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
1834 1836 timeout = schedule_timeout(timeout);
1835 1837 lock_sock(sk);
1836 1838
1837 - /* Connection established. Whatever happens to socket once we
1838 - * release it, that's not connect()'s concern. No need to go
1839 + /* Connection was established. Whatever happens to socket once
1840 + * we release it, that's not connect()'s concern. No need to go
1839 1841 * into signal and timeout handling. Call it a day.
1840 1842 *
1841 1843 * Note that allowing to "reset" an already established socket
1842 1844 * here is racy and insecure.
1843 1845 */
1844 - if (sk->sk_state == TCP_ESTABLISHED)
1845 - break;
1846 + if (sk->sk_state == TCP_ESTABLISHED ||
1847 + sk->sk_state == TCP_CLOSING) {
1848 + err = 0;
1849 + goto out_wait;
1850 + }
1846 1851
1847 1852 /* If connection was _not_ established and a signal/timeout came
1848 1853 * to be, we want the socket's state reset. User space may want
1849 - * to retry.
1850 - *
1851 - * sk_state != TCP_ESTABLISHED implies that socket is not on
1852 - * vsock_connected_table. We keep the binding and the transport
1853 - * assigned.
1854 + * to retry, so we keep the binding and the transport assigned.
1854 1855 */
1855 1856 if (signal_pending(current) || timeout == 0) {
1856 1857 err = timeout == 0 ? -ETIMEDOUT : sock_intr_errno(timeout);
modified net/vmw_vsock/virtio_transport_common.c
@@ -1927,6 +1927,7 @@ int virtio_transport_read_skb(struct vsock_sock *vsk, skb_read_actor_t recv_acto
1927 1927 struct sock *sk = sk_vsock(vsk);
1928 1928 struct virtio_vsock_hdr *hdr;
1929 1929 struct sk_buff *skb;
1930 + u32 bytes_read;
1930 1931 u32 pkt_len;
1931 1932 int off = 0;
1932 1933 int err;
@@ -1946,7 +1947,8 @@ int virtio_transport_read_skb(struct vsock_sock *vsk, skb_read_actor_t recv_acto
1946 1947 vvs->msg_count--;
1947 1948
1948 1949 pkt_len = le32_to_cpu(hdr->len);
1949 - virtio_transport_dec_rx_pkt(vvs, pkt_len, pkt_len);
1950 + bytes_read = skb->len - VIRTIO_VSOCK_SKB_CB(skb)->offset;
1951 + virtio_transport_dec_rx_pkt(vvs, bytes_read, pkt_len);
1950 1952 spin_unlock_bh(&vvs->rx_lock);
1951 1953
1952 1954 virtio_transport_send_credit_update(vsk);
modified net/xfrm/xfrm_output.c
@@ -823,16 +823,22 @@ int xfrm_output(struct sock *sk, struct sk_buff *skb)
823 823 }
824 824
825 825 if (skb->ip_summed == CHECKSUM_PARTIAL) {
826 - err = skb_checksum_help(skb);
827 - if (err) {
828 - XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR);
829 - kfree_skb(skb);
830 - return err;
826 + if (skb->protocol == htons(ETH_P_IP)) {
827 + err = ip_check_csum_start(skb);
828 + if (err)
829 + goto error;
831 830 }
831 + err = skb_checksum_help(skb);
832 + if (err)
833 + goto error;
832 834 }
833 835
834 836 out:
835 837 return xfrm_output2(net, sk, skb);
838 + error:
839 + XFRM_INC_STATS(net, LINUX_MIB_XFRMOUTERROR);
840 + kfree_skb(skb);
841 + return err;
836 842 }
837 843 EXPORT_SYMBOL_GPL(xfrm_output);
838 844
modified samples/pidfd/Makefile
@@ -1,4 +1,4 @@
1 1 # SPDX-License-Identifier: GPL-2.0
2 - usertprogs-always-y += pidfd-metadata
2 + userprogs-always-y += pidfd-metadata
3 3
4 4 userccflags += -I usr/include
modified security/keys/key.c
@@ -840,9 +840,6 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
840 840
841 841 key_check(keyring);
842 842
843 - if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
844 - restrict_link = keyring->restrict_link;
845 -
846 843 key_ref = ERR_PTR(-ENOTDIR);
847 844 if (keyring->type != &key_type_keyring)
848 845 goto error_put_type;
@@ -880,6 +877,9 @@ static key_ref_t __key_create_or_update(key_ref_t keyring_ref,
880 877 goto error_link_end;
881 878 }
882 879
880 + if (!(flags & KEY_ALLOC_BYPASS_RESTRICTION))
881 + restrict_link = keyring->restrict_link;
882 +
883 883 if (restrict_link && restrict_link->check) {
884 884 ret = restrict_link->check(keyring, index_key.type,
885 885 &prep.payload, restrict_link->key);
modified security/keys/persistent.c
@@ -33,25 +33,31 @@ static int key_create_persistent_register(struct user_namespace *ns)
33 33 }
34 34
35 35 /*
36 - * Create the persistent keyring for the specified user.
36 + * Get or create the persistent keyring for the specified user.
37 37 *
38 38 * Called with the namespace's sem locked for writing.
39 + *
40 + * Returns a boolean indicating whether the keyring already existed,
41 + * or a negative error. On success, *persistent_ref holds a reference
42 + * to the keyring.
39 43 */
40 - static key_ref_t key_create_persistent(struct user_namespace *ns, kuid_t uid,
41 - struct keyring_index_key *index_key)
44 + static int key_get_or_create_persistent(struct user_namespace *ns, kuid_t uid,
45 + struct keyring_index_key *index_key,
46 + key_ref_t *persistent_ref)
42 47 {
43 48 struct key *persistent;
44 - key_ref_t reg_ref, persistent_ref;
49 + key_ref_t reg_ref;
45 50
46 51 if (!ns->persistent_keyring_register) {
47 - long err = key_create_persistent_register(ns);
52 + int err = key_create_persistent_register(ns);
53 +
48 54 if (err < 0)
49 - return ERR_PTR(err);
55 + return err;
50 56 } else {
51 57 reg_ref = make_key_ref(ns->persistent_keyring_register, true);
52 - persistent_ref = find_key_to_update(reg_ref, index_key);
53 - if (persistent_ref)
54 - return persistent_ref;
58 + *persistent_ref = find_key_to_update(reg_ref, index_key);
59 + if (*persistent_ref)
60 + return 1;
55 61 }
56 62
57 63 persistent = keyring_alloc(index_key->description,
@@ -61,9 +67,10 @@ static key_ref_t key_create_persistent(struct user_namespace *ns, kuid_t uid,
61 67 KEY_ALLOC_NOT_IN_QUOTA, NULL,
62 68 ns->persistent_keyring_register);
63 69 if (IS_ERR(persistent))
64 - return ERR_CAST(persistent);
70 + return PTR_ERR(persistent);
65 71
66 - return make_key_ref(persistent, true);
72 + *persistent_ref = make_key_ref(persistent, true);
73 + return 0;
67 74 }
68 75
69 76 /*
@@ -78,6 +85,7 @@ static long key_get_persistent(struct user_namespace *ns, kuid_t uid,
78 85 key_ref_t reg_ref, persistent_ref;
79 86 char buf[32];
80 87 long ret;
88 + bool created = false;
81 89
82 90 /* Look in the register if it exists */
83 91 memset(&index_key, 0, sizeof(index_key));
@@ -100,23 +108,24 @@ static long key_get_persistent(struct user_namespace *ns, kuid_t uid,
100 108 * also need to create the register.
101 109 */
102 110 down_write(&ns->keyring_sem);
103 - persistent_ref = key_create_persistent(ns, uid, &index_key);
111 + ret = key_get_or_create_persistent(ns, uid, &index_key,
112 + &persistent_ref);
104 113 up_write(&ns->keyring_sem);
105 - if (!IS_ERR(persistent_ref))
106 - goto found;
107 -
108 - return PTR_ERR(persistent_ref);
114 + if (ret < 0)
115 + return ret;
116 + created = ret == 0;
109 117
110 118 found:
119 + persistent = key_ref_to_ptr(persistent_ref);
111 120 ret = key_task_permission(persistent_ref, current_cred(), KEY_NEED_LINK);
112 - if (ret == 0) {
113 - persistent = key_ref_to_ptr(persistent_ref);
121 + if (ret == 0)
114 122 ret = key_link(key_ref_to_ptr(dest_ref), persistent);
115 - if (ret == 0) {
116 - key_set_timeout(persistent, persistent_keyring_expiry);
117 - ret = persistent->serial;
118 - }
119 - }
123 +
124 + if (ret == 0 || created)
125 + key_set_timeout(persistent, persistent_keyring_expiry);
126 +
127 + if (ret == 0)
128 + ret = persistent->serial;
120 129
121 130 key_ref_put(persistent_ref);
122 131 return ret;
modified security/landlock/domain.h
@@ -242,9 +242,14 @@ struct landlock_domain {
242 242 * to properly handle merged rulesets without
243 243 * overlapping access rights. These layers are set once
244 244 * and never changed for the lifetime of the domain.
245 + *
246 + * Not annotated with __counted_by(num_layers): clang
247 + * miscomputes the counter address for a FAM nested in
248 + * an anonymous struct within a union, which trips
249 + * FORTIFY:
250 + * https://github.com/llvm/llvm-project/pull/228309
245 251 */
246 - struct access_masks
247 - handled_masks[] __counted_by(num_layers);
252 + struct access_masks handled_masks[];
248 253 };
249 254 };
250 255 };
modified security/selinux/avc.c
@@ -578,7 +578,7 @@ static int avc_latest_notif_update(u32 seqno, int is_insert)
578 578 }
579 579 } else {
580 580 if (seqno > selinux_avc.avc_cache.latest_notif)
581 - selinux_avc.avc_cache.latest_notif = seqno;
581 + WRITE_ONCE(selinux_avc.avc_cache.latest_notif, seqno);
582 582 }
583 583 spin_unlock_irqrestore(&notif_lock, flag);
584 584
@@ -1206,5 +1206,6 @@ int avc_has_perm(u32 ssid, u32 tsid, u16 tclass,
1206 1206
1207 1207 u32 avc_policy_seqno(void)
1208 1208 {
1209 - return selinux_avc.avc_cache.latest_notif;
1209 + /* Writers hold notif_lock; readers only sample the sequence number. */
1210 + return READ_ONCE(selinux_avc.avc_cache.latest_notif);
1210 1211 }
modified security/selinux/hooks.c
@@ -690,8 +690,12 @@ static int selinux_set_mnt_opts(struct super_block *sb,
690 690 * will be used for both mounts)
691 691 */
692 692 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
693 - && !opts)
693 + && !opts) {
694 + if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) &&
695 + sbsec->behavior == SECURITY_FS_USE_NATIVE)
696 + *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
694 697 goto out;
698 + }
695 699
696 700 root_isec = backing_inode_security_novalidate(root);
697 701
@@ -735,6 +739,9 @@ static int selinux_set_mnt_opts(struct super_block *sb,
735 739 /* previously mounted with options, but not on this attempt? */
736 740 if ((sbsec->flags & SE_MNTMASK) && !opts)
737 741 goto out_double_mount;
742 + if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) &&
743 + sbsec->behavior == SECURITY_FS_USE_NATIVE)
744 + *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
738 745 rc = 0;
739 746 goto out;
740 747 }
modified sound/hda/codecs/realtek/alc269.c
@@ -7646,6 +7646,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
7646 7646 SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
7647 7647 SND_PCI_QUIRK(0x103c, 0x8be9, "HP Envy x360 2-in-1 Laptop 15-fh0xxx", ALC245_FIXUP_HP_ENVY_X360_15_FH0XXX),
7648 7648 SND_PCI_QUIRK(0x103c, 0x8bf0, "HP", ALC236_FIXUP_HP_GPIO_LED),
7649 + SND_PCI_QUIRK(0x103c, 0x8bfd, "HP Pavilion 15-eg3xxx", ALC287_FIXUP_HP_GPIO_LED),
7649 7650 SND_PCI_QUIRK(0x103c, 0x8c15, "HP Spectre x360 2-in-1 Laptop 14-eu0xxx", ALC245_FIXUP_HP_SPECTRE_X360_EU0XXX),
7650 7651 SND_PCI_QUIRK(0x103c, 0x8c16, "HP Spectre x360 2-in-1 Laptop 16-aa0xxx", ALC245_FIXUP_HP_SPECTRE_X360_16_AA0XXX),
7651 7652 SND_PCI_QUIRK(0x103c, 0x8c17, "HP Spectre x360 2-in-1 Laptop 16-aa0xxx", ALC245_FIXUP_HP_SPECTRE_X360_16_AA0XXX),
@@ -8346,6 +8347,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
8346 8347 SND_PCI_QUIRK(0x17aa, 0x9e56, "Lenovo ZhaoYang CF4620Z", ALC286_FIXUP_SONY_MIC_NO_PRESENCE),
8347 8348 SND_PCI_QUIRK(0x1849, 0x0269, "Positivo Master C6400", ALC269VB_FIXUP_ASUS_ZENBOOK),
8348 8349 SND_PCI_QUIRK(0x1849, 0x1233, "ASRock NUC Box 1100", ALC233_FIXUP_NO_AUDIO_JACK),
8350 + SND_PCI_QUIRK(0x1849, 0x6256, "ASRock NUC Box 358H", ALC233_FIXUP_NO_AUDIO_JACK),
8349 8351 SND_PCI_QUIRK(0x1849, 0xa233, "Positivo Master C6300", ALC269_FIXUP_HEADSET_MIC),
8350 8352 SND_PCI_QUIRK(0x1854, 0x0440, "LG CQ6", ALC256_FIXUP_HEADPHONE_AMP_VOL),
8351 8353 SND_PCI_QUIRK(0x1854, 0x0441, "LG CQ6 AIO", ALC256_FIXUP_HEADPHONE_AMP_VOL),
modified sound/hda/codecs/side-codecs/tas2781_hda.c
@@ -139,9 +139,21 @@ static void tas2781_apply_calib(struct tasdevice_priv *p)
139 139 */
140 140 crc = crc32(~0, data, 84) ^ ~0;
141 141 if (crc != tmp_val[21]) {
142 - cali_data->total_sz = 0;
143 - dev_err(p->dev, "%s: V1 CRC error\n", __func__);
144 - return;
142 + /*
143 + * Some Lenovo BIOSes (e.g. Legion Pro 7 16IRX9H,
144 + * SSID 17aa:38cd) store valid V1 calibration data
145 + * but leave TimeStamp and CRC zeroed.
146 + */
147 + if (!tmp_val[20] && !tmp_val[21] &&
148 + tmp_val[0] && tmp_val[1]) {
149 + dev_warn(p->dev,
150 + "%s: V1 data without CRC, accepting\n",
151 + __func__);
152 + } else {
153 + cali_data->total_sz = 0;
154 + dev_err(p->dev, "%s: V1 CRC error\n", __func__);
155 + return;
156 + }
145 157 }
146 158
147 159 for (j = p->ndev - 1; j >= 0; j--) {
modified sound/pci/ctxfi/ctdaio.c
@@ -221,14 +221,18 @@ static int dao_set_right_input(struct dao *dao, struct rsc *input)
221 221
222 222 static int dao_clear_input(struct dao *dao, unsigned int start, unsigned int end)
223 223 {
224 + struct imapper *entry;
224 225 unsigned int i;
225 226
226 - if (!dao->imappers[start])
227 + entry = dao->imappers[start];
228 + if (!entry)
227 229 return 0;
230 +
228 231 for (i = start; i < end; i++) {
229 232 dao->mgr->imap_delete(dao->mgr, dao->imappers[i]);
230 233 dao->imappers[i] = NULL;
231 234 }
235 + kfree(entry);
232 236
233 237 return 0;
234 238 }
modified sound/soc/amd/yc/pci-acp6x.c
@@ -301,7 +301,7 @@ static int snd_acp6x_suspend(struct device *dev)
301 301 return ret;
302 302 }
303 303
304 - static int snd_acp6x_resume(struct device *dev)
304 + static int snd_acp6x_runtime_resume(struct device *dev)
305 305 {
306 306 struct acp6x_dev_data *adata;
307 307 int ret;
@@ -313,8 +313,42 @@ static int snd_acp6x_resume(struct device *dev)
313 313 return ret;
314 314 }
315 315
316 + static void acp6x_disable_msi_on_resume(struct pci_dev *pdev)
317 + {
318 + u16 control;
319 +
320 + if (!pdev->msi_cap)
321 + return;
322 +
323 + pci_read_config_word(pdev, pdev->msi_cap + PCI_MSI_FLAGS, &control);
324 + if (control & PCI_MSI_FLAGS_ENABLE) {
325 + dev_warn(&pdev->dev,
326 + "ACP: MSI unexpectedly enabled after resume (flags=0x%04x), disabling\n",
327 + control);
328 + control &= ~PCI_MSI_FLAGS_ENABLE;
329 + pci_write_config_word(pdev, pdev->msi_cap + PCI_MSI_FLAGS, control);
330 + }
331 + }
332 +
333 + static int snd_acp6x_resume(struct device *dev)
334 + {
335 + struct pci_dev *pdev = to_pci_dev(dev);
336 +
337 + /*
338 + * BIOS/firmware may re-enable MSI in PCI config space during
339 + * system resume even though this driver only uses legacy INTx
340 + * interrupts. If MSI is left enabled with stale address/data
341 + * registers, the device will write interrupts to a bogus address
342 + * causing IOMMU IO_PAGE_FAULT and interrupt delivery failure.
343 + * Explicitly clear the MSI Enable bit before reinitializing
344 + * the ACP hardware.
345 + */
346 + acp6x_disable_msi_on_resume(pdev);
347 + return snd_acp6x_runtime_resume(dev);
348 + }
349 +
316 350 static const struct dev_pm_ops acp6x_pm = {
317 - RUNTIME_PM_OPS(snd_acp6x_suspend, snd_acp6x_resume, NULL)
351 + RUNTIME_PM_OPS(snd_acp6x_suspend, snd_acp6x_runtime_resume, NULL)
318 352 SYSTEM_SLEEP_PM_OPS(snd_acp6x_suspend, snd_acp6x_resume)
319 353 };
320 354
modified sound/soc/codecs/cs42l52.c
@@ -290,7 +290,7 @@ static const char * const cs42l52_ng_type_text[] = {
290 290 };
291 291
292 292 static SOC_ENUM_SINGLE_DECL(ng_type_enum,
293 - CS42L52_NOISE_GATE_CTL, 6,
293 + CS42L52_NOISE_GATE_CTL, 7,
294 294 cs42l52_ng_type_text);
295 295
296 296 static const char * const left_swap_text[] = {
modified sound/soc/codecs/cs42l56.c
@@ -481,7 +481,7 @@ static const struct snd_kcontrol_new cs42l56_snd_controls[] = {
481 481 0, 0x3f, 0, 0),
482 482 SOC_SINGLE_TLV("Limiter MAX", CS42L56_LIM_THRESHOLD_CTL,
483 483 5, 0x07, 1, alc_tlv),
484 - SOC_SINGLE_TLV("Limiter Cushion", CS42L56_ALC_THRESHOLD,
484 + SOC_SINGLE_TLV("Limiter Cushion", CS42L56_LIM_THRESHOLD_CTL,
485 485 2, 0x07, 1, alc_tlv),
486 486
487 487 SOC_SINGLE("NG Switch", CS42L56_NOISE_GATE_CTL, 6, 1, 1),
modified sound/soc/codecs/max98371.c
@@ -166,7 +166,7 @@ static const struct snd_kcontrol_new max98371_snd_controls[] = {
166 166 0, (1<<MAX98371_DHT_MAX_WIDTH)-1, 0,
167 167 max98371_dht_max_gain),
168 168 SOC_SINGLE_TLV("Speaker DHT Min Volume", MAX98371_DHT_GAIN,
169 - 0, (1<<MAX98371_DHT_GAIN_WIDTH)-1, 0,
169 + 4, (1<<MAX98371_DHT_GAIN_WIDTH)-1, 0,
170 170 max98371_dht_min_gain),
171 171 SOC_SINGLE_TLV("Speaker DHT Rotation Volume", MAX98371_DHT_GAIN,
172 172 0, (1<<MAX98371_DHT_ROT_WIDTH)-1, 0,
modified sound/soc/codecs/nau8822.c
@@ -383,9 +383,9 @@ static const struct snd_kcontrol_new nau8822_snd_controls[] = {
383 383 NAU8822_REG_RIGHT_ADC_BOOST_CONTROL, 0, 7, 0, boost_tlv),
384 384
385 385 SOC_SINGLE("DAC 128x Oversampling Switch",
386 - NAU8822_REG_DAC_CONTROL, 5, 1, 0),
386 + NAU8822_REG_DAC_CONTROL, 3, 1, 0),
387 387 SOC_SINGLE("ADC 128x Oversampling Switch",
388 - NAU8822_REG_ADC_CONTROL, 5, 1, 0),
388 + NAU8822_REG_ADC_CONTROL, 3, 1, 0),
389 389 };
390 390
391 391 /* LMAIN and RMAIN Mixer */
modified sound/soc/codecs/pcm3168a.c
@@ -103,7 +103,7 @@ static SOC_ENUM_SINGLE_DECL(pcm3168a_dac_zf_func, PCM3168A_DAC_ATT_DEMP_ZF,
103 103 static const char *const pcm3168a_pol[] = { "Active High", "Active Low" };
104 104
105 105 static SOC_ENUM_SINGLE_DECL(pcm3168a_dac_zf_pol, PCM3168A_DAC_ATT_DEMP_ZF,
106 - PCM3168A_DAC_ATSPDA_SHIFT, pcm3168a_pol);
106 + PCM3168A_DAC_ZREV_SHIFT, pcm3168a_pol);
107 107
108 108 static const char *const pcm3168a_con[] = { "Differential", "Single-Ended" };
109 109
modified sound/soc/codecs/wm8978.c
@@ -255,9 +255,9 @@ static const struct snd_kcontrol_new wm8978_snd_controls[] = {
255 255
256 256 /* DAC / ADC oversampling */
257 257 SOC_SINGLE("DAC 128x Oversampling Switch", WM8978_DAC_CONTROL,
258 - 5, 1, 0),
258 + 3, 1, 0),
259 259 SOC_SINGLE("ADC 128x Oversampling Switch", WM8978_ADC_CONTROL,
260 - 5, 1, 0),
260 + 3, 1, 0),
261 261 };
262 262
263 263 /* Mixer #1: Output (OUT1, OUT2) Mixer: mix AUX, Input mixer output and DAC */
modified sound/soc/intel/avs/pcm.c
@@ -756,7 +756,7 @@ static int avs_dai_fe_prepare(struct snd_pcm_substream *substream, struct snd_so
756 756 data = snd_soc_dai_get_dma_data(dai, substream);
757 757 host_stream = data->host_stream;
758 758
759 - if (runtime->state == SNDRV_PCM_STATE_XRUN)
759 + if (runtime->state != SNDRV_PCM_STATE_PREPARED)
760 760 hdac_stream(host_stream)->prepared = false;
761 761 if (hdac_stream(host_stream)->prepared)
762 762 return 0;
modified sound/soc/stm/stm32_spdifrx.c
@@ -720,7 +720,7 @@ static irqreturn_t stm32_spdifrx_isr(int irq, void *devid)
720 720
721 721 if (err) {
722 722 regmap_read(spdifrx->regmap, STM32_SPDIFRX_CR, &cr);
723 - sync_state = FIELD_GET(SPDIFRX_CR_SPDIFEN_MASK, cr) &&
723 + sync_state = FIELD_GET(SPDIFRX_CR_SPDIFEN_MASK, cr) ==
724 724 SPDIFRX_SPDIFEN_SYNC;
725 725
726 726 /* SPDIFRX is in STATE_STOP. Disable SPDIFRX to clear errors */
modified sound/usb/quirks.c
@@ -2510,6 +2510,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = {
2510 2510 QUIRK_FLAG_DSD_RAW),
2511 2511 DEVICE_FLG(0x21b4, 0x0232, /* Ayre QX-5 Twenty */
2512 2512 QUIRK_FLAG_DSD_RAW),
2513 + DEVICE_FLG(0x22e8, 0xca10, /* Cambridge Audio streamers */
2514 + QUIRK_FLAG_DSD_RAW),
2513 2515 DEVICE_FLG(0x2522, 0x0007, /* LH Labs Geek Out HD Audio 1V5 */
2514 2516 QUIRK_FLAG_SET_IFACE_FIRST),
2515 2517 DEVICE_FLG(0x25aa, 0x600b, /* TAE1159 */
modified tools/arch/x86/include/asm/insn.h
@@ -321,7 +321,7 @@ static inline int insn_offset_immediate(struct insn *insn)
321 321 * are repeated, it cannot be used for looping over the prefixes.
322 322 */
323 323 #define for_each_insn_prefix(insn, prefix) \
324 - for (int idx = 0; idx < ARRAY_SIZE(insn->prefixes.bytes) && (prefix = insn->prefixes.bytes[idx]) != 0; idx++)
324 + for (int __i = 0; __i < ARRAY_SIZE(insn->prefixes.bytes) && (prefix = insn->prefixes.bytes[__i]) != 0; __i++)
325 325
326 326 #define POP_SS_OPCODE 0x1f
327 327 #define MOV_SREG_OPCODE 0x8e
modified tools/bootconfig/main.c
@@ -495,7 +495,8 @@ static int apply_xbc(const char *path, const char *xbc_path)
495 495 footer.size = htole32(size);
496 496 footer.csum = htole32(csum);
497 497 memcpy(footer.magic, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN);
498 - static_assert(sizeof(footer) == BOOTCONFIG_FOOTER_SIZE);
498 + static_assert(sizeof(footer) == BOOTCONFIG_FOOTER_SIZE,
499 + "bootconfig footer size mismatch");
499 500 memcpy(data + size, &footer, BOOTCONFIG_FOOTER_SIZE);
500 501
501 502 total_size = size + BOOTCONFIG_FOOTER_SIZE;
modified tools/gpio/Makefile
@@ -7,7 +7,13 @@ bindir ?= /usr/bin
7 7 # isn't set and when invoked from selftests build, where srctree
8 8 # is set to ".". building_out_of_srctree is undefined for in srctree
9 9 # builds
10 + ifeq ($(srctree),)
11 + update_srctree := 1
12 + endif
10 13 ifndef building_out_of_srctree
14 + update_srctree := 1
15 + endif
16 + ifeq ($(update_srctree),1)
11 17 srctree := $(patsubst %/,%,$(dir $(CURDIR)))
12 18 srctree := $(patsubst %/,%,$(dir $(srctree)))
13 19 endif
modified tools/hv/hv_get_dns_info.sh
@@ -1,6 +1,6 @@
1 1 #!/bin/sh
2 2
3 - # This example script parses /etc/resolv.conf to retrive DNS information.
3 + # This example script parses /etc/resolv.conf to retrieve DNS information.
4 4 # In the interest of keeping the KVP daemon code free of distro specific
5 5 # information; the kvp daemon code invokes this external script to gather
6 6 # DNS information.
modified tools/power/x86/turbostat/turbostat.c
@@ -2034,8 +2034,11 @@ const struct dirent *pmt_diriter_begin(struct pmt_diriter_t *iter, const char *p
2034 2034 return NULL;
2035 2035
2036 2036 num_names = scandir(pmt_root_path, &iter->namelist, pmt_telemdir_filter, pmt_telemdir_sort);
2037 - if (num_names == -1)
2037 + if (num_names == -1) {
2038 + closedir(iter->dir);
2039 + iter->dir = NULL;
2038 2040 return NULL;
2041 + }
2039 2042 }
2040 2043
2041 2044 iter->current_name_idx = 0;
@@ -2063,8 +2066,10 @@ void pmt_diriter_remove(struct pmt_diriter_t *iter)
2063 2066 iter->num_names = 0;
2064 2067 iter->current_name_idx = 0;
2065 2068
2066 - closedir(iter->dir);
2067 - iter->dir = NULL;
2069 + if (iter->dir) {
2070 + closedir(iter->dir);
2071 + iter->dir = NULL;
2072 + }
2068 2073 }
2069 2074
2070 2075 unsigned int pmt_counter_get_width(const struct pmt_counter *p)
@@ -3636,7 +3641,7 @@ int format_counters(PER_THREAD_PARAMS)
3636 3641 if (p->gfx_rc6_ms == -1) { /* detect GFX counter reset */
3637 3642 outp += sprintf(outp, "%s**.**", (printed++ ? delim : ""));
3638 3643 } else {
3639 - outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), p->gfx_rc6_ms / 10.0 / interval_float);
3644 + outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), pct(p->gfx_rc6_ms / 10.0, interval_float));
3640 3645 }
3641 3646 }
3642 3647
@@ -3653,7 +3658,7 @@ int format_counters(PER_THREAD_PARAMS)
3653 3658 if (p->sam_mc6_ms == -1) { /* detect GFX counter reset */
3654 3659 outp += sprintf(outp, "%s**.**", (printed++ ? delim : ""));
3655 3660 } else {
3656 - outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), p->sam_mc6_ms / 10.0 / interval_float);
3661 + outp += sprintf(outp, "%s%.2f", (printed++ ? delim : ""), pct(p->sam_mc6_ms / 10.0, interval_float));
3657 3662 }
3658 3663 }
3659 3664
@@ -5915,7 +5920,7 @@ void free_fd_msr(void)
5915 5920 if (!msr_counter_info)
5916 5921 return;
5917 5922
5918 - for (int cpu = 0; cpu < topo.max_cpu_num; ++cpu) {
5923 + for (int cpu = 0; cpu <= topo.max_cpu_num; ++cpu) {
5919 5924 if (msr_counter_info[cpu].fd_perf != -1)
5920 5925 close(msr_counter_info[cpu].fd_perf);
5921 5926 }
@@ -6311,33 +6316,35 @@ int for_all_proc_cpus(int (func) (int))
6311 6316
6312 6317 #define PATH_EFFECTIVE_CPUS "/sys/fs/cgroup/cpuset.cpus.effective"
6313 6318
6314 - static char cpu_effective_str[1024];
6319 + static char *cpu_effective_str;
6315 6320
6316 6321 static int update_effective_str(bool startup)
6317 6322 {
6318 6323 FILE *fp;
6319 - char *pos;
6320 - char buf[1024];
6324 + char *buf = NULL;
6325 + size_t size = 0;
6321 6326 int ret;
6322 6327
6323 - if (cpu_effective_str[0] == '\0' && !startup)
6328 + if (!cpu_effective_str && !startup)
6324 6329 return 0;
6325 6330
6326 6331 fp = fopen(PATH_EFFECTIVE_CPUS, "r");
6327 6332 if (!fp)
6328 6333 return 0;
6329 6334
6330 - pos = fgets(buf, 1024, fp);
6331 - if (!pos)
6335 + if (getline(&buf, &size, fp) < 0)
6332 6336 err(1, "%s: file read failed", PATH_EFFECTIVE_CPUS);
6333 6337
6334 6338 fclose(fp);
6335 6339
6336 - ret = strncmp(cpu_effective_str, buf, 1024);
6337 - if (!ret)
6340 + ret = cpu_effective_str ? strcmp(cpu_effective_str, buf) : 1;
6341 + if (!ret) {
6342 + free(buf);
6338 6343 return 0;
6344 + }
6339 6345
6340 - strncpy(cpu_effective_str, buf, 1024);
6346 + free(cpu_effective_str);
6347 + cpu_effective_str = buf;
6341 6348 return 1;
6342 6349 }
6343 6350
@@ -8529,13 +8536,16 @@ end:
8529 8536 return ret;
8530 8537 }
8531 8538
8532 - char cpuset_buf[1024];
8533 - int initialize_cpu_set_from_sysfs(cpu_set_t *cpu_set, char *sysfs_path, char *sysfs_file)
8539 + int initialize_cpu_set_from_sysfs(cpu_set_t *cpu_set, const char *sysfs_path,
8540 + const char *sysfs_file)
8534 8541 {
8535 8542 FILE *fp;
8543 + char *cpuset_buf = NULL;
8544 + size_t size = 0;
8536 8545 char path[128];
8546 + int ret = -1;
8537 8547
8538 - if (snprintf(path, 128, "%s/%s", sysfs_path, sysfs_file) > 128)
8548 + if (snprintf(path, sizeof(path), "%s/%s", sysfs_path, sysfs_file) >= (int)sizeof(path))
8539 8549 err(-1, "%s %s", sysfs_path, sysfs_file);
8540 8550
8541 8551 fp = fopen(path, "r");
@@ -8543,19 +8553,20 @@ int initialize_cpu_set_from_sysfs(cpu_set_t *cpu_set, char *sysfs_path, char *sy
8543 8553 warn("open %s", path);
8544 8554 return -1;
8545 8555 }
8546 - if (fread(cpuset_buf, sizeof(char), 1024, fp) == 0) {
8556 + if (getline(&cpuset_buf, &size, fp) < 0) {
8547 8557 warn("read %s", sysfs_path);
8548 - goto err;
8558 + goto out;
8549 8559 }
8550 8560 if (parse_cpu_str(cpuset_buf, cpu_set, cpu_possible_setsize)) {
8551 - warnx("%s: cpu str malformat %s\n", sysfs_path, cpu_effective_str);
8552 - goto err;
8561 + warnx("%s: cpu str malformat %s\n", sysfs_path, cpuset_buf);
8562 + goto out;
8553 8563 }
8554 - return 0;
8564 + ret = 0;
8555 8565
8556 - err:
8566 + out:
8557 8567 fclose(fp);
8558 - return -1;
8568 + free(cpuset_buf);
8569 + return ret;
8559 8570 }
8560 8571
8561 8572 void print_cpu_set(char *s, cpu_set_t *set)
@@ -8655,6 +8666,8 @@ void rapl_perf_init(void)
8655 8666 {
8656 8667 const unsigned int num_domains = get_rapl_num_domains();
8657 8668 bool *domain_visited = calloc(num_domains, sizeof(bool));
8669 + if (!domain_visited)
8670 + err(-1, "calloc domain_visited");
8658 8671
8659 8672 rapl_counter_info_perdomain = calloc(num_domains, sizeof(*rapl_counter_info_perdomain));
8660 8673 if (rapl_counter_info_perdomain == NULL)
@@ -9471,8 +9484,10 @@ void perf_l2_init(void)
9471 9484 free_fd_l2_percpu();
9472 9485 return;
9473 9486 }
9474 - } else
9475 - err(-1, "%s: cpu%d: type %d", __func__, cpu, cpus[cpu].type);
9487 + } else {
9488 + warn("%s: cpu%d: type %d: Update kernel perf support or use \"--hide L2MRPS,L2%%hit\" or \"--hide cache\" or \"--no-perf\"", __func__, cpu, cpus[cpu].type);
9489 + return;
9490 + }
9476 9491 }
9477 9492 BIC_PRESENT(BIC_L2_MRPS);
9478 9493 BIC_PRESENT(BIC_L2_HIT);
@@ -9999,6 +10014,8 @@ int added_perf_counters_init_(struct perf_counter_info *pinfo)
9999 10014 const size_t max_num_domains = MAX(topo.max_cpu_num + 1, MAX(topo.max_core_id + 1, topo.max_package_id + 1));
10000 10015
10001 10016 domain_visited = calloc(max_num_domains, sizeof(*domain_visited));
10017 + if (!domain_visited)
10018 + errx(1, "%s: alloc %s", __func__, "domain_visited");
10002 10019
10003 10020 while (pinfo) {
10004 10021 switch (pinfo->scope) {
@@ -10390,6 +10407,8 @@ int pmt_add_counter(unsigned int guid, unsigned int seq, const char *name, enum
10390 10407 pcounter = pmt_find_counter(*pmt_root, name);
10391 10408 if (!pcounter) {
10392 10409 pcounter = calloc(1, sizeof(*pcounter));
10410 + if (!pcounter)
10411 + return 1;
10393 10412 new_counter = true;
10394 10413 }
10395 10414
@@ -10439,7 +10458,7 @@ void pmt_init(void)
10439 10458 mod_num = 0; /* Relative module number for current PMT file. */
10440 10459
10441 10460 /* Open the counter for each CPU. */
10442 - for (cpu_num = 0; cpu_num < topo.max_cpu_num;) {
10461 + for (cpu_num = 0; cpu_num <= topo.max_cpu_num;) {
10443 10462
10444 10463 if (cpu_is_not_allowed(cpu_num))
10445 10464 goto next_loop_iter;
@@ -10608,7 +10627,7 @@ int get_and_dump_counters(void)
10608 10627
10609 10628 void print_version()
10610 10629 {
10611 - fprintf(outf, "turbostat version 2026.04.21 - Len Brown <lenb@kernel.org>\n");
10630 + fprintf(outf, "turbostat version 2026.09.28 - Len Brown <lenb@kernel.org>\n");
10612 10631 }
10613 10632
10614 10633 #define COMMAND_LINE_SIZE 2048
@@ -10668,10 +10687,11 @@ int add_counter(unsigned int msr_num, char *path, char *name,
10668 10687 fprintf(stderr, "%s: %s FOUND\n", __func__, name);
10669 10688 break;
10670 10689 }
10671 - if (sys.added_thread_counters++ >= MAX_ADDED_THREAD_COUNTERS) {
10690 + if (sys.added_thread_counters >= MAX_ADDED_THREAD_COUNTERS) {
10672 10691 warnx("ignoring thread counter %s", name);
10673 10692 return -1;
10674 10693 }
10694 + sys.added_thread_counters++;
10675 10695 break;
10676 10696 case SCOPE_CORE:
10677 10697 msrp = find_msrp_by_name(sys.cp, name);
@@ -10680,10 +10700,11 @@ int add_counter(unsigned int msr_num, char *path, char *name,
10680 10700 fprintf(stderr, "%s: %s FOUND\n", __func__, name);
10681 10701 break;
10682 10702 }
10683 - if (sys.added_core_counters++ >= MAX_ADDED_CORE_COUNTERS) {
10703 + if (sys.added_core_counters >= MAX_ADDED_CORE_COUNTERS) {
10684 10704 warnx("ignoring core counter %s", name);
10685 10705 return -1;
10686 10706 }
10707 + sys.added_core_counters++;
10687 10708 break;
10688 10709 case SCOPE_PACKAGE:
10689 10710 msrp = find_msrp_by_name(sys.pp, name);
@@ -10692,10 +10713,11 @@ int add_counter(unsigned int msr_num, char *path, char *name,
10692 10713 fprintf(stderr, "%s: %s FOUND\n", __func__, name);
10693 10714 break;
10694 10715 }
10695 - if (sys.added_package_counters++ >= MAX_ADDED_PACKAGE_COUNTERS) {
10716 + if (sys.added_package_counters >= MAX_ADDED_PACKAGE_COUNTERS) {
10696 10717 warnx("ignoring package counter %s", name);
10697 10718 return -1;
10698 10719 }
10720 + sys.added_package_counters++;
10699 10721 break;
10700 10722 default:
10701 10723 warnx("ignoring counter %s with unknown scope", name);
modified tools/testing/selftests/Makefile
@@ -43,6 +43,7 @@ TARGETS += filesystems/open_tree_ns
43 43 TARGETS += filesystems/overlayfs
44 44 TARGETS += filesystems/statmount
45 45 TARGETS += filesystems/mount-notify
46 + TARGETS += filesystems/mount_cycle
46 47 TARGETS += filesystems/nsfs
47 48 TARGETS += filesystems/fuse
48 49 TARGETS += filesystems/move_mount
@@ -50,6 +51,8 @@ TARGETS += filesystems/empty_mntns
50 51 TARGETS += filesystems/fsmount_ns
51 52 TARGETS += filesystems/fscontext_ns
52 53 TARGETS += filesystems/xattr
54 + TARGETS += filesystems/mntns_unbindable
55 + TARGETS += filesystems/umount_propagation
53 56 TARGETS += firmware
54 57 TARGETS += fpu
55 58 TARGETS += ftrace
modified tools/testing/selftests/drivers/net/mlxsw/port_range_occ.sh
@@ -9,6 +9,7 @@ lib_dir=$(dirname $0)/../../../net/forwarding
9 9
10 10 ALL_TESTS="
11 11 port_range_occ_test
12 + port_range_occ_tmplt_test
12 13 "
13 14 NUM_NETIFS=2
14 15 source $lib_dir/lib.sh
@@ -101,6 +102,31 @@ port_range_occ_test()
101 102 log_test "port range occupancy"
102 103 }
103 104
105 + port_range_occ_tmplt_test()
106 + {
107 + local occ
108 +
109 + RET=0
110 + occ=$(port_range_occ_get)
111 +
112 + # Addition of a chain template should not impact occupancy.
113 + tc chain add dev "$swp1" ingress chain 1 protocol ip \
114 + flower ip_proto udp src_port 501-600 dst_port 701-800
115 + check_err $? "Could not add chain template"
116 +
117 + (( occ == $(port_range_occ_get) ))
118 + check_err $? "Got occupancy $(port_range_occ_get), expected $occ"
119 +
120 + # And just for completeness sake, neither should deletion.
121 + tc chain del dev "$swp1" ingress chain 1
122 + check_err $? "Could not delete chain template"
123 +
124 + (( occ == $(port_range_occ_get) ))
125 + check_err $? "Got occupancy $(port_range_occ_get), expected $occ"
126 +
127 + log_test "port range occupancy after template create/destroy"
128 + }
129 +
104 130 trap cleanup EXIT
105 131
106 132 setup_prepare
modified tools/testing/selftests/filesystems/.gitignore
@@ -7,3 +7,4 @@ anon_inode_test
7 7 kernfs_test
8 8 idmapped_tmpfile
9 9 ustat_test
10 + rw_hint_test
modified tools/testing/selftests/filesystems/Makefile
@@ -1,7 +1,7 @@
1 1 # SPDX-License-Identifier: GPL-2.0
2 2
3 3 CFLAGS += $(KHDR_INCLUDES)
4 - TEST_GEN_PROGS := devpts_pts file_stressor anon_inode_test kernfs_test fclog ustat_test
4 + TEST_GEN_PROGS := devpts_pts file_stressor anon_inode_test kernfs_test fclog ustat_test rw_hint_test
5 5 TEST_GEN_PROGS += idmapped_tmpfile
6 6 TEST_GEN_PROGS_EXTENDED := dnotify_test
7 7
modified tools/testing/selftests/filesystems/empty_mntns/.gitignore
@@ -2,3 +2,6 @@
2 2 clone3_empty_mntns_test
3 3 empty_mntns_test
4 4 overmount_chroot_test
5 + internal_sb_reconfigure_test
6 + nullfs_atime_test
7 + root_readdir_test
modified tools/testing/selftests/filesystems/empty_mntns/Makefile
@@ -4,9 +4,14 @@ CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES) $(TOOLS_INCLUDES)
4 4 LDLIBS += -lcap
5 5
6 6 TEST_GEN_PROGS := empty_mntns_test overmount_chroot_test clone3_empty_mntns_test
7 + TEST_GEN_PROGS += internal_sb_reconfigure_test nullfs_atime_test root_readdir_test
8 +
9 + LOCAL_HDRS += ../readdir_hold.h
7 10
8 11 include ../../lib.mk
9 12
10 13 $(OUTPUT)/empty_mntns_test: ../utils.c
11 14 $(OUTPUT)/overmount_chroot_test: ../utils.c
12 15 $(OUTPUT)/clone3_empty_mntns_test: ../utils.c
16 + $(OUTPUT)/internal_sb_reconfigure_test: ../utils.c
17 + $(OUTPUT)/root_readdir_test: LDLIBS += -pthread
added tools/testing/selftests/filesystems/empty_mntns/internal_sb_reconfigure_test.c mode 100644
@@ -0,0 +1,108 @@
1 + // SPDX-License-Identifier: GPL-2.0-or-later
2 + /*
3 + * The root of an empty mount namespace is a nullfs mount. Its superblock is
4 + * kernel-internal and shared by every mount namespace. It can't be
5 + * reconfigured, neither through fspick() nor through mount(MS_REMOUNT) nor
6 + * through umount() of the root which remounts it read-only.
7 + */
8 + #define _GNU_SOURCE
9 + #include <errno.h>
10 + #include <fcntl.h>
11 + #include <sched.h>
12 + #include <stdio.h>
13 + #include <string.h>
14 + #include <sys/mount.h>
15 + #include <sys/statfs.h>
16 + #include <sys/statvfs.h>
17 + #include <sys/syscall.h>
18 + #include <sys/vfs.h>
19 + #include <sys/wait.h>
20 + #include <unistd.h>
21 +
22 + #include "../utils.h"
23 + #include "../wrappers.h"
24 + #include "empty_mntns.h"
25 + #include "kselftest_harness.h"
26 +
27 + #ifndef __NR_fspick
28 + #define __NR_fspick 433
29 + #endif
30 +
31 + static int sys_fspick(int dfd, const char *path, unsigned int flags)
32 + {
33 + return syscall(__NR_fspick, dfd, path, flags);
34 + }
35 +
36 + /* Child exit codes. */
37 + enum {
38 + CHILD_OK,
39 + CHILD_USERNS, /* could not create the user namespace */
40 + CHILD_UNSHARE, /* could not create the empty mount namespace */
41 + CHILD_FSPICK, /* fspick() of the root was not refused with EINVAL */
42 + CHILD_REMOUNT, /* mount(MS_REMOUNT) was not refused with EINVAL */
43 + CHILD_UMOUNT, /* umount() of the root succeeded */
44 + CHILD_STATFS, /* statfs() of the root failed */
45 + CHILD_RDONLY, /* the root ended up read-only */
46 + };
47 +
48 + static int empty_mntns_child(void)
49 + {
50 + struct statfs st;
51 +
52 + if (enter_userns())
53 + return CHILD_USERNS;
54 + if (unshare(UNSHARE_EMPTY_MNTNS))
55 + return CHILD_UNSHARE;
56 +
57 + if (sys_fspick(AT_FDCWD, "/", 0) >= 0 || errno != EINVAL)
58 + return CHILD_FSPICK;
59 + if (!mount(NULL, "/", NULL, MS_REMOUNT | MS_RDONLY, NULL) ||
60 + errno != EINVAL)
61 + return CHILD_REMOUNT;
62 + if (!umount2("/", 0))
63 + return CHILD_UMOUNT;
64 + if (statfs("/", &st))
65 + return CHILD_STATFS;
66 + if (st.f_flags & ST_RDONLY)
67 + return CHILD_RDONLY;
68 + return CHILD_OK;
69 + }
70 +
71 + FIXTURE(internal_sb_reconfigure) {};
72 +
73 + FIXTURE_SETUP(internal_sb_reconfigure)
74 + {
75 + pid_t pid;
76 + int status;
77 +
78 + pid = fork();
79 + ASSERT_GE(pid, 0);
80 + if (pid == 0) {
81 + if (enter_userns())
82 + _exit(1);
83 + if (unshare(UNSHARE_EMPTY_MNTNS))
84 + _exit(1);
85 + _exit(0);
86 + }
87 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
88 + if (!WIFEXITED(status) || WEXITSTATUS(status))
89 + SKIP(return, "UNSHARE_EMPTY_MNTNS not supported");
90 + }
91 +
92 + FIXTURE_TEARDOWN(internal_sb_reconfigure) {}
93 +
94 + TEST_F(internal_sb_reconfigure, nullfs_root)
95 + {
96 + pid_t pid;
97 + int status;
98 +
99 + pid = fork();
100 + ASSERT_GE(pid, 0);
101 + if (pid == 0)
102 + _exit(empty_mntns_child());
103 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
104 + ASSERT_TRUE(WIFEXITED(status));
105 + ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
106 + }
107 +
108 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/empty_mntns/nullfs_atime_test.c mode 100644
@@ -0,0 +1,129 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * The root of every empty mount namespace is the same nullfs inode. A read
4 + * of it by one user must not change the access time another user sees.
5 + */
6 + #define _GNU_SOURCE
7 + #include <dirent.h>
8 + #include <errno.h>
9 + #include <fcntl.h>
10 + #include <sched.h>
11 + #include <stdio.h>
12 + #include <stdlib.h>
13 + #include <string.h>
14 + #include <unistd.h>
15 + #include <sys/stat.h>
16 + #include <sys/wait.h>
17 +
18 + #include "../../kselftest_harness.h"
19 +
20 + #ifndef UNSHARE_EMPTY_MNTNS
21 + #define UNSHARE_EMPTY_MNTNS 0x00100000
22 + #endif
23 +
24 + enum {
25 + CHILD_OK,
26 + CHILD_UNSUPPORTED,
27 + CHILD_SETUP,
28 + CHILD_CHANGED,
29 + };
30 +
31 + static int wait_byte(int fd)
32 + {
33 + char c;
34 +
35 + return read(fd, &c, 1) == 1 ? 0 : -1;
36 + }
37 +
38 + static int send_byte(int fd)
39 + {
40 + return write(fd, "x", 1) == 1 ? 0 : -1;
41 + }
42 +
43 + static int empty_mntns(void)
44 + {
45 + if (!unshare(UNSHARE_EMPTY_MNTNS))
46 + return 0;
47 + return errno == EINVAL ? CHILD_UNSUPPORTED : CHILD_SETUP;
48 + }
49 +
50 + /* the watcher: stats its root before and after the reader read its own */
51 + static int watcher(int to_reader, int from_reader)
52 + {
53 + struct stat before, after;
54 + int ret;
55 +
56 + ret = empty_mntns();
57 + if (ret)
58 + return ret;
59 + if (stat("/", &before))
60 + return CHILD_SETUP;
61 + if (send_byte(to_reader) || wait_byte(from_reader))
62 + return CHILD_SETUP;
63 + if (stat("/", &after))
64 + return CHILD_SETUP;
65 + if (before.st_atim.tv_sec != after.st_atim.tv_sec ||
66 + before.st_atim.tv_nsec != after.st_atim.tv_nsec)
67 + return CHILD_CHANGED;
68 + return CHILD_OK;
69 + }
70 +
71 + /* the reader: lists its own root, which is the same inode */
72 + static int reader(int to_watcher, int from_watcher)
73 + {
74 + struct dirent *de;
75 + DIR *d;
76 + int ret;
77 +
78 + ret = empty_mntns();
79 + if (ret)
80 + return ret;
81 + if (wait_byte(from_watcher))
82 + return CHILD_SETUP;
83 + d = opendir("/");
84 + if (!d)
85 + return CHILD_SETUP;
86 + while ((de = readdir(d)))
87 + ;
88 + closedir(d);
89 + return send_byte(to_watcher) ? CHILD_SETUP : CHILD_OK;
90 + }
91 +
92 + static int wait_child(pid_t pid)
93 + {
94 + int status;
95 +
96 + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
97 + return -1;
98 + return WEXITSTATUS(status);
99 + }
100 +
101 + TEST(empty_mntns_root_atime)
102 + {
103 + int to_reader[2], to_watcher[2], w, r;
104 + pid_t watcher_pid, reader_pid;
105 +
106 + if (geteuid())
107 + SKIP(return, "test requires root");
108 + ASSERT_EQ(pipe(to_reader), 0);
109 + ASSERT_EQ(pipe(to_watcher), 0);
110 +
111 + watcher_pid = fork();
112 + ASSERT_GE(watcher_pid, 0);
113 + if (watcher_pid == 0)
114 + _exit(watcher(to_reader[1], to_watcher[0]));
115 + reader_pid = fork();
116 + ASSERT_GE(reader_pid, 0);
117 + if (reader_pid == 0)
118 + _exit(reader(to_watcher[1], to_reader[0]));
119 +
120 + r = wait_child(reader_pid);
121 + w = wait_child(watcher_pid);
122 + if (r == CHILD_UNSUPPORTED || w == CHILD_UNSUPPORTED)
123 + SKIP(return, "UNSHARE_EMPTY_MNTNS not supported");
124 + EXPECT_EQ(r, CHILD_OK);
125 + EXPECT_EQ(w, CHILD_OK)
126 + TH_LOG("the access time of the root changed while this namespace did nothing");
127 + }
128 +
129 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/empty_mntns/root_readdir_test.c mode 100644
@@ -0,0 +1,45 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * Reading the root of an empty mount namespace holds nothing that anybody
4 + * else waits for: the directory never has an entry, so a readdir stuck in
5 + * the page fault of its buffer stalls neither a create nor a lookup in it.
6 + */
7 + #define _GNU_SOURCE
8 + #include <errno.h>
9 + #include <fcntl.h>
10 + #include <sched.h>
11 + #include <stdio.h>
12 + #include <stdlib.h>
13 + #include <unistd.h>
14 +
15 + #include "../../kselftest_harness.h"
16 + #include "../readdir_hold.h"
17 + #include "empty_mntns.h"
18 +
19 + TEST(readdir_blocks_nobody)
20 + {
21 + struct readdir_hold hold;
22 + bool stalled;
23 + int dfd;
24 +
25 + if (geteuid())
26 + SKIP(return, "test requires root");
27 + if (readdir_hold_init(&hold))
28 + SKIP(return, "test requires userfaultfd");
29 + if (unshare(UNSHARE_EMPTY_MNTNS)) {
30 + readdir_hold_destroy(&hold);
31 + if (errno == EINVAL)
32 + SKIP(return, "UNSHARE_EMPTY_MNTNS not supported");
33 + ASSERT_TRUE(false)
34 + TH_LOG("unshare(UNSHARE_EMPTY_MNTNS): %m");
35 + }
36 + dfd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
37 + ASSERT_GE(dfd, 0);
38 + ASSERT_EQ(readdir_hold_check(&hold, dfd, &stalled), 0);
39 + /* the lookup came back while the readdir was stuck in its fault */
40 + EXPECT_FALSE(stalled);
41 + close(dfd);
42 + readdir_hold_destroy(&hold);
43 + }
44 +
45 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mntns_unbindable/Makefile mode 100644
@@ -0,0 +1,6 @@
1 + # SPDX-License-Identifier: GPL-2.0
2 + TEST_GEN_PROGS := mntns_unbindable_test
3 +
4 + CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
5 +
6 + include ../../lib.mk
added tools/testing/selftests/filesystems/mntns_unbindable/mntns_unbindable_test.c mode 100644
@@ -0,0 +1,227 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * An unbindable mount stays unbindable in a cloned mount namespace.
4 + */
5 + #define _GNU_SOURCE
6 + #include <errno.h>
7 + #include <fcntl.h>
8 + #include <sched.h>
9 + #include <stdio.h>
10 + #include <stdlib.h>
11 + #include <string.h>
12 + #include <sys/mount.h>
13 + #include <sys/stat.h>
14 + #include <sys/syscall.h>
15 + #include <sys/wait.h>
16 + #include <unistd.h>
17 +
18 + #include "../../kselftest_harness.h"
19 +
20 + #ifndef OPEN_TREE_CLONE
21 + #define OPEN_TREE_CLONE 1
22 + #endif
23 + #ifndef OPEN_TREE_CLOEXEC
24 + #define OPEN_TREE_CLOEXEC O_CLOEXEC
25 + #endif
26 +
27 + static int sys_open_tree(int dfd, const char *filename, unsigned int flags)
28 + {
29 + return syscall(__NR_open_tree, dfd, filename, flags);
30 + }
31 +
32 + /* Child exit codes. */
33 + enum {
34 + CHILD_OK, /* the operation failed with EINVAL as it must */
35 + CHILD_ALLOWED, /* the operation succeeded: the flag was lost */
36 + CHILD_UNSHARE, /* unshare(CLONE_NEWNS) failed */
37 + CHILD_ERRNO, /* the operation failed with some other errno */
38 + CHILD_MOUNTINFO, /* the mount was not found in mountinfo */
39 + };
40 +
41 + FIXTURE(mntns_unbindable)
42 + {
43 + char base[64];
44 + char src[80];
45 + char dst[80];
46 + bool mounted;
47 + };
48 +
49 + FIXTURE_SETUP(mntns_unbindable)
50 + {
51 + self->mounted = false;
52 +
53 + if (geteuid() != 0)
54 + SKIP(return, "test requires CAP_SYS_ADMIN");
55 +
56 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
57 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
58 +
59 + snprintf(self->base, sizeof(self->base), "/tmp/mntns_unbindable.XXXXXX");
60 + ASSERT_NE(mkdtemp(self->base), NULL);
61 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, NULL), 0);
62 + self->mounted = true;
63 +
64 + snprintf(self->src, sizeof(self->src), "%s/src", self->base);
65 + snprintf(self->dst, sizeof(self->dst), "%s/dst", self->base);
66 + ASSERT_EQ(mkdir(self->src, 0755), 0);
67 + ASSERT_EQ(mkdir(self->dst, 0755), 0);
68 +
69 + ASSERT_EQ(mount("tmpfs", self->src, "tmpfs", 0, NULL), 0);
70 + ASSERT_EQ(mount(NULL, self->src, NULL, MS_UNBINDABLE, NULL), 0);
71 + }
72 +
73 + FIXTURE_TEARDOWN(mntns_unbindable)
74 + {
75 + if (self->mounted)
76 + umount2(self->base, MNT_DETACH);
77 + rmdir(self->base);
78 + }
79 +
80 + static int classify(int ret, int err)
81 + {
82 + if (ret >= 0)
83 + return CHILD_ALLOWED;
84 + return err == EINVAL ? CHILD_OK : CHILD_ERRNO;
85 + }
86 +
87 + /* Is the mount on @mountpoint marked unbindable in /proc/self/mountinfo? */
88 + static int mountinfo_unbindable(const char *mountpoint)
89 + {
90 + char line[4096];
91 + FILE *f;
92 + int ret = CHILD_MOUNTINFO;
93 +
94 + f = fopen("/proc/self/mountinfo", "re");
95 + if (!f)
96 + return CHILD_ERRNO;
97 +
98 + while (fgets(line, sizeof(line), f)) {
99 + char *fields[6], *p = line, *opt;
100 + int i;
101 +
102 + for (i = 0; i < 6; i++) {
103 + fields[i] = strsep(&p, " ");
104 + if (!fields[i])
105 + break;
106 + }
107 + if (i < 6 || strcmp(fields[4], mountpoint))
108 + continue;
109 +
110 + /* the optional fields, up to the "-" separator */
111 + ret = CHILD_ALLOWED;
112 + while ((opt = strsep(&p, " ")) && strcmp(opt, "-")) {
113 + if (!strcmp(opt, "unbindable"))
114 + ret = CHILD_OK;
115 + }
116 + break;
117 + }
118 + fclose(f);
119 + return ret;
120 + }
121 +
122 + static int run_in_child(int (*fn)(const char *src, const char *dst),
123 + const char *src, const char *dst)
124 + {
125 + int status;
126 + pid_t pid;
127 +
128 + pid = fork();
129 + if (pid < 0)
130 + return -1;
131 + if (pid == 0)
132 + _exit(fn(src, dst));
133 + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
134 + return -1;
135 + return WEXITSTATUS(status);
136 + }
137 +
138 + static int bind_after_clone(const char *src, const char *dst)
139 + {
140 + int ret;
141 +
142 + if (unshare(CLONE_NEWNS))
143 + return CHILD_UNSHARE;
144 + ret = mount(src, dst, NULL, MS_BIND, NULL);
145 + return classify(ret, errno);
146 + }
147 +
148 + static int rbind_after_clone(const char *src, const char *dst)
149 + {
150 + int ret;
151 +
152 + if (unshare(CLONE_NEWNS))
153 + return CHILD_UNSHARE;
154 + ret = mount(src, dst, NULL, MS_BIND | MS_REC, NULL);
155 + return classify(ret, errno);
156 + }
157 +
158 + static int open_tree_after_clone(const char *src, const char *dst)
159 + {
160 + int ret;
161 +
162 + if (unshare(CLONE_NEWNS))
163 + return CHILD_UNSHARE;
164 + ret = sys_open_tree(AT_FDCWD, src, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
165 + return classify(ret, errno);
166 + }
167 +
168 + static int mountinfo_after_clone(const char *src, const char *dst)
169 + {
170 + if (unshare(CLONE_NEWNS))
171 + return CHILD_UNSHARE;
172 + return mountinfo_unbindable(src);
173 + }
174 +
175 + static int bind_after_two_clones(const char *src, const char *dst)
176 + {
177 + int ret;
178 +
179 + if (unshare(CLONE_NEWNS))
180 + return CHILD_UNSHARE;
181 + if (unshare(CLONE_NEWNS))
182 + return CHILD_UNSHARE;
183 + ret = mount(src, dst, NULL, MS_BIND, NULL);
184 + return classify(ret, errno);
185 + }
186 +
187 + /* The namespace the mount was made unbindable in. */
188 + TEST_F(mntns_unbindable, refuses_bind)
189 + {
190 + int ret = mount(self->src, self->dst, NULL, MS_BIND, NULL);
191 +
192 + ASSERT_EQ(classify(ret, errno), CHILD_OK);
193 + ASSERT_EQ(mountinfo_unbindable(self->src), CHILD_OK);
194 + }
195 +
196 + /* A copy of the namespace must not turn the mount bindable. */
197 + TEST_F(mntns_unbindable, refuses_bind_after_clone)
198 + {
199 + ASSERT_EQ(run_in_child(bind_after_clone, self->src, self->dst), CHILD_OK)
200 + TH_LOG("bind of an unbindable mount allowed in a copied mount namespace");
201 + }
202 +
203 + TEST_F(mntns_unbindable, refuses_rbind_after_clone)
204 + {
205 + ASSERT_EQ(run_in_child(rbind_after_clone, self->src, self->dst), CHILD_OK)
206 + TH_LOG("rbind of an unbindable mount allowed in a copied mount namespace");
207 + }
208 +
209 + TEST_F(mntns_unbindable, refuses_open_tree_after_clone)
210 + {
211 + ASSERT_EQ(run_in_child(open_tree_after_clone, self->src, self->dst), CHILD_OK)
212 + TH_LOG("OPEN_TREE_CLONE of an unbindable mount allowed in a copied mount namespace");
213 + }
214 +
215 + TEST_F(mntns_unbindable, mountinfo_after_clone)
216 + {
217 + ASSERT_EQ(run_in_child(mountinfo_after_clone, self->src, self->dst), CHILD_OK)
218 + TH_LOG("mountinfo does not show the mount as unbindable in a copied mount namespace");
219 + }
220 +
221 + TEST_F(mntns_unbindable, refuses_bind_after_two_clones)
222 + {
223 + ASSERT_EQ(run_in_child(bind_after_two_clones, self->src, self->dst), CHILD_OK)
224 + TH_LOG("bind of an unbindable mount allowed two mount namespace copies down");
225 + }
226 +
227 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/.gitignore mode 100644
@@ -0,0 +1,8 @@
1 + # SPDX-License-Identifier: GPL-2.0-only
2 + loop_cycle_test
3 + unmounted_tree_test
4 + overmount_reparent_test
5 + mount_cover_test
6 + locked_handle_test
7 + nsfs_rbind_loop_test
8 + overmount_ns_file_test
added tools/testing/selftests/filesystems/mount_cycle/Makefile mode 100644
@@ -0,0 +1,12 @@
1 + # SPDX-License-Identifier: GPL-2.0
2 + TEST_GEN_PROGS := loop_cycle_test unmounted_tree_test overmount_reparent_test mount_cover_test locked_handle_test
3 + TEST_GEN_PROGS += nsfs_rbind_loop_test overmount_ns_file_test
4 +
5 + CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
6 +
7 + LOCAL_HDRS += ../readdir_hold.h
8 +
9 + include ../../lib.mk
10 +
11 + $(OUTPUT)/locked_handle_test: LDLIBS += -pthread
12 + $(OUTPUT)/mount_cover_test: LDLIBS += -pthread
added tools/testing/selftests/filesystems/mount_cycle/config mode 100644
@@ -0,0 +1,39 @@
1 + CONFIG_USER_NS=y
2 + CONFIG_TMPFS=y
3 + CONFIG_BLK_DEV_LOOP=y
4 + CONFIG_VFAT_FS=y
5 + CONFIG_MSDOS_FS=y
6 + CONFIG_NLS_CODEPAGE_437=y
7 + CONFIG_NLS_ISO8859_1=y
8 + CONFIG_MINIX_FS=y
9 + CONFIG_AUTOFS_FS=y
10 + CONFIG_ZRAM=y
11 + CONFIG_ZRAM_WRITEBACK=y
12 + CONFIG_KEYS=y
13 + CONFIG_ECRYPT_FS=y
14 + CONFIG_BINFMT_MISC=y
15 + CONFIG_FUSE_FS=y
16 + CONFIG_FUSE_PASSTHROUGH=y
17 + CONFIG_BLK_DEV_ZONED=y
18 + CONFIG_BLK_DEV_ZONED_LOOP=y
19 + CONFIG_CONFIGFS_FS=y
20 + CONFIG_USB_SUPPORT=y
21 + CONFIG_USB=y
22 + CONFIG_USB_STORAGE=y
23 + CONFIG_SCSI=y
24 + CONFIG_BLK_DEV_SD=y
25 + CONFIG_USB_GADGET=y
26 + CONFIG_USB_DUMMY_HCD=y
27 + CONFIG_USB_CONFIGFS=y
28 + CONFIG_USB_CONFIGFS_MASS_STORAGE=y
29 + CONFIG_MD=y
30 + CONFIG_BLK_DEV_MD=y
31 + CONFIG_MD_RAID1=y
32 + CONFIG_MD_BITMAP=y
33 + CONFIG_MD_BITMAP_FILE=y
34 + CONFIG_INOTIFY_USER=y
35 + CONFIG_DNOTIFY=y
36 + CONFIG_FANOTIFY=y
37 + CONFIG_FILE_LOCKING=y
38 + CONFIG_CRYPTO_AES=y
39 + CONFIG_USERFAULTFD=y
added tools/testing/selftests/filesystems/mount_cycle/locked_handle_test.c mode 100644
@@ -0,0 +1,377 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * may_decode_fh() refuses a file handle below a mount with locked children
4 + * to root in a user namespace. That has to hold while the mount is lazily
5 + * unmounted and its children, the locked ones too, are taken off it.
6 + */
7 + #define _GNU_SOURCE
8 + #include <errno.h>
9 + #include <fcntl.h>
10 + #include <pthread.h>
11 + #include <sched.h>
12 + #include <stdatomic.h>
13 + #include <stdbool.h>
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <unistd.h>
18 + #include <sys/mount.h>
19 + #include <sys/prctl.h>
20 + #include <sys/stat.h>
21 + #include <sys/syscall.h>
22 + #include <sys/wait.h>
23 +
24 + #include "../../kselftest_harness.h"
25 +
26 + #ifndef OPEN_TREE_CLONE
27 + #define OPEN_TREE_CLONE 1
28 + #endif
29 + #ifndef OPEN_TREE_CLOEXEC
30 + #define OPEN_TREE_CLOEXEC O_CLOEXEC
31 + #endif
32 + #ifndef AT_RECURSIVE
33 + #define AT_RECURSIVE 0x8000
34 + #endif
35 +
36 + #define DIR_LEN 64
37 + #define PATH_LEN 128
38 +
39 + #define ROUNDS 100 /* lazy umounts raced per test */
40 + #define RACERS 3 /* threads in open_by_handle_at() */
41 + #define EXTRA_MOUNTS 64 /* make umount_tree() hold mount_lock longer */
42 + #define MAX_DELAY_US 3000 /* before the umount */
43 + #define TAIL_US 2000 /* after it */
44 +
45 + struct handle {
46 + struct file_handle fh;
47 + unsigned char buf[MAX_HANDLE_SZ];
48 + };
49 +
50 + /* exit codes of the child */
51 + enum {
52 + CHILD_OK,
53 + CHILD_SETUP,
54 + CHILD_DECODED, /* decoded past a locked child */
55 + CHILD_MOUNTED, /* not refused while mounted */
56 + CHILD_UNMOUNTED, /* not refused once unmounted */
57 + CHILD_ALLOWED, /* refused where nothing is locked */
58 + CHILD_NOUSERNS, /* no user namespace to be had */
59 + };
60 +
61 + static int write_file(const char *path, const char *s)
62 + {
63 + ssize_t n = -1;
64 + int fd;
65 +
66 + fd = open(path, O_WRONLY | O_CLOEXEC);
67 + if (fd >= 0) {
68 + n = write(fd, s, strlen(s));
69 + close(fd);
70 + }
71 + return n == (ssize_t)strlen(s) ? 0 : -1;
72 + }
73 +
74 + /* Become root in a new user namespace with a private mount namespace. */
75 + static int enter_userns(void)
76 + {
77 + uid_t uid = getuid();
78 + gid_t gid = getgid();
79 + char map[32];
80 +
81 + prctl(PR_SET_DUMPABLE, 1);
82 + /* EINVAL: no USER_NS, ENOSPC: user.max_user_namespaces is 0, EPERM: an LSM */
83 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
84 + return errno == EINVAL || errno == ENOSPC || errno == EPERM ?
85 + CHILD_NOUSERNS : CHILD_SETUP;
86 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
87 + return CHILD_SETUP;
88 + snprintf(map, sizeof(map), "0 %d 1", uid);
89 + if (write_file("/proc/self/uid_map", map))
90 + return CHILD_SETUP;
91 + snprintf(map, sizeof(map), "0 %d 1", gid);
92 + if (write_file("/proc/self/gid_map", map))
93 + return CHILD_SETUP;
94 + if (setgid(0) || setuid(0))
95 + return CHILD_SETUP;
96 + if (mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
97 + return CHILD_SETUP;
98 + return CHILD_OK;
99 + }
100 +
101 + static int get_handle(const char *path, struct handle *h)
102 + {
103 + int mntid;
104 +
105 + h->fh.handle_bytes = MAX_HANDLE_SZ;
106 + return name_to_handle_at(AT_FDCWD, path, &h->fh, &mntid, 0);
107 + }
108 +
109 + static int decode(int dfd, struct handle *h)
110 + {
111 + return open_by_handle_at(dfd, &h->fh, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
112 + }
113 +
114 + struct race {
115 + int dfd;
116 + struct handle *h;
117 + atomic_int go;
118 + atomic_int stop;
119 + atomic_int won; /* the first decoded descriptor */
120 + };
121 +
122 + static void *racer(void *arg)
123 + {
124 + struct race *r = arg;
125 +
126 + while (!atomic_load(&r->go))
127 + ;
128 + while (!atomic_load(&r->stop)) {
129 + int none = -1;
130 + int fd;
131 +
132 + fd = decode(r->dfd, r->h);
133 + if (fd < 0)
134 + continue;
135 + if (!atomic_compare_exchange_strong(&r->won, &none, fd))
136 + close(fd);
137 + }
138 + return NULL;
139 + }
140 +
141 + /* stop the @n racers started so far and wait for them, they spin on @r */
142 + static void stop_racers(struct race *r, pthread_t *th, int n)
143 + {
144 + int i;
145 +
146 + atomic_store(&r->stop, 1);
147 + atomic_store(&r->go, 1); /* one still waiting for the start sees stop next */
148 + for (i = 0; i < n; i++)
149 + pthread_join(th[i], NULL);
150 + }
151 +
152 + /*
153 + * Bind @h recursively at @w, or take a detached copy of it, and race
154 + * open_by_handle_at() of @inner against the lazy umount. The decoded
155 + * descriptor, if there was one, is left in @won.
156 + */
157 + static int race_round(const char *h, const char *w, struct handle *inner,
158 + bool dissolve, int *won)
159 + {
160 + struct race r = { .h = inner, .won = -1 };
161 + pthread_t th[RACERS];
162 + int treefd = -1, fd, i;
163 +
164 + if (dissolve) {
165 + treefd = syscall(__NR_open_tree, AT_FDCWD, h,
166 + OPEN_TREE_CLONE | AT_RECURSIVE | OPEN_TREE_CLOEXEC);
167 + if (treefd < 0)
168 + return CHILD_SETUP;
169 + /* an ordinary descriptor on the copy, treefd's close dissolves it */
170 + r.dfd = openat(treefd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
171 + } else {
172 + if (mount(h, w, NULL, MS_BIND | MS_REC, NULL))
173 + return CHILD_SETUP;
174 + r.dfd = open(w, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
175 + }
176 + if (r.dfd < 0)
177 + return CHILD_SETUP;
178 +
179 + fd = decode(r.dfd, inner);
180 + if (fd >= 0 || errno != EPERM) {
181 + if (fd >= 0)
182 + close(fd);
183 + return CHILD_MOUNTED;
184 + }
185 +
186 + for (i = 0; i < RACERS; i++) {
187 + if (pthread_create(&th[i], NULL, racer, &r)) {
188 + stop_racers(&r, th, i);
189 + return CHILD_SETUP;
190 + }
191 + }
192 + atomic_store(&r.go, 1);
193 + usleep(rand() % MAX_DELAY_US);
194 + if (dissolve)
195 + close(treefd);
196 + else if (umount2(w, MNT_DETACH)) {
197 + stop_racers(&r, th, RACERS);
198 + return CHILD_SETUP;
199 + }
200 + usleep(TAIL_US);
201 + stop_racers(&r, th, RACERS);
202 +
203 + fd = decode(r.dfd, inner);
204 + if (fd >= 0) {
205 + close(fd);
206 + return CHILD_UNMOUNTED;
207 + }
208 + close(r.dfd);
209 + *won = atomic_load(&r.won);
210 + return CHILD_OK;
211 + }
212 +
213 + static int race_child(const char *h, const char *w, struct handle *inner,
214 + bool dissolve)
215 + {
216 + int ret, won, i;
217 +
218 + srand(getpid());
219 + ret = enter_userns();
220 + if (ret)
221 + return ret;
222 + for (i = 0; i < ROUNDS; i++) {
223 + ret = race_round(h, w, inner, dissolve, &won);
224 + if (ret)
225 + return ret;
226 + if (won >= 0)
227 + return CHILD_DECODED;
228 + }
229 + return CHILD_OK;
230 + }
231 +
232 + /* a bind without locked children decodes while mounted and not after */
233 + static int allowed_child(const char *plain, const char *w, struct handle *h)
234 + {
235 + int dfd, fd, ret;
236 +
237 + ret = enter_userns();
238 + if (ret)
239 + return ret;
240 + if (mount(plain, w, NULL, MS_BIND | MS_REC, NULL))
241 + return CHILD_SETUP;
242 + dfd = open(w, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
243 + if (dfd < 0)
244 + return CHILD_SETUP;
245 + fd = decode(dfd, h);
246 + if (fd < 0)
247 + return CHILD_ALLOWED;
248 + close(fd);
249 + if (umount2(w, MNT_DETACH))
250 + return CHILD_SETUP;
251 + fd = decode(dfd, h);
252 + if (fd >= 0) {
253 + close(fd);
254 + return CHILD_UNMOUNTED;
255 + }
256 + return errno == EPERM ? CHILD_OK : CHILD_UNMOUNTED;
257 + }
258 +
259 + FIXTURE(locked_handle) {
260 + char base[DIR_LEN];
261 + char h[PATH_LEN]; /* the tree with the covered directory */
262 + char plain[PATH_LEN]; /* a tree with no mount in it */
263 + char w[PATH_LEN]; /* where the child binds either */
264 + struct handle inner; /* h/top/secret/inner, covered */
265 + struct handle uncovered; /* plain/inner */
266 + };
267 +
268 + FIXTURE_SETUP(locked_handle)
269 + {
270 + char p[PATH_LEN], e[PATH_LEN];
271 + int i;
272 +
273 + if (geteuid())
274 + SKIP(return, "test requires root");
275 +
276 + snprintf(self->base, sizeof(self->base), "/tmp/locked_handle.XXXXXX");
277 + ASSERT_NE(mkdtemp(self->base), NULL);
278 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
279 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
280 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, NULL), 0);
281 +
282 + snprintf(self->h, sizeof(self->h), "%s/h", self->base);
283 + snprintf(self->plain, sizeof(self->plain), "%s/plain", self->base);
284 + snprintf(self->w, sizeof(self->w), "%s/w", self->base);
285 + ASSERT_EQ(mkdir(self->h, 0755), 0);
286 + ASSERT_EQ(mkdir(self->plain, 0755), 0);
287 + ASSERT_EQ(mkdir(self->w, 0755), 0);
288 + snprintf(p, sizeof(p), "%s/plain/inner", self->base);
289 + ASSERT_EQ(mkdir(p, 0755), 0);
290 + ASSERT_EQ(get_handle(p, &self->uncovered), 0);
291 +
292 + /* the handle is for this filesystem */
293 + ASSERT_EQ(mount("tmpfs", self->h, "tmpfs", 0, NULL), 0);
294 + snprintf(p, sizeof(p), "%s/h/top", self->base);
295 + ASSERT_EQ(mkdir(p, 0755), 0);
296 + snprintf(p, sizeof(p), "%s/h/top/secret", self->base);
297 + ASSERT_EQ(mkdir(p, 0755), 0);
298 + snprintf(p, sizeof(p), "%s/h/top/secret/inner", self->base);
299 + ASSERT_EQ(mkdir(p, 0755), 0);
300 + ASSERT_EQ(get_handle(p, &self->inner), 0);
301 + snprintf(e, sizeof(e), "%s/h/empty", self->base);
302 + ASSERT_EQ(mkdir(e, 0755), 0);
303 +
304 + /* cover it, and some more so the umount takes longer */
305 + snprintf(p, sizeof(p), "%s/h/top/secret", self->base);
306 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, NULL), 0);
307 + for (i = 0; i < EXTRA_MOUNTS; i++) {
308 + snprintf(p, sizeof(p), "%s/h/c%d", self->base, i);
309 + ASSERT_EQ(mkdir(p, 0755), 0);
310 + ASSERT_EQ(mount(e, p, NULL, MS_BIND, NULL), 0);
311 + }
312 + }
313 +
314 + FIXTURE_TEARDOWN(locked_handle)
315 + {
316 + umount2(self->base, MNT_DETACH);
317 + rmdir(self->base);
318 + }
319 +
320 + static int wait_child(pid_t pid)
321 + {
322 + int status;
323 +
324 + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
325 + return -1;
326 + return WEXITSTATUS(status);
327 + }
328 +
329 + TEST_F(locked_handle, lazy_umount)
330 + {
331 + pid_t pid;
332 + int ret;
333 +
334 + pid = fork();
335 + ASSERT_GE(pid, 0);
336 + if (pid == 0)
337 + _exit(race_child(self->h, self->w, &self->inner, false));
338 + ret = wait_child(pid);
339 + TH_LOG("child exit code %d", ret);
340 + if (ret == CHILD_NOUSERNS)
341 + SKIP(return, "no user namespaces");
342 + EXPECT_EQ(ret, CHILD_OK);
343 + }
344 +
345 + TEST_F(locked_handle, dissolve)
346 + {
347 + pid_t pid;
348 + int ret;
349 +
350 + pid = fork();
351 + ASSERT_GE(pid, 0);
352 + if (pid == 0)
353 + _exit(race_child(self->h, self->w, &self->inner, true));
354 + ret = wait_child(pid);
355 + TH_LOG("child exit code %d", ret);
356 + if (ret == CHILD_NOUSERNS)
357 + SKIP(return, "no user namespaces");
358 + EXPECT_EQ(ret, CHILD_OK);
359 + }
360 +
361 + TEST_F(locked_handle, allowed_use)
362 + {
363 + pid_t pid;
364 + int ret;
365 +
366 + pid = fork();
367 + ASSERT_GE(pid, 0);
368 + if (pid == 0)
369 + _exit(allowed_child(self->plain, self->w, &self->uncovered));
370 + ret = wait_child(pid);
371 + TH_LOG("child exit code %d", ret);
372 + if (ret == CHILD_NOUSERNS)
373 + SKIP(return, "no user namespaces");
374 + EXPECT_EQ(ret, CHILD_OK);
375 + }
376 +
377 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/loop_cycle_test.c mode 100644
@@ -0,0 +1,1542 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A mount that another namespace's rmdir detached, or that went down with
4 + * the detached tree it was in when the tree's last fd was closed, keeps
5 + * its submounts connected, and a connected submount is put by its
6 + * parent's final mntput(). A submount whose filesystem keeps a file open
7 + * on the parent then holds the parent's count above zero for good:
8 + * nothing in userspace refers to either mount any more and nothing can
9 + * release them. A loop device is the simplest such filesystem, its
10 + * backing file sits on the parent.
11 + */
12 + #define _GNU_SOURCE
13 + #include <dirent.h>
14 + #include <errno.h>
15 + #include <fcntl.h>
16 + #include <sched.h>
17 + #include <stdio.h>
18 + #include <stdlib.h>
19 + #include <string.h>
20 + #include <sys/ioctl.h>
21 + #include <sys/mount.h>
22 + #include <sys/stat.h>
23 + #include <stdbool.h>
24 + #include <sys/wait.h>
25 + #include <unistd.h>
26 + #include <linux/fuse.h>
27 + #include <linux/keyctl.h>
28 + #include <linux/major.h>
29 + #include <linux/raid/md_u.h>
30 + #include <linux/raid/md_p.h>
31 + #include <linux/loop.h>
32 + #include <linux/magic.h>
33 + #include <sys/syscall.h>
34 + #include <sys/sysmacros.h>
35 + #include <sys/uio.h>
36 +
37 + #include "../wrappers.h"
38 + #include "../../kselftest_harness.h"
39 +
40 + #define IMAGE_SIZE (1440 * 1024)
41 + #define SECTOR 512
42 +
43 + /*
44 + * The tmpfs of the fixture. A directory of its own from mkdtemp(), so that
45 + * the test needs no writable root directory and two instances don't take
46 + * each other's mounts down.
47 + */
48 + static char base[64];
49 +
50 + /* The configfs directory of the gadget, named after the test process. */
51 + static char gadget[96];
52 +
53 + /* A path below the base directory. Eight of them can be in use at a time. */
54 + static const char *at(const char *rel)
55 + {
56 + static char buf[8][PATH_MAX];
57 + static unsigned int next;
58 + char *p = buf[next++ % 8];
59 +
60 + snprintf(p, PATH_MAX, "%s/%s", base, rel);
61 + return p;
62 + }
63 +
64 + /* A path below the gadget's configfs directory. */
65 + static const char *gat(const char *rel)
66 + {
67 + static char buf[4][PATH_MAX];
68 + static unsigned int next;
69 + char *p = buf[next++ % 4];
70 +
71 + snprintf(p, PATH_MAX, "%s%s", gadget, rel);
72 + return p;
73 + }
74 +
75 + /* The loop devices this process has bound, to release them on every path. */
76 + #define MAX_LOOPS 4
77 + static int bound[MAX_LOOPS];
78 + static int nr_bound;
79 +
80 + /* What a child tells its parent: the loop devices it has bound, -1 for none. */
81 + struct report {
82 + int n[2];
83 + };
84 +
85 + /* A blank FAT12 floppy image: boot sector, two FATs, an empty root directory. */
86 + static int write_fat12(int fd)
87 + {
88 + struct stat st;
89 + unsigned char sector[SECTOR] = {
90 + 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
91 + [11] = 0x00, 0x02, /* bytes per sector: 512 */
92 + [13] = 1, /* sectors per cluster */
93 + [14] = 1, 0, /* reserved sectors */
94 + [16] = 2, /* FATs */
95 + [17] = 0xe0, 0x00, /* root directory entries: 224 */
96 + [19] = 0x40, 0x0b, /* total sectors: 2880 */
97 + [21] = 0xf0, /* media descriptor */
98 + [22] = 9, 0, /* sectors per FAT */
99 + [24] = 18, 0, /* sectors per track */
100 + [26] = 2, 0, /* heads */
101 + [38] = 0x29, /* extended boot signature */
102 + [39] = 0x12, 0x34, 0x56, 0x78,
103 + [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
104 + [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
105 + [510] = 0x55, 0xaa,
106 + };
107 + unsigned char fat[SECTOR] = { 0xf0, 0xff, 0xff };
108 +
109 + if (pwrite(fd, sector, SECTOR, 0) != SECTOR)
110 + return -1;
111 + /* the first FAT and the second one, one sector each is enough */
112 + if (pwrite(fd, fat, SECTOR, 1 * SECTOR) != SECTOR ||
113 + pwrite(fd, fat, SECTOR, 10 * SECTOR) != SECTOR)
114 + return -1;
115 + if (fstat(fd, &st) || S_ISBLK(st.st_mode))
116 + return 0;
117 + return ftruncate(fd, IMAGE_SIZE);
118 + }
119 +
120 + /*
121 + * A blank FAT12 image with 4 KiB sectors and @sectors of them, for a device
122 + * with 4 KiB logical blocks (zram) or for a bigger image than a floppy.
123 + */
124 + static int write_fat12_4k(int fd, unsigned int sectors)
125 + {
126 + unsigned int fat_sectors = (sectors * 3 / 2 + 4095) / 4096;
127 + unsigned char sector[4096] = {
128 + 0xeb, 0x3c, 0x90, 'M', 'S', 'W', 'I', 'N', '4', '.', '1',
129 + [11] = 0x00, 0x10, /* bytes per sector: 4096 */
130 + [13] = 1, /* sectors per cluster */
131 + [14] = 1, 0, /* reserved sectors */
132 + [16] = 2, /* FATs */
133 + [17] = 128, 0, /* root directory entries: one sector */
134 + [19] = sectors & 0xff, sectors >> 8,
135 + [21] = 0xf8, /* media descriptor */
136 + [22] = fat_sectors, 0,
137 + [24] = 63, 0, /* sectors per track */
138 + [26] = 255, 0, /* heads */
139 + [38] = 0x29, /* extended boot signature */
140 + [39] = 0x12, 0x34, 0x56, 0x78,
141 + [43] = 'N', 'O', ' ', 'N', 'A', 'M', 'E', ' ', ' ', ' ', ' ',
142 + [54] = 'F', 'A', 'T', '1', '2', ' ', ' ', ' ',
143 + [510] = 0x55, 0xaa,
144 + };
145 + unsigned char fat[4096] = { 0xf8, 0xff, 0xff };
146 + struct stat st;
147 +
148 + if (pwrite(fd, sector, sizeof(sector), 0) != sizeof(sector))
149 + return -1;
150 + if (pwrite(fd, fat, sizeof(fat), 1 * 4096) != sizeof(fat) ||
151 + pwrite(fd, fat, sizeof(fat), (1 + fat_sectors) * 4096) != sizeof(fat))
152 + return -1;
153 + if (fstat(fd, &st) || S_ISBLK(st.st_mode))
154 + return 0;
155 + return ftruncate(fd, (off_t)sectors * 4096);
156 + }
157 +
158 + #define MINIX_BLOCK 1024
159 + #define MINIX_BLOCKS 4096 /* a 4 MiB image */
160 + #define MINIX_INODES 512
161 + #define MINIX_ITABLE (MINIX_INODES * 32 / MINIX_BLOCK)
162 + #define MINIX_FIRSTDATA (2 + 1 + 1 + MINIX_ITABLE) /* boot, super, imap, zmap, inodes */
163 +
164 + /*
165 + * A blank minix v1 image, for the holders that need a FIFO or a device
166 + * node on the dying mount, which vfat can't hold. Superblock in block 1,
167 + * one block each for the inode and zone bitmaps, the inode table, and
168 + * the root directory in the first data zone.
169 + */
170 + static int write_minix(int fd)
171 + {
172 + struct {
173 + __u16 s_ninodes, s_nzones, s_imap_blocks, s_zmap_blocks;
174 + __u16 s_firstdatazone, s_log_zone_size;
175 + __u32 s_max_size;
176 + __u16 s_magic, s_state;
177 + } sb = {
178 + .s_ninodes = MINIX_INODES,
179 + .s_nzones = MINIX_BLOCKS,
180 + .s_imap_blocks = 1,
181 + .s_zmap_blocks = 1,
182 + .s_firstdatazone = MINIX_FIRSTDATA,
183 + .s_max_size = (7 + 512 + 512 * 512) * MINIX_BLOCK,
184 + .s_magic = MINIX_SUPER_MAGIC,
185 + .s_state = 1, /* MINIX_VALID_FS */
186 + };
187 + struct {
188 + __u16 i_mode, i_uid;
189 + __u32 i_size, i_time;
190 + __u8 i_gid, i_nlinks;
191 + __u16 i_zone[9];
192 + } root = {
193 + .i_mode = S_IFDIR | 0755,
194 + .i_size = 2 * 16,
195 + .i_nlinks = 2,
196 + .i_zone = { MINIX_FIRSTDATA },
197 + };
198 + unsigned char imap[MINIX_BLOCK], zmap[MINIX_BLOCK], dir[MINIX_BLOCK] = {};
199 + int i;
200 +
201 + /* bit 0 is reserved in both maps, the root inode and its zone are in use */
202 + memset(imap, 0xff, sizeof(imap));
203 + for (i = 2; i <= MINIX_INODES; i++)
204 + imap[i / 8] &= ~(1 << (i % 8));
205 + memset(zmap, 0xff, sizeof(zmap));
206 + for (i = 2; i <= MINIX_BLOCKS - MINIX_FIRSTDATA; i++)
207 + zmap[i / 8] &= ~(1 << (i % 8));
208 + dir[0] = 1;
209 + dir[2] = '.';
210 + dir[16] = 1;
211 + dir[18] = '.';
212 + dir[19] = '.';
213 +
214 + if (pwrite(fd, &sb, sizeof(sb), 1 * MINIX_BLOCK) != sizeof(sb) ||
215 + pwrite(fd, imap, sizeof(imap), 2 * MINIX_BLOCK) != sizeof(imap) ||
216 + pwrite(fd, zmap, sizeof(zmap), 3 * MINIX_BLOCK) != sizeof(zmap) ||
217 + pwrite(fd, &root, sizeof(root), 4 * MINIX_BLOCK) != sizeof(root) ||
218 + pwrite(fd, dir, sizeof(dir), MINIX_FIRSTDATA * MINIX_BLOCK) != sizeof(dir))
219 + return -1;
220 + return ftruncate(fd, (off_t)MINIX_BLOCKS * MINIX_BLOCK);
221 + }
222 +
223 + static int read_sysfs(const char *path, char *buf, size_t size)
224 + {
225 + ssize_t n;
226 + int fd;
227 +
228 + fd = open(path, O_RDONLY);
229 + if (fd < 0)
230 + return -1;
231 + n = read(fd, buf, size - 1);
232 + close(fd);
233 + if (n < 0)
234 + return -1;
235 + buf[n] = '\0';
236 + return 0;
237 + }
238 +
239 + /* Is @dev the mount source of this line of mountinfo? loop1 is not loop10. */
240 + static bool line_has_source(const char *line, const char *dev)
241 + {
242 + const char *sep, *src, *end;
243 +
244 + sep = strstr(line, " - ");
245 + if (!sep)
246 + return false;
247 + src = strchr(sep + 3, ' '); /* skip the filesystem type */
248 + if (!src)
249 + return false;
250 + src++;
251 + end = strchr(src, ' ');
252 + if (!end)
253 + return false;
254 + return (size_t)(end - src) == strlen(dev) && !strncmp(src, dev, end - src);
255 + }
256 +
257 + /*
258 + * Does a mount namespace of a process that /proc shows have a mount of @dev?
259 + * The mounts under test are in no namespace at this point on any kernel, so
260 + * this only checks that the test got as far as it thinks.
261 + */
262 + static bool mounted_anywhere(const char *dev)
263 + {
264 + char path[PATH_MAX], line[4096];
265 + struct dirent *de;
266 + bool found = false;
267 + DIR *proc;
268 + FILE *f;
269 +
270 + proc = opendir("/proc");
271 + if (!proc)
272 + return false;
273 + while (!found && (de = readdir(proc))) {
274 + if (de->d_name[0] < '0' || de->d_name[0] > '9')
275 + continue;
276 + snprintf(path, sizeof(path), "/proc/%s/mountinfo", de->d_name);
277 + f = fopen(path, "re");
278 + if (!f)
279 + continue;
280 + while (fgets(line, sizeof(line), f)) {
281 + if (line_has_source(line, dev)) {
282 + found = true;
283 + break;
284 + }
285 + }
286 + fclose(f);
287 + }
288 + closedir(proc);
289 + return found;
290 + }
291 +
292 + /* Wait up to @ms milliseconds for the loop device to give up its backing file. */
293 + static bool loop_released(const char *sysfs, int ms)
294 + {
295 + char buf[PATH_MAX];
296 +
297 + for (; ms > 0; ms -= 100) {
298 + if (read_sysfs(sysfs, buf, sizeof(buf)) < 0)
299 + return errno == ENOENT;
300 + usleep(100000);
301 + }
302 + return read_sysfs(sysfs, buf, sizeof(buf)) < 0 && errno == ENOENT;
303 + }
304 +
305 + /* Tell the loop device to give its file up, now or when its last user is gone. */
306 + static void loop_clear(int n)
307 + {
308 + char dev[32];
309 + int lfd;
310 +
311 + if (n < 0)
312 + return;
313 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
314 + lfd = open(dev, O_RDWR);
315 + if (lfd < 0)
316 + return;
317 + ioctl(lfd, LOOP_CLR_FD);
318 + close(lfd);
319 + }
320 +
321 + FIXTURE(loop_cycle) {
322 + char dev[32]; /* the loop device the child set up */
323 + char sysfs[64]; /* its backing_file attribute */
324 + int loops[MAX_LOOPS]; /* every loop device the case has bound */
325 + int nr_loops;
326 + bool gadget; /* the gadget's configfs directory exists */
327 + };
328 +
329 + static void remember_loop(FIXTURE_DATA(loop_cycle) *self, int n)
330 + {
331 + if (n >= 0 && self->nr_loops < MAX_LOOPS)
332 + self->loops[self->nr_loops++] = n;
333 + }
334 +
335 + FIXTURE_SETUP(loop_cycle)
336 + {
337 + if (geteuid() != 0)
338 + SKIP(return, "test requires CAP_SYS_ADMIN");
339 + if (access("/dev/loop-control", R_OK | W_OK))
340 + SKIP(return, "test requires loop devices");
341 +
342 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
343 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
344 +
345 + snprintf(base, sizeof(base), "/tmp/loop_cycle.XXXXXX");
346 + ASSERT_NE(mkdtemp(base), NULL);
347 + /* a failed assertion in the setup does not run the teardown */
348 + ASSERT_EQ(mount("tmpfs", base, "tmpfs", 0, NULL), 0)
349 + rmdir(base);
350 + snprintf(gadget, sizeof(gadget),
351 + "/sys/kernel/config/usb_gadget/kselftest_cycle_%d", getpid());
352 + self->dev[0] = '\0';
353 + self->nr_loops = 0;
354 + self->gadget = false;
355 + }
356 +
357 + static int mount_configfs(void);
358 + static void gadget_remove(void);
359 +
360 + FIXTURE_TEARDOWN(loop_cycle)
361 + {
362 + if (self->gadget)
363 + gadget_remove();
364 + /* whatever a failed assertion has left bound */
365 + for (int i = 0; i < self->nr_loops; i++)
366 + loop_clear(self->loops[i]);
367 + umount2(base, MNT_DETACH);
368 + rmdir(base);
369 + }
370 +
371 + /* Child exit codes. */
372 + enum {
373 + CHILD_OK,
374 + CHILD_NS, /* could not set up the namespace or the tmpfs */
375 + CHILD_IMAGE, /* could not write the image */
376 + CHILD_LOOP, /* could not set up the loop device */
377 + CHILD_MOUNT, /* could not mount it (vfat and msdos both refused) */
378 + CHILD_PIPE, /* the parent went away */
379 + CHILD_HOLDER, /* could not set the holder up below the mount */
380 + CHILD_SKIP, /* the kernel lacks what the holder needs */
381 + CHILD_NOFS, /* the kernel lacks the filesystem of the image */
382 + };
383 +
384 + /* Bind the loop device that LOOP_CTL_GET_FREE names to @ifd; the device number. */
385 + static int loop_bind_free(int ifd)
386 + {
387 + int cfd, lfd, n;
388 + char dev[32];
389 +
390 + cfd = open("/dev/loop-control", O_RDWR);
391 + if (cfd < 0)
392 + return -1;
393 + n = ioctl(cfd, LOOP_CTL_GET_FREE);
394 + close(cfd);
395 + if (n < 0)
396 + return -1;
397 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
398 + lfd = open(dev, O_RDWR);
399 + if (lfd < 0)
400 + return -1;
401 + if (ioctl(lfd, LOOP_SET_FD, ifd))
402 + n = -1;
403 + close(lfd);
404 + return n;
405 + }
406 +
407 + /*
408 + * Bind a free loop device to the open image @ifd; the device number. The
409 + * device is free when LOOP_CTL_GET_FREE names it and may be somebody else's
410 + * a moment later, so try again when it is busy.
411 + */
412 + static int loop_bind(int ifd)
413 + {
414 + int n = -1;
415 +
416 + for (int i = 0; i < 64 && n < 0; i++) {
417 + n = loop_bind_free(ifd);
418 + if (n < 0 && errno != EBUSY)
419 + return -1;
420 + }
421 + if (n >= 0 && nr_bound < MAX_LOOPS)
422 + bound[nr_bound++] = n;
423 + return n;
424 + }
425 +
426 + /* Mount a FAT image, as vfat or as msdos; -1 with ENODEV if the kernel has neither. */
427 + static int mount_fat(const char *dev, const char *mp)
428 + {
429 + int err;
430 +
431 + if (!mount(dev, mp, "vfat", 0, NULL))
432 + return 0;
433 + err = errno;
434 + if (!mount(dev, mp, "msdos", 0, NULL))
435 + return 0;
436 + if (err != ENODEV)
437 + errno = err;
438 + return -1;
439 + }
440 +
441 + /*
442 + * A child that gives up has to take down what it has set up: nobody else
443 + * knows about it. Unmount, then tell the loop devices to let go. The mounts
444 + * are released after this process is gone and the devices follow them.
445 + */
446 + static int child_fails(int ret)
447 + {
448 + umount2(at("vol"), MNT_DETACH);
449 + umount2(at("vol2"), MNT_DETACH);
450 + umount2(at("p"), MNT_DETACH);
451 + umount2(at("img"), MNT_DETACH);
452 + for (int i = 0; i < nr_bound; i++)
453 + loop_clear(bound[i]);
454 + return ret;
455 + }
456 +
457 + /* Write an image to @img, bind a loop device to it and mount that at @mp; the device number. */
458 + static int loop_mount(const char *img, const char *mp)
459 + {
460 + char dev[32];
461 + int ifd, n;
462 +
463 + ifd = open(img, O_RDWR | O_CREAT | O_EXCL, 0600);
464 + if (ifd < 0 || write_fat12(ifd))
465 + return -CHILD_IMAGE;
466 + n = loop_bind(ifd);
467 + close(ifd); /* the loop device holds the file from now on */
468 + if (n < 0)
469 + return -CHILD_LOOP;
470 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
471 + if (mkdir(mp, 0755))
472 + return -CHILD_MOUNT;
473 + if (mount_fat(dev, mp))
474 + return errno == ENODEV ? -CHILD_NOFS : -CHILD_MOUNT;
475 + return n;
476 + }
477 +
478 + /*
479 + * Two tmpfs mounts, each carrying the image of the loop mount below the
480 + * other: the loop mount below vol has its image on vol2 and the other way
481 + * round.
482 + */
483 + static int crossed_child(int to_parent, int from_parent)
484 + {
485 + struct report r;
486 + char c;
487 +
488 + if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
489 + return CHILD_NS;
490 + if (mkdir(at("vol"), 0755) || mount("tmpfs", at("vol"), "tmpfs", 0, NULL) ||
491 + mkdir(at("vol2"), 0755) || mount("tmpfs", at("vol2"), "tmpfs", 0, NULL))
492 + return child_fails(CHILD_NS);
493 + r.n[0] = loop_mount(at("vol2/img"), at("vol/mnt"));
494 + if (r.n[0] < 0)
495 + return child_fails(-r.n[0]);
496 + r.n[1] = loop_mount(at("vol/img"), at("vol2/mnt"));
497 + if (r.n[1] < 0)
498 + return child_fails(-r.n[1]);
499 + if (write(to_parent, &r, sizeof(r)) != sizeof(r))
500 + return child_fails(CHILD_PIPE);
501 + if (read(from_parent, &c, 1) != 1)
502 + return child_fails(CHILD_PIPE);
503 + return CHILD_OK;
504 + }
505 +
506 + /*
507 + * In its own mount namespace the child mounts a tmpfs on vol,
508 + * puts a filesystem image on it, binds a loop device to the image and
509 + * mounts that loop device below. The loop device's backing file is a
510 + * reference on the mount the image is on, held by the loop device, held
511 + * by the mounted filesystem, held by the mount below.
512 + */
513 + static int loop_child(int to_parent, int from_parent)
514 + {
515 + struct report r = { { -1, -1 } };
516 + char c;
517 +
518 + if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
519 + return CHILD_NS;
520 + if (mkdir(at("vol"), 0755) || mount("tmpfs", at("vol"), "tmpfs", 0, NULL))
521 + return child_fails(CHILD_NS);
522 + r.n[0] = loop_mount(at("vol/img"), at("vol/mnt"));
523 + if (r.n[0] < 0)
524 + return child_fails(-r.n[0]);
525 +
526 + if (write(to_parent, &r, sizeof(r)) != sizeof(r))
527 + return child_fails(CHILD_PIPE);
528 + /* keep the namespace alive while the parent removes the directory */
529 + if (read(from_parent, &c, 1) != 1)
530 + return child_fails(CHILD_PIPE);
531 + return CHILD_OK;
532 + }
533 +
534 + /*
535 + * The child did not report. Skip if the kernel lacks something, fail with
536 + * what the child said otherwise. A child that a signal killed has failed.
537 + */
538 + #define CHILD_GAVE_UP(pid) do { \
539 + int __status; \
540 + \
541 + ASSERT_EQ(waitpid(pid, &__status, 0), pid); \
542 + if (WIFEXITED(__status) && WEXITSTATUS(__status) == CHILD_NOFS) \
543 + SKIP(return, "test requires the filesystem of the image (FAT or minix)"); \
544 + if (WIFEXITED(__status) && WEXITSTATUS(__status) == CHILD_SKIP) \
545 + SKIP(return, "the kernel lacks what this holder needs"); \
546 + ASSERT_TRUE(false) \
547 + TH_LOG("child failed to set up: %s %d", \
548 + WIFEXITED(__status) ? "exit status" : "signal", \
549 + WIFEXITED(__status) ? WEXITSTATUS(__status) : WTERMSIG(__status)); \
550 + } while (0)
551 +
552 + /* The child has to leave by itself and with nothing to complain about. */
553 + #define CHILD_LEFT(pid) do { \
554 + int __status; \
555 + \
556 + ASSERT_EQ(waitpid(pid, &__status, 0), pid); \
557 + ASSERT_TRUE(WIFEXITED(__status)); \
558 + ASSERT_EQ(WEXITSTATUS(__status), CHILD_OK); \
559 + } while (0)
560 +
561 + /*
562 + * An exclusive open of the device fails while a filesystem holds it, and
563 + * the only filesystem that ever did is the one mounted below the dead
564 + * mount. Give a release in flight a moment. Then the device must clear
565 + * right away rather than only be marked for autoclear.
566 + */
567 + static void assert_loop_released(struct __test_metadata *_metadata,
568 + FIXTURE_DATA(loop_cycle) *self)
569 + {
570 + int lfd;
571 +
572 + for (int i = 0; i < 20; i++) {
573 + lfd = open(self->dev, O_RDONLY | O_EXCL);
574 + if (lfd >= 0)
575 + break;
576 + usleep(100000);
577 + }
578 + EXPECT_GE(lfd, 0)
579 + TH_LOG("%s is still held by the loop mount below the dead mount: nothing refers to either mount and nothing can release them",
580 + self->dev);
581 + if (lfd >= 0)
582 + close(lfd);
583 +
584 + lfd = open(self->dev, O_RDWR);
585 + ASSERT_GE(lfd, 0);
586 + ASSERT_EQ(ioctl(lfd, LOOP_CLR_FD), 0);
587 + close(lfd);
588 + ASSERT_TRUE(loop_released(self->sysfs, 5000))
589 + TH_LOG("%s kept its backing file after LOOP_CLR_FD: the filesystem on it is still mounted somewhere nobody can reach",
590 + self->dev);
591 + /* somebody else may bind it from now on, so the teardown leaves it alone */
592 + for (int i = 0; i < self->nr_loops; i++) {
593 + char dev[32];
594 +
595 + snprintf(dev, sizeof(dev), "/dev/loop%d", self->loops[i]);
596 + if (!strcmp(dev, self->dev))
597 + self->loops[i] = -1;
598 + }
599 + }
600 +
601 + /*
602 + * rmdir of vol from here, where it is not a mountpoint, detaches
603 + * the child's tmpfs with the loop mount connected below it. Once the child
604 + * is gone nothing refers to either mount. The loop device must then be
605 + * free to give up its backing file, which only happens when the mounted
606 + * filesystem below the detached tmpfs has been released.
607 + */
608 + TEST_F(loop_cycle, detached_loop_mount_released)
609 + {
610 + int to_parent[2], to_child[2];
611 + struct report r = { { -1, -1 } };
612 + char buf[PATH_MAX];
613 + pid_t pid;
614 +
615 + ASSERT_EQ(pipe(to_parent), 0);
616 + ASSERT_EQ(pipe(to_child), 0);
617 +
618 + pid = fork();
619 + ASSERT_GE(pid, 0);
620 + if (pid == 0) {
621 + close(to_parent[0]);
622 + close(to_child[1]);
623 + _exit(loop_child(to_parent[1], to_child[0]));
624 + }
625 + close(to_parent[1]);
626 + close(to_child[0]);
627 +
628 + if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
629 + CHILD_GAVE_UP(pid);
630 + remember_loop(self, r.n[0]);
631 + snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", r.n[0]);
632 + snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", r.n[0]);
633 + ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
634 + ASSERT_NE(strstr(buf, "/vol/img"), NULL);
635 +
636 + /* not a mountpoint in this namespace, so the directory can go */
637 + ASSERT_EQ(rmdir(at("vol")), 0);
638 +
639 + /* the child leaves: its namespace and every reference it held are gone */
640 + ASSERT_EQ(write(to_child[1], "", 1), 1);
641 + CHILD_LEFT(pid);
642 + close(to_parent[0]);
643 + close(to_child[1]);
644 +
645 + /* nothing can reach the two mounts any more */
646 + ASSERT_EQ(access(at("vol"), F_OK), -1);
647 + ASSERT_FALSE(mounted_anywhere(self->dev));
648 +
649 + assert_loop_released(_metadata, self);
650 + }
651 +
652 + /*
653 + * The same two mounts in a detached tree: a clone of vol from
654 + * open_tree(), the image opened through the clone so that the loop device
655 + * holds the clone, and the loop mount moved below the clone. The last
656 + * close of the tree's fd dissolves the tree with the loop mount left
657 + * connected below the dead clone, and nothing refers to either afterwards.
658 + */
659 + TEST_F(loop_cycle, dissolved_tree_loop_mount_released)
660 + {
661 + int tfd, ifd, fsfd, mfd, n;
662 + char buf[PATH_MAX];
663 +
664 + fsfd = sys_fsopen("vfat", 0);
665 + if (fsfd < 0)
666 + fsfd = sys_fsopen("msdos", 0);
667 + if (fsfd < 0)
668 + SKIP(return, "test requires a FAT filesystem");
669 +
670 + ASSERT_EQ(mkdir(at("vol"), 0755), 0);
671 + ASSERT_EQ(mount("tmpfs", at("vol"), "tmpfs", 0, NULL), 0);
672 + tfd = sys_open_tree(AT_FDCWD, at("vol"), OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
673 + ASSERT_GE(tfd, 0);
674 +
675 + /* the image, opened through the clone: the loop device holds the clone */
676 + ifd = openat(tfd, "img", O_RDWR | O_CREAT | O_EXCL, 0600);
677 + ASSERT_GE(ifd, 0);
678 + ASSERT_EQ(write_fat12(ifd), 0);
679 + n = loop_bind(ifd);
680 + close(ifd);
681 + ASSERT_GE(n, 0);
682 + remember_loop(self, n);
683 + snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", n);
684 + snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", n);
685 +
686 + /* the loop mount, moved below the clone */
687 + ASSERT_EQ(mkdirat(tfd, "mnt", 0755), 0);
688 + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_SET_STRING, "source", self->dev, 0), 0);
689 + ASSERT_EQ(sys_fsconfig(fsfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0), 0);
690 + mfd = sys_fsmount(fsfd, 0, 0);
691 + ASSERT_GE(mfd, 0);
692 + close(fsfd);
693 + ASSERT_EQ(sys_move_mount(mfd, "", tfd, "mnt", MOVE_MOUNT_F_EMPTY_PATH), 0);
694 + close(mfd);
695 +
696 + ASSERT_EQ(read_sysfs(self->sysfs, buf, sizeof(buf)), 0);
697 + ASSERT_NE(strstr(buf, "img"), NULL);
698 +
699 + /* the last fd of the tree: both mounts die, the loop mount connected */
700 + close(tfd);
701 +
702 + /* nothing can reach the two mounts any more */
703 + ASSERT_FALSE(mounted_anywhere(self->dev));
704 +
705 + assert_loop_released(_metadata, self);
706 + }
707 +
708 + /*
709 + * The cycle in two steps: rmdir of vol leaves the loop mount below it
710 + * connected while its image's mount, vol2, is alive; then rmdir of vol2
711 + * takes that one with the loop mount whose image is on the dead vol. Each
712 + * dead mount now owns a loop mount whose filesystem pins the other.
713 + */
714 + TEST_F(loop_cycle, crossed_images_released)
715 + {
716 + int to_parent[2], to_child[2];
717 + struct report r = { { -1, -1 } };
718 + char sysfs[2][64], dev[2][32];
719 + pid_t pid;
720 +
721 + ASSERT_EQ(pipe(to_parent), 0);
722 + ASSERT_EQ(pipe(to_child), 0);
723 +
724 + pid = fork();
725 + ASSERT_GE(pid, 0);
726 + if (pid == 0) {
727 + close(to_parent[0]);
728 + close(to_child[1]);
729 + _exit(crossed_child(to_parent[1], to_child[0]));
730 + }
731 + close(to_parent[1]);
732 + close(to_child[0]);
733 +
734 + if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
735 + CHILD_GAVE_UP(pid);
736 + for (int i = 0; i < 2; i++) {
737 + remember_loop(self, r.n[i]);
738 + snprintf(dev[i], sizeof(dev[i]), "/dev/loop%d", r.n[i]);
739 + snprintf(sysfs[i], sizeof(sysfs[i]), "/sys/block/loop%d/loop/backing_file", r.n[i]);
740 + }
741 +
742 + /* step one: the mount with the first loop mount below it goes */
743 + ASSERT_EQ(rmdir(at("vol")), 0);
744 +
745 + /* step two: the other one, with the loop mount whose image is on the first */
746 + ASSERT_EQ(rmdir(at("vol2")), 0);
747 +
748 + /* the child leaves: its namespace and every reference it held are gone */
749 + ASSERT_EQ(write(to_child[1], "", 1), 1);
750 + CHILD_LEFT(pid);
751 + close(to_parent[0]);
752 + close(to_child[1]);
753 +
754 + /* nothing can reach the four mounts any more */
755 + for (int i = 0; i < 2; i++) {
756 + ASSERT_FALSE(mounted_anywhere(dev[i]));
757 + strcpy(self->dev, dev[i]);
758 + strcpy(self->sysfs, sysfs[i]);
759 + assert_loop_released(_metadata, self);
760 + }
761 + }
762 +
763 + /*
764 + * The holders. Each keeps a file or a path on a mount P for as long as
765 + * its own filesystem or device lives, and each has that filesystem or
766 + * device mounted at C below P. Once another namespace's rmdir has
767 + * detached P with C connected below it and the child is gone, P is owned
768 + * by nobody, C by P, and P is kept by whatever the holder still holds.
769 + *
770 + * P is a loop mount so that its death can be observed: the loop device
771 + * gives its backing file up when P's superblock goes. The image sits on
772 + * a tmpfs next to P, not above it, so the loop device's own reference is
773 + * not part of the picture.
774 + */
775 + enum holder {
776 + HOLDER_AUTOFS, /* a FIFO on P as the daemon's pipe */
777 + HOLDER_ZRAM, /* a device node on P as the writeback device */
778 + HOLDER_ECRYPTFS, /* a directory on P as the lower directory */
779 + HOLDER_BINFMT_MISC, /* an executable on P as an 'F' interpreter */
780 + HOLDER_FUSE, /* a file on P as a passthrough backing file */
781 + HOLDER_ZLOOP, /* a directory on P for the zone files */
782 + HOLDER_GADGET, /* a file on P as a mass storage LUN, over dummy_hcd */
783 + HOLDER_MD, /* a file on P as an array's bitmap file */
784 + };
785 +
786 + #define HOLDER_IMG at("img/p.img")
787 + #define HOLDER_MNT at("p")
788 + #define HOLDER_BELOW at("p/c")
789 +
790 + static int write_file(const char *path, const char *s)
791 + {
792 + int fd = open(path, O_WRONLY);
793 + ssize_t n;
794 +
795 + if (fd < 0)
796 + return -1;
797 + n = write(fd, s, strlen(s));
798 + close(fd);
799 + return n == (ssize_t)strlen(s) ? 0 : -1;
800 + }
801 +
802 + /* Bind a free loop device to @img; the device number. */
803 + static int loop_attach(const char *img)
804 + {
805 + int ifd, n;
806 +
807 + ifd = open(img, O_RDWR);
808 + if (ifd < 0)
809 + return -1;
810 + n = loop_bind(ifd);
811 + close(ifd);
812 + return n;
813 + }
814 +
815 + static int holder_autofs(void)
816 + {
817 + char opts[64];
818 + int pfd;
819 +
820 + if (mkfifo(at("p/pipe"), 0600))
821 + return CHILD_HOLDER;
822 + pfd = open(at("p/pipe"), O_RDWR);
823 + if (pfd < 0)
824 + return CHILD_HOLDER;
825 + snprintf(opts, sizeof(opts), "fd=%d,minproto=5,maxproto=5", pfd);
826 + if (mount("autofs", HOLDER_BELOW, "autofs", 0, opts))
827 + return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
828 + close(pfd); /* the mount keeps its own */
829 + return CHILD_OK;
830 + }
831 +
832 + /*
833 + * zram's writeback device has to be a block device node, and that node has
834 + * to be on P. Point it at a second loop device.
835 + */
836 + static void zram_reset(void);
837 +
838 + static int holder_zram(void)
839 + {
840 + char dev[32], buf[64];
841 + struct stat st;
842 + int fd, n;
843 +
844 + if (access("/sys/block/zram0/backing_dev", W_OK))
845 + return CHILD_SKIP;
846 + /* somebody else's device, leave it alone */
847 + if (read_sysfs("/sys/block/zram0/initstate", buf, sizeof(buf)) || buf[0] != '0')
848 + return CHILD_SKIP;
849 + fd = open(at("img/wb.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
850 + if (fd < 0 || ftruncate(fd, IMAGE_SIZE))
851 + return CHILD_HOLDER;
852 + close(fd);
853 + n = loop_attach(at("img/wb.img"));
854 + if (n < 0)
855 + return CHILD_HOLDER;
856 + /* the minor is not the number of the device when loop has partitions */
857 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
858 + if (stat(dev, &st) || mknod(at("p/wbdev"), S_IFBLK | 0600, st.st_rdev))
859 + return CHILD_HOLDER;
860 + if (write_file("/sys/block/zram0/backing_dev", at("p/wbdev")))
861 + return CHILD_HOLDER;
862 + snprintf(buf, sizeof(buf), "%d", 4 * 1024 * 1024);
863 + if (write_file("/sys/block/zram0/disksize", buf))
864 + goto undo;
865 + fd = open("/dev/zram0", O_RDWR);
866 + if (fd < 0)
867 + goto undo;
868 + n = write_fat12_4k(fd, 1024); /* zram has 4 KiB blocks */
869 + close(fd); /* the reset in undo is refused while the device is open */
870 + if (n)
871 + goto undo;
872 + if (mount_fat("/dev/zram0", HOLDER_BELOW)) {
873 + n = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
874 + zram_reset();
875 + return n;
876 + }
877 + return CHILD_OK;
878 + undo:
879 + zram_reset();
880 + return CHILD_HOLDER;
881 + }
882 +
883 + /* Is @alg in /proc/crypto? A module is listed once a request has loaded it. */
884 + static bool crypto_has(const char *alg)
885 + {
886 + char line[256], name[64];
887 + bool found = false;
888 + FILE *f;
889 +
890 + f = fopen("/proc/crypto", "r");
891 + if (!f)
892 + return true; /* no way to tell, assume it is */
893 + while (!found && fgets(line, sizeof(line), f))
894 + found = sscanf(line, "name : %63s", name) == 1 && !strcmp(name, alg);
895 + fclose(f);
896 + return found;
897 + }
898 +
899 + /* The kernel's auth token layout, which userspace has to match byte for byte. */
900 + struct ecryptfs_auth_tok {
901 + __u16 version;
902 + __u16 token_type;
903 + __u32 flags;
904 + struct {
905 + __u32 flags, encrypted_key_size, decrypted_key_size;
906 + __u8 encrypted_key[512], decrypted_key[64];
907 + } session_key;
908 + __u8 reserved[32];
909 + struct {
910 + __u32 password_bytes;
911 + __s32 hash_algo;
912 + __u32 hash_iterations, session_key_encryption_key_bytes, flags;
913 + __u8 session_key_encryption_key[64];
914 + __u8 signature[17];
915 + __u8 salt[8];
916 + } password;
917 + } __attribute__((packed));
918 +
919 + #define ECRYPTFS_SIG "0123456789abcdef"
920 +
921 + static int holder_ecryptfs(void)
922 + {
923 + struct ecryptfs_auth_tok tok = {
924 + .version = 0x0004,
925 + .token_type = 0, /* ECRYPTFS_PASSWORD */
926 + .password.session_key_encryption_key_bytes = 16,
927 + .password.flags = 0x02, /* ECRYPTFS_SESSION_KEY_ENCRYPTION_KEY_SET */
928 + .password.signature = ECRYPTFS_SIG,
929 + };
930 +
931 + /* a session keyring of this child's own, so that the key goes with it */
932 + if (syscall(__NR_keyctl, KEYCTL_JOIN_SESSION_KEYRING, NULL) < 0)
933 + return errno == ENOSYS ? CHILD_SKIP : CHILD_HOLDER;
934 + if (syscall(__NR_add_key, "user", ECRYPTFS_SIG, &tok, sizeof(tok),
935 + KEY_SPEC_SESSION_KEYRING) < 0)
936 + return CHILD_HOLDER;
937 + if (mkdir(at("p/lower"), 0755))
938 + return CHILD_HOLDER;
939 + if (mount(at("p/lower"), HOLDER_BELOW, "ecryptfs", 0,
940 + "ecryptfs_sig=" ECRYPTFS_SIG ",ecryptfs_cipher=aes,ecryptfs_key_bytes=16")) {
941 + /* EINVAL without the cipher; a module is loaded by the attempt */
942 + if (errno == ENODEV || (errno == EINVAL && !crypto_has("aes")))
943 + return CHILD_SKIP;
944 + return CHILD_HOLDER;
945 + }
946 + return CHILD_OK;
947 + }
948 +
949 + /*
950 + * binfmt_misc instances are per user namespace, so the mount below P is
951 + * made from a new one, which gets a copy of P.
952 + */
953 + static int holder_binfmt_misc(void)
954 + {
955 + static const char interp[] = "#!/bin/true\n";
956 + char reg[PATH_MAX];
957 + int out;
958 +
959 + /* 'F' opens the interpreter at registration, nothing runs it here */
960 + out = open(at("p/interp"), O_WRONLY | O_CREAT | O_EXCL, 0755);
961 + if (out < 0 || write(out, interp, sizeof(interp) - 1) != sizeof(interp) - 1)
962 + return CHILD_HOLDER;
963 + close(out);
964 +
965 + /* ENOSPC: user.max_user_namespaces is 0, EPERM: an LSM says no */
966 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS)) {
967 + if (errno == EINVAL || errno == ENOSPC || errno == EPERM)
968 + return CHILD_SKIP;
969 + return CHILD_HOLDER;
970 + }
971 + if (write_file("/proc/self/setgroups", "deny") ||
972 + write_file("/proc/self/uid_map", "0 0 1") ||
973 + write_file("/proc/self/gid_map", "0 0 1"))
974 + return CHILD_HOLDER;
975 + if (mount("binfmt_misc", HOLDER_BELOW, "binfmt_misc", 0, NULL))
976 + return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
977 + snprintf(reg, sizeof(reg), ":cycle:E::cyc::%s:F", at("p/interp"));
978 + if (write_file(at("p/c/register"), reg))
979 + return CHILD_HOLDER;
980 + return CHILD_OK;
981 + }
982 +
983 + /*
984 + * A fuse server that only ever answers FUSE_INIT, with passthrough on, and
985 + * then registers a file on P as a backing file. The registration alone
986 + * makes the fuse superblock hold the file.
987 + */
988 + static int holder_fuse(void)
989 + {
990 + struct fuse_backing_map map = {};
991 + struct fuse_in_header *ih;
992 + struct fuse_init_out init = {
993 + .major = FUSE_KERNEL_VERSION,
994 + .minor = FUSE_KERNEL_MINOR_VERSION,
995 + .flags = FUSE_INIT_EXT,
996 + .flags2 = FUSE_PASSTHROUGH >> 32,
997 + .max_write = 4096,
998 + .max_stack_depth = 1,
999 + };
1000 + struct fuse_out_header oh = { .len = sizeof(oh) + sizeof(init) };
1001 + struct iovec iov[2] = { { &oh, sizeof(oh) }, { &init, sizeof(init) } };
1002 + char opts[64], buf[8192];
1003 + int ffd, bfd;
1004 + ssize_t n;
1005 +
1006 + bfd = open(at("p/backing"), O_RDWR | O_CREAT | O_EXCL, 0600);
1007 + if (bfd < 0)
1008 + return CHILD_HOLDER;
1009 + ffd = open("/dev/fuse", O_RDWR);
1010 + if (ffd < 0)
1011 + return CHILD_SKIP;
1012 + snprintf(opts, sizeof(opts), "fd=%d,rootmode=40000,user_id=0,group_id=0", ffd);
1013 + if (mount("fuse", HOLDER_BELOW, "fuse", 0, opts))
1014 + return errno == ENODEV ? CHILD_SKIP : CHILD_HOLDER;
1015 +
1016 + n = read(ffd, buf, sizeof(buf));
1017 + ih = (void *)buf;
1018 + if (n < (ssize_t)sizeof(*ih) || ih->opcode != FUSE_INIT)
1019 + return CHILD_HOLDER;
1020 + oh.unique = ih->unique;
1021 + if (writev(ffd, iov, 2) != (ssize_t)oh.len)
1022 + return CHILD_HOLDER;
1023 +
1024 + map.fd = bfd;
1025 + if (ioctl(ffd, FUSE_DEV_IOC_BACKING_OPEN, &map) < 0) {
1026 + /* EOPNOTSUPP: no FUSE_PASSTHROUGH, ENOTTY: no such ioctl */
1027 + if (errno == EPERM || errno == EOPNOTSUPP || errno == ENOTTY)
1028 + return CHILD_SKIP;
1029 + return CHILD_HOLDER;
1030 + }
1031 + close(bfd); /* the connection keeps its own */
1032 + return CHILD_OK; /* ffd stays open until the child exits */
1033 + }
1034 +
1035 + /* Wait for a device node the kernel is about to create. */
1036 + static int open_when_there(const char *dev, int flags, int ms)
1037 + {
1038 + int fd;
1039 +
1040 + for (; ms > 0; ms -= 100) {
1041 + fd = open(dev, flags);
1042 + if (fd >= 0)
1043 + return fd;
1044 + usleep(100000);
1045 + }
1046 + return -1;
1047 + }
1048 +
1049 + /*
1050 + * zloop keeps every zone file open. One conventional zone is enough for a
1051 + * FAT image, the sequential one stays empty.
1052 + */
1053 + static int holder_zloop(void)
1054 + {
1055 + char cmd[PATH_MAX];
1056 + int fd, ret = CHILD_HOLDER;
1057 +
1058 + if (access("/dev/zloop-control", W_OK))
1059 + return CHILD_SKIP;
1060 + /* somebody else's device, leave it alone */
1061 + if (!access("/sys/block/zloop0", F_OK))
1062 + return CHILD_SKIP;
1063 + if (mkdir(at("p/zl"), 0755) || mkdir(at("p/zl/0"), 0755))
1064 + return CHILD_HOLDER;
1065 + snprintf(cmd, sizeof(cmd),
1066 + "add id=0,capacity_mb=8,zone_size_mb=4,conv_zones=1,base_dir=%s",
1067 + at("p/zl"));
1068 + if (write_file("/dev/zloop-control", cmd))
1069 + return CHILD_HOLDER;
1070 + fd = open_when_there("/dev/zloop0", O_RDWR, 5000);
1071 + if (fd < 0 || write_fat12_4k(fd, 1024)) /* 4 KiB blocks, like P */
1072 + goto undo;
1073 + close(fd);
1074 + fd = -1;
1075 + if (mount_fat("/dev/zloop0", HOLDER_BELOW)) {
1076 + ret = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1077 + goto undo;
1078 + }
1079 + return CHILD_OK;
1080 + undo:
1081 + if (fd >= 0)
1082 + close(fd);
1083 + write_file("/dev/zloop-control", "remove id=0");
1084 + return ret;
1085 + }
1086 +
1087 + static int mount_configfs(void)
1088 + {
1089 + if (access("/sys/kernel/config", F_OK))
1090 + return -1;
1091 + if (mount("configfs", "/sys/kernel/config", "configfs", 0, NULL) && errno != EBUSY)
1092 + return -1;
1093 + return 0;
1094 + }
1095 +
1096 + /* Take the gadget out of configfs again, in the reverse order of its creation. */
1097 + static void gadget_remove(void)
1098 + {
1099 + if (mount_configfs())
1100 + return;
1101 + write_file(gat("/functions/mass_storage.0/lun.0/file"), "\n");
1102 + write_file(gat("/UDC"), "\n");
1103 + unlink(gat("/configs/c.1/mass_storage.0"));
1104 + rmdir(gat("/configs/c.1/strings/0x409"));
1105 + rmdir(gat("/configs/c.1"));
1106 + rmdir(gat("/functions/mass_storage.0"));
1107 + rmdir(gat("/strings/0x409"));
1108 + rmdir(gat(""));
1109 + }
1110 +
1111 + /* The disk usb-storage created for the gadget, by the LUN's inquiry string. */
1112 + static int find_gadget_disk(char *dev, size_t len, int ms)
1113 + {
1114 + char path[PATH_MAX], model[64];
1115 + struct dirent *de;
1116 + DIR *d;
1117 +
1118 + for (; ms > 0; ms -= 100, usleep(100000)) {
1119 + d = opendir("/sys/block");
1120 + if (!d)
1121 + return -1;
1122 + while ((de = readdir(d))) {
1123 + if (strncmp(de->d_name, "sd", 2))
1124 + continue;
1125 + snprintf(path, sizeof(path), "/sys/block/%s/device/model", de->d_name);
1126 + if (read_sysfs(path, model, sizeof(model)) ||
1127 + strncmp(model, "File-Stor Gadget", 16))
1128 + continue;
1129 + snprintf(dev, len, "/dev/%s", de->d_name);
1130 + closedir(d);
1131 + return 0;
1132 + }
1133 + closedir(d);
1134 + }
1135 + return -1;
1136 + }
1137 +
1138 + /*
1139 + * A mass storage gadget bound to the dummy UDC, so that this kernel is
1140 + * also the USB host that sees the LUN as a SCSI disk. sd locks the
1141 + * medium on open, which is what keeps the LUN's file from being ejected.
1142 + */
1143 + #define GADGET_STEP(x) do { \
1144 + if (x) { \
1145 + fprintf(stderr, "gadget: %s failed: %s\n", #x, strerror(errno)); \
1146 + gadget_remove(); \
1147 + return CHILD_HOLDER; \
1148 + } \
1149 + } while (0)
1150 +
1151 + static int holder_gadget(void)
1152 + {
1153 + char dev[PATH_MAX];
1154 + int fd;
1155 +
1156 + if (mount_configfs())
1157 + return CHILD_SKIP;
1158 + if (access("/sys/kernel/config/usb_gadget", F_OK) ||
1159 + access("/sys/class/udc/dummy_udc.0", F_OK))
1160 + return CHILD_SKIP;
1161 +
1162 + fd = open(at("p/lun.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
1163 + if (fd < 0 || write_fat12(fd))
1164 + return CHILD_HOLDER;
1165 + close(fd);
1166 +
1167 + GADGET_STEP(mkdir(gat(""), 0755));
1168 + GADGET_STEP(write_file(gat("/idVendor"), "0x1d6b"));
1169 + GADGET_STEP(write_file(gat("/idProduct"), "0x0104"));
1170 + GADGET_STEP(mkdir(gat("/strings/0x409"), 0755));
1171 + GADGET_STEP(write_file(gat("/strings/0x409/serialnumber"), "1"));
1172 + GADGET_STEP(write_file(gat("/strings/0x409/manufacturer"), "kselftest"));
1173 + GADGET_STEP(write_file(gat("/strings/0x409/product"), "cycle"));
1174 + GADGET_STEP(mkdir(gat("/configs/c.1"), 0755));
1175 + GADGET_STEP(mkdir(gat("/configs/c.1/strings/0x409"), 0755));
1176 + GADGET_STEP(write_file(gat("/configs/c.1/strings/0x409/configuration"), "c"));
1177 + GADGET_STEP(mkdir(gat("/functions/mass_storage.0"), 0755));
1178 + GADGET_STEP(write_file(gat("/functions/mass_storage.0/lun.0/removable"), "1"));
1179 + GADGET_STEP(write_file(gat("/functions/mass_storage.0/lun.0/file"), at("p/lun.img")));
1180 + GADGET_STEP(symlink(gat("/functions/mass_storage.0"), gat("/configs/c.1/mass_storage.0")));
1181 + /* EBUSY: the controller is somebody else's, leave it alone */
1182 + if (write_file(gat("/UDC"), "dummy_udc.0")) {
1183 + fd = errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
1184 + gadget_remove();
1185 + return fd;
1186 + }
1187 +
1188 + /* usb-storage waits a second before it scans the device */
1189 + if (find_gadget_disk(dev, sizeof(dev), 15000)) {
1190 + /* without usb-storage and sd the LUN never shows up as a disk */
1191 + fd = (access("/sys/bus/usb/drivers/usb-storage", F_OK) ||
1192 + access("/sys/bus/scsi/drivers/sd", F_OK)) ? CHILD_SKIP : CHILD_HOLDER;
1193 + gadget_remove();
1194 + return fd;
1195 + }
1196 + fd = open_when_there(dev, O_RDONLY, 5000);
1197 + GADGET_STEP(fd < 0);
1198 + close(fd);
1199 + if (mount_fat(dev, HOLDER_BELOW)) {
1200 + fd = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1201 + gadget_remove();
1202 + return fd;
1203 + }
1204 + return CHILD_OK;
1205 + }
1206 +
1207 + #define BITMAP_MAGIC 0x6d746962
1208 +
1209 + /*
1210 + * A RAID1 of one loop device, not persistent, with its bitmap in a file
1211 + * on P. The bitmap file needs a superblock the kernel accepts; sync_size,
1212 + * uuid and events are not looked at for a non-persistent array.
1213 + */
1214 + static int holder_md(void)
1215 + {
1216 + struct {
1217 + __u32 magic, version;
1218 + __u8 uuid[16];
1219 + __u64 events, events_cleared, sync_size;
1220 + __u32 state, chunksize, daemon_sleep, write_behind;
1221 + } bsb = {
1222 + .magic = BITMAP_MAGIC,
1223 + .version = 4,
1224 + .chunksize = 64 * 1024,
1225 + .daemon_sleep = 5,
1226 + };
1227 + mdu_array_info_t info = {
1228 + .level = 1,
1229 + .raid_disks = 1,
1230 + .size = 8 * 1024, /* KiB */
1231 + .not_persistent = 1,
1232 + };
1233 + mdu_disk_info_t disk = {
1234 + .major = 7,
1235 + .state = (1 << MD_DISK_ACTIVE) | (1 << MD_DISK_SYNC),
1236 + };
1237 + int fd, mdfd, bfd, n, ret = CHILD_HOLDER;
1238 + char dev[32], buf[4096];
1239 + struct stat st;
1240 +
1241 + fd = open(at("img/md.img"), O_RDWR | O_CREAT | O_EXCL, 0600);
1242 + if (fd < 0 || ftruncate(fd, 8 * 1024 * 1024))
1243 + return CHILD_HOLDER;
1244 + close(fd);
1245 + n = loop_attach(at("img/md.img"));
1246 + if (n < 0)
1247 + return CHILD_HOLDER;
1248 + /* the minor is not the number of the device when loop has partitions */
1249 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
1250 + if (stat(dev, &st))
1251 + return CHILD_HOLDER;
1252 + disk.major = major(st.st_rdev);
1253 + disk.minor = minor(st.st_rdev);
1254 +
1255 + bfd = open(at("p/bitmap"), O_RDWR | O_CREAT | O_EXCL, 0600);
1256 + if (bfd < 0 || write(bfd, &bsb, sizeof(bsb)) != sizeof(bsb) || ftruncate(bfd, 4096))
1257 + return CHILD_HOLDER;
1258 +
1259 + if (read_sysfs("/proc/mdstat", buf, sizeof(buf))) {
1260 + fprintf(stderr, "md: no /proc/mdstat\n");
1261 + return CHILD_SKIP;
1262 + }
1263 + if (!strstr(buf, "[raid1]")) {
1264 + fprintf(stderr, "md: no raid1 personality: %s\n", buf);
1265 + return CHILD_SKIP;
1266 + }
1267 + /* a node of our own: /dev may not have one and is not ours to change */
1268 + if (mknod(at("img/md0"), S_IFBLK | 0600, makedev(MD_MAJOR, 0)))
1269 + return CHILD_HOLDER;
1270 + mdfd = open(at("img/md0"), O_RDWR);
1271 + if (mdfd < 0)
1272 + return CHILD_SKIP;
1273 + /* somebody else's array: SET_ARRAY_INFO would say EINVAL, not EBUSY */
1274 + if (!read_sysfs("/sys/block/md0/md/array_state", buf, sizeof(buf)) &&
1275 + strncmp(buf, "clear", 5)) {
1276 + fprintf(stderr, "md: md0 is in use: %s", buf);
1277 + close(mdfd);
1278 + return CHILD_SKIP;
1279 + }
1280 + /* the bitmap ops are only installed once a bitmap type is chosen */
1281 + write_file("/sys/block/md0/md/bitmap_type", "bitmap");
1282 + /* EBUSY: somebody else's array, leave it alone */
1283 + if (ioctl(mdfd, SET_ARRAY_INFO, &info))
1284 + return errno == EBUSY ? CHILD_SKIP : CHILD_HOLDER;
1285 + /* the array is ours from here on and has to be stopped on every path */
1286 + if (ioctl(mdfd, ADD_NEW_DISK, &disk))
1287 + goto undo;
1288 + /* attach the bitmap file before the array runs, the way mdadm does */
1289 + if (ioctl(mdfd, SET_BITMAP_FILE, bfd)) {
1290 + fprintf(stderr, "md: SET_BITMAP_FILE: %s\n", strerror(errno));
1291 + if (errno == EINVAL)
1292 + ret = CHILD_SKIP;
1293 + goto undo;
1294 + }
1295 + close(bfd); /* the array keeps its own */
1296 + if (ioctl(mdfd, RUN_ARRAY, NULL)) {
1297 + fprintf(stderr, "md: RUN_ARRAY: %s\n", strerror(errno));
1298 + goto undo;
1299 + }
1300 + if (write_fat12(mdfd))
1301 + goto undo;
1302 + close(mdfd);
1303 + if (mount_fat(at("img/md0"), HOLDER_BELOW)) {
1304 + ret = errno == ENODEV ? CHILD_NOFS : CHILD_HOLDER;
1305 + mdfd = open(at("img/md0"), O_RDWR);
1306 + goto undo;
1307 + }
1308 + return CHILD_OK;
1309 + undo:
1310 + if (mdfd >= 0) {
1311 + ioctl(mdfd, STOP_ARRAY);
1312 + close(mdfd);
1313 + }
1314 + return ret;
1315 + }
1316 +
1317 + /*
1318 + * A device keeps its file for as long as it is configured, so once nothing
1319 + * below the dead mount is left the device has to be told to let go. With
1320 + * the cycle unbroken C's filesystem still holds the device and every one
1321 + * of these refuses.
1322 + */
1323 + static int holder_let_go_once(enum holder holder)
1324 + {
1325 + int fd, ret;
1326 +
1327 + switch (holder) {
1328 + case HOLDER_ZRAM:
1329 + return write_file("/sys/block/zram0/reset", "1");
1330 + case HOLDER_ZLOOP:
1331 + return write_file("/dev/zloop-control", "remove id=0");
1332 + case HOLDER_GADGET:
1333 + if (mount_configfs())
1334 + return -1;
1335 + /* a zero-length write is a no-op for configfs; a newline ejects */
1336 + return write_file(gat("/functions/mass_storage.0/lun.0/file"), "\n");
1337 + case HOLDER_MD:
1338 + fd = open(at("img/md0"), O_RDONLY);
1339 + if (fd < 0) {
1340 + /* the child's node went with its tmpfs */
1341 + mknod(at("md0"), S_IFBLK | 0600, makedev(MD_MAJOR, 0));
1342 + fd = open(at("md0"), O_RDONLY);
1343 + }
1344 + if (fd < 0)
1345 + return -1;
1346 + ret = ioctl(fd, STOP_ARRAY);
1347 + close(fd);
1348 + return ret;
1349 + default:
1350 + return 0;
1351 + }
1352 + }
1353 +
1354 + static void zram_reset(void)
1355 + {
1356 + holder_let_go_once(HOLDER_ZRAM);
1357 + }
1358 +
1359 + /*
1360 + * In its own mount namespace the child puts the image on a tmpfs next to
1361 + * P, mounts P from a loop device, and sets the holder up with its own
1362 + * filesystem or device mounted at C below P.
1363 + */
1364 + static int holder_child(int to_parent, int from_parent, enum holder holder)
1365 + {
1366 + bool fifo = holder == HOLDER_AUTOFS || holder == HOLDER_ZRAM;
1367 + /* room for a 4 MiB zone file or a floppy image on P */
1368 + bool big = holder == HOLDER_ZLOOP || holder == HOLDER_GADGET;
1369 + struct report r = { { -1, -1 } };
1370 + char dev[32], c;
1371 + int ifd, n, ret;
1372 +
1373 + if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
1374 + return CHILD_NS;
1375 + if (mkdir(at("img"), 0755) || mount("tmpfs", at("img"), "tmpfs", 0, NULL))
1376 + return child_fails(CHILD_NS);
1377 +
1378 + ifd = open(HOLDER_IMG, O_RDWR | O_CREAT | O_EXCL, 0600);
1379 + if (ifd < 0 || (fifo ? write_minix(ifd) :
1380 + big ? write_fat12_4k(ifd, 3072) : write_fat12(ifd)))
1381 + return child_fails(CHILD_IMAGE);
1382 + close(ifd);
1383 + n = loop_attach(HOLDER_IMG);
1384 + if (n < 0)
1385 + return child_fails(CHILD_LOOP);
1386 + snprintf(dev, sizeof(dev), "/dev/loop%d", n);
1387 + if (mkdir(HOLDER_MNT, 0755))
1388 + return child_fails(CHILD_MOUNT);
1389 + if (fifo ? mount(dev, HOLDER_MNT, "minix", 0, NULL) : mount_fat(dev, HOLDER_MNT))
1390 + return child_fails(errno == ENODEV ? CHILD_NOFS : CHILD_MOUNT);
1391 + if (mkdir(HOLDER_BELOW, 0755))
1392 + return child_fails(CHILD_MOUNT);
1393 +
1394 + switch (holder) {
1395 + case HOLDER_AUTOFS:
1396 + ret = holder_autofs();
1397 + break;
1398 + case HOLDER_ZRAM:
1399 + ret = holder_zram();
1400 + break;
1401 + case HOLDER_ECRYPTFS:
1402 + ret = holder_ecryptfs();
1403 + break;
1404 + case HOLDER_BINFMT_MISC:
1405 + ret = holder_binfmt_misc();
1406 + break;
1407 + case HOLDER_FUSE:
1408 + ret = holder_fuse();
1409 + break;
1410 + case HOLDER_ZLOOP:
1411 + ret = holder_zloop();
1412 + break;
1413 + case HOLDER_GADGET:
1414 + ret = holder_gadget();
1415 + break;
1416 + case HOLDER_MD:
1417 + ret = holder_md();
1418 + break;
1419 + default:
1420 + ret = CHILD_HOLDER;
1421 + }
1422 + if (ret != CHILD_OK)
1423 + return child_fails(ret);
1424 +
1425 + /* P's device first, then the one the holder has bound for itself */
1426 + r.n[0] = n;
1427 + if (nr_bound > 1)
1428 + r.n[1] = bound[1];
1429 + if (write(to_parent, &r, sizeof(r)) != sizeof(r) ||
1430 + read(from_parent, &c, 1) != 1) {
1431 + /* the parent went away and will not tell the devices to let go */
1432 + umount2(HOLDER_BELOW, MNT_DETACH);
1433 + for (int i = 0; i < 50 && holder_let_go_once(holder); i++)
1434 + usleep(100000);
1435 + if (holder == HOLDER_GADGET)
1436 + gadget_remove();
1437 + return child_fails(CHILD_PIPE);
1438 + }
1439 + return CHILD_OK;
1440 + }
1441 +
1442 + /*
1443 + * The release of C's filesystem may still be in flight when the child is
1444 + * gone, and a device that is still held refuses to let go, so try for a
1445 + * while. With the cycle unbroken it refuses for good.
1446 + */
1447 + static void holder_let_go(enum holder holder)
1448 + {
1449 + for (int i = 0; i < 50; i++) {
1450 + if (!holder_let_go_once(holder))
1451 + return;
1452 + usleep(100000);
1453 + }
1454 + }
1455 +
1456 + /*
1457 + * rmdir of p from here, where it is a plain directory, detaches
1458 + * P in the child's namespace with C connected below it. Once the child is
1459 + * gone the holder's file on P is the only thing left that refers to P,
1460 + * and it is dropped only when C's filesystem dies, which waits for P.
1461 + * The loop device backing P tells whether that resolved.
1462 + */
1463 + static void holder_cycle(struct __test_metadata *_metadata,
1464 + FIXTURE_DATA(loop_cycle) *self, enum holder holder)
1465 + {
1466 + struct report r = { { -1, -1 } };
1467 + int to_parent[2], from_parent[2];
1468 + pid_t pid;
1469 +
1470 + ASSERT_EQ(pipe(to_parent), 0);
1471 + ASSERT_EQ(pipe(from_parent), 0);
1472 + pid = fork();
1473 + ASSERT_GE(pid, 0);
1474 + if (pid == 0) {
1475 + close(to_parent[0]);
1476 + close(from_parent[1]);
1477 + _exit(holder_child(to_parent[1], from_parent[0], holder));
1478 + }
1479 + close(to_parent[1]);
1480 + close(from_parent[0]);
1481 +
1482 + if (read(to_parent[0], &r, sizeof(r)) != sizeof(r))
1483 + CHILD_GAVE_UP(pid);
1484 + self->gadget = holder == HOLDER_GADGET;
1485 + remember_loop(self, r.n[0]);
1486 + remember_loop(self, r.n[1]);
1487 + snprintf(self->dev, sizeof(self->dev), "/dev/loop%d", r.n[0]);
1488 + snprintf(self->sysfs, sizeof(self->sysfs), "/sys/block/loop%d/loop/backing_file", r.n[0]);
1489 +
1490 + ASSERT_EQ(rmdir(HOLDER_MNT), 0);
1491 + ASSERT_EQ(write(from_parent[1], "x", 1), 1);
1492 + CHILD_LEFT(pid);
1493 + close(to_parent[0]);
1494 + close(from_parent[1]);
1495 +
1496 + holder_let_go(holder);
1497 + assert_loop_released(_metadata, self);
1498 + /* the teardown takes the gadget and the holder's own loop device away */
1499 + }
1500 +
1501 + TEST_F(loop_cycle, autofs_pipe_on_dead_mount_released)
1502 + {
1503 + holder_cycle(_metadata, self, HOLDER_AUTOFS);
1504 + }
1505 +
1506 + TEST_F(loop_cycle, zram_writeback_node_on_dead_mount_released)
1507 + {
1508 + holder_cycle(_metadata, self, HOLDER_ZRAM);
1509 + }
1510 +
1511 + TEST_F(loop_cycle, ecryptfs_lower_on_dead_mount_released)
1512 + {
1513 + holder_cycle(_metadata, self, HOLDER_ECRYPTFS);
1514 + }
1515 +
1516 + TEST_F(loop_cycle, binfmt_misc_interpreter_on_dead_mount_released)
1517 + {
1518 + holder_cycle(_metadata, self, HOLDER_BINFMT_MISC);
1519 + }
1520 +
1521 + TEST_F(loop_cycle, fuse_backing_file_on_dead_mount_released)
1522 + {
1523 + holder_cycle(_metadata, self, HOLDER_FUSE);
1524 + }
1525 +
1526 + TEST_F(loop_cycle, zloop_zone_files_on_dead_mount_released)
1527 + {
1528 + holder_cycle(_metadata, self, HOLDER_ZLOOP);
1529 + }
1530 +
1531 + /* up to 15 s for the disk to show up and 12 s for a device that is held */
1532 + TEST_F_TIMEOUT(loop_cycle, mass_storage_lun_on_dead_mount_released, 120)
1533 + {
1534 + holder_cycle(_metadata, self, HOLDER_GADGET);
1535 + }
1536 +
1537 + TEST_F(loop_cycle, md_bitmap_file_on_dead_mount_released)
1538 + {
1539 + holder_cycle(_metadata, self, HOLDER_MD);
1540 + }
1541 +
1542 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/mount_cover_test.c mode 100644
@@ -0,0 +1,579 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * An unmounted mount that would have stayed attached to its unmounted parent
4 + * leaves a cover behind instead. A lookup on the parent at the mountpoint
5 + * finds knullfs: an empty read-only directory that is shared by every cover
6 + * and every kernel thread, so it can't be watched or locked and nothing can
7 + * be mounted on it. The mount itself is a root from then on. Where a file
8 + * was mounted, the stand-in is an empty regular file of the same instance.
9 + */
10 + #define _GNU_SOURCE
11 + #include <errno.h>
12 + #include <fcntl.h>
13 + #include <sched.h>
14 + #include <stdint.h>
15 + #include <stdio.h>
16 + #include <stdlib.h>
17 + #include <string.h>
18 + #include <unistd.h>
19 + #include <sys/fanotify.h>
20 + #include <sys/file.h>
21 + #include <sys/inotify.h>
22 + #include <sys/mount.h>
23 + #include <sys/prctl.h>
24 + #include <sys/stat.h>
25 + #include <sys/statvfs.h>
26 + #include <sys/syscall.h>
27 + #include <sys/vfs.h>
28 + #include <sys/wait.h>
29 +
30 + #include "../../kselftest_harness.h"
31 + #include "../readdir_hold.h"
32 +
33 + #ifndef NULL_FS_MAGIC
34 + #define NULL_FS_MAGIC 0x4E554C4C
35 + #endif
36 +
37 + #ifndef TMPFS_MAGIC
38 + #define TMPFS_MAGIC 0x01021994
39 + #endif
40 +
41 + #ifndef F_SETDELEG
42 + #define F_SETDELEG (F_SETLEASE + 16)
43 + #endif
44 +
45 + /* struct delegation of <linux/fcntl.h>, which doesn't mix with <fcntl.h> */
46 + struct delegation_req {
47 + uint32_t d_flags;
48 + uint16_t d_type;
49 + uint16_t __pad;
50 + };
51 +
52 + #define DIR_LEN 64
53 + #define PATH_LEN 128
54 +
55 + /* what the parent asks the child to do */
56 + #define CMD_RMDIR 'r'
57 + #define CMD_CLOSE_T 't'
58 + #define CMD_QUIT 'q'
59 +
60 + static int write_file(const char *path, const char *s)
61 + {
62 + ssize_t n = -1;
63 + int fd;
64 +
65 + fd = open(path, O_WRONLY | O_CLOEXEC);
66 + if (fd >= 0) {
67 + n = write(fd, s, strlen(s));
68 + close(fd);
69 + }
70 + return n == (ssize_t)strlen(s) ? 0 : -1;
71 + }
72 +
73 + static int touch(const char *path)
74 + {
75 + int fd;
76 +
77 + fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
78 + if (fd < 0)
79 + return -1;
80 + close(fd);
81 + return 0;
82 + }
83 +
84 + /* Become root in a new user namespace with a private mount namespace. */
85 + static int enter_userns(void)
86 + {
87 + uid_t uid = getuid();
88 + gid_t gid = getgid();
89 + char map[32];
90 +
91 + prctl(PR_SET_DUMPABLE, 1);
92 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
93 + return -1;
94 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
95 + return -1;
96 + snprintf(map, sizeof(map), "0 %d 1", uid);
97 + if (write_file("/proc/self/uid_map", map))
98 + return -1;
99 + snprintf(map, sizeof(map), "0 %d 1", gid);
100 + if (write_file("/proc/self/gid_map", map))
101 + return -1;
102 + if (setgid(0) || setuid(0))
103 + return -1;
104 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
105 + }
106 +
107 + /*
108 + * The child mounts P on @base/p, C on P/covered and the file P/src on P/file
109 + * in a mount namespace of its own, binds P a second time at @base/q and hands
110 + * out descriptors on P and on C. rmdir() of @base/p from here unmounts P
111 + * together with C and the file bind. P and C are held by the descriptors and
112 + * the unmounted children leave their covers behind. On request the child
113 + * removes C's mountpoint through the bind.
114 + *
115 + * It also mounts T on @base/t with a child on T/covered, binds T at @base/u
116 + * with a second child on the same dentry and hands out descriptors on T and
117 + * U. rmdir() of both from here leaves two covers on one mountpoint. On request
118 + * the child lets go of T.
119 + */
120 + static int cover_child(const char *base, int to_parent, int from_parent)
121 + {
122 + char p[PATH_LEN], c[PATH_LEN], q[PATH_LEN], qc[PATH_LEN];
123 + char f[PATH_LEN], src[PATH_LEN], t[PATH_LEN], u[PATH_LEN], tc[PATH_LEN];
124 + int fds[4], ret;
125 + char cmd;
126 +
127 + if (unshare(CLONE_NEWNS) || mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL))
128 + return 1;
129 + snprintf(p, sizeof(p), "%s/p", base);
130 + if (mkdir(p, 0755) || mount("tmpfs", p, "tmpfs", 0, NULL))
131 + return 2;
132 + snprintf(c, sizeof(c), "%s/p/covered", base);
133 + if (mkdir(c, 0755) || mount("tmpfs", c, "tmpfs", 0, NULL))
134 + return 3;
135 + snprintf(f, sizeof(f), "%s/p/file", base);
136 + snprintf(src, sizeof(src), "%s/p/src", base);
137 + if (touch(src) || touch(f) || mount(src, f, NULL, MS_BIND, NULL))
138 + return 4;
139 + snprintf(q, sizeof(q), "%s/q", base);
140 + if (mkdir(q, 0755) || mount(p, q, NULL, MS_BIND, NULL))
141 + return 5;
142 + snprintf(t, sizeof(t), "%s/t", base);
143 + if (mkdir(t, 0755) || mount("tmpfs", t, "tmpfs", 0, NULL))
144 + return 6;
145 + snprintf(tc, sizeof(tc), "%s/t/covered", base);
146 + if (mkdir(tc, 0755) || mount("tmpfs", tc, "tmpfs", 0, NULL))
147 + return 7;
148 + snprintf(u, sizeof(u), "%s/u", base);
149 + if (mkdir(u, 0755) || mount(t, u, NULL, MS_BIND, NULL))
150 + return 8;
151 + snprintf(tc, sizeof(tc), "%s/u/covered", base);
152 + if (mount("tmpfs", tc, "tmpfs", 0, NULL))
153 + return 9;
154 + fds[0] = open(p, O_PATH | O_DIRECTORY | O_CLOEXEC);
155 + fds[1] = open(c, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
156 + fds[2] = open(t, O_PATH | O_DIRECTORY | O_CLOEXEC);
157 + fds[3] = open(u, O_PATH | O_DIRECTORY | O_CLOEXEC);
158 + if (fds[0] < 0 || fds[1] < 0 || fds[2] < 0 || fds[3] < 0)
159 + return 10;
160 + if (write(to_parent, fds, sizeof(fds)) != sizeof(fds))
161 + return 11;
162 +
163 + snprintf(qc, sizeof(qc), "%s/q/covered", base);
164 + for (;;) {
165 + if (read(from_parent, &cmd, 1) != 1)
166 + return 12;
167 + switch (cmd) {
168 + case CMD_RMDIR:
169 + ret = rmdir(qc) ? errno : 0;
170 + if (write(to_parent, &ret, sizeof(ret)) != sizeof(ret))
171 + return 13;
172 + break;
173 + case CMD_CLOSE_T:
174 + ret = close(fds[2]) ? errno : 0;
175 + if (write(to_parent, &ret, sizeof(ret)) != sizeof(ret))
176 + return 13;
177 + break;
178 + case CMD_QUIT:
179 + return 0;
180 + default:
181 + return 14;
182 + }
183 + }
184 + }
185 +
186 + FIXTURE(mount_cover) {
187 + char base[DIR_LEN];
188 + pid_t child;
189 + int to_child;
190 + int from_child;
191 + int dfd; /* P, unmounted, held */
192 + int cfd; /* C, unmounted, held */
193 + int fd; /* what a lookup on P finds at C's mountpoint */
194 + int tfd; /* T, unmounted, held */
195 + int ufd; /* U, a bind of T, unmounted, held */
196 + int fan; /* fanotify group from before the user namespace, or -1 */
197 + struct readdir_hold hold; /* likewise from before, uffd -1 without */
198 + };
199 +
200 + /*
201 + * Everything the setup has made. The harness does not run the teardown
202 + * when an assertion of the setup fails, so the setup calls this itself.
203 + */
204 + static void cover_cleanup(FIXTURE_DATA(mount_cover) *self)
205 + {
206 + char cmd = CMD_QUIT;
207 + int status;
208 +
209 + if (self->fd >= 0)
210 + close(self->fd);
211 + if (self->cfd >= 0)
212 + close(self->cfd);
213 + if (self->dfd >= 0)
214 + close(self->dfd);
215 + if (self->tfd >= 0)
216 + close(self->tfd);
217 + if (self->ufd >= 0)
218 + close(self->ufd);
219 + if (self->fan >= 0)
220 + close(self->fan);
221 + readdir_hold_destroy(&self->hold);
222 + if (self->child > 0) {
223 + if (write(self->to_child, &cmd, 1) != 1)
224 + kill(self->child, SIGKILL);
225 + waitpid(self->child, &status, 0);
226 + }
227 + if (self->to_child >= 0)
228 + close(self->to_child);
229 + if (self->from_child >= 0)
230 + close(self->from_child);
231 + umount2(self->base, MNT_DETACH);
232 + rmdir(self->base);
233 + }
234 +
235 + static int same_file(int fd1, int fd2)
236 + {
237 + struct stat st1, st2;
238 +
239 + if (fstat(fd1, &st1) || fstat(fd2, &st2))
240 + return 0;
241 + return st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino;
242 + }
243 +
244 + FIXTURE_SETUP(mount_cover)
245 + {
246 + int to_parent[2], to_child[2], fds[4], pidfd, status;
247 + char dir[PATH_LEN];
248 + struct statfs sf;
249 +
250 + self->child = 0;
251 + self->to_child = self->from_child = -1;
252 + self->dfd = self->cfd = self->fd = self->tfd = self->ufd = -1;
253 +
254 + /*
255 + * A group for plain events takes CAP_SYS_ADMIN in the initial user
256 + * namespace, so get one before that is gone. An inode mark can be
257 + * added to it from anywhere.
258 + */
259 + self->fan = fanotify_init(FAN_CLASS_NOTIF | FAN_CLOEXEC, O_RDONLY);
260 + /* same for the userfaultfd that holds a readdir in its fault */
261 + readdir_hold_init(&self->hold);
262 +
263 + snprintf(self->base, sizeof(self->base), "/tmp/mount_cover.XXXXXX");
264 + ASSERT_NE(mkdtemp(self->base), NULL);
265 + if (enter_userns()) {
266 + cover_cleanup(self);
267 + SKIP(return, "test requires user namespaces");
268 + }
269 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, NULL), 0)
270 + cover_cleanup(self);
271 +
272 + snprintf(dir, sizeof(dir), "%s/p", self->base);
273 + ASSERT_EQ(pipe(to_parent), 0)
274 + cover_cleanup(self);
275 + ASSERT_EQ(pipe(to_child), 0)
276 + cover_cleanup(self);
277 + self->child = fork();
278 + ASSERT_GE(self->child, 0)
279 + cover_cleanup(self);
280 + if (self->child == 0) {
281 + close(to_parent[0]);
282 + close(to_child[1]);
283 + _exit(cover_child(self->base, to_parent[1], to_child[0]));
284 + }
285 + close(to_parent[1]);
286 + close(to_child[0]);
287 + self->to_child = to_child[1];
288 + self->from_child = to_parent[0];
289 + if (read(self->from_child, fds, sizeof(fds)) != sizeof(fds)) {
290 + pid_t pid = self->child;
291 +
292 + waitpid(pid, &status, 0);
293 + self->child = 0;
294 + cover_cleanup(self);
295 + ASSERT_TRUE(false)
296 + TH_LOG("child failed to set up: %s %d",
297 + WIFEXITED(status) ? "step" : "signal",
298 + WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status));
299 + }
300 +
301 + pidfd = syscall(__NR_pidfd_open, self->child, 0);
302 + ASSERT_GE(pidfd, 0)
303 + cover_cleanup(self);
304 + self->dfd = syscall(__NR_pidfd_getfd, pidfd, fds[0], 0);
305 + self->cfd = syscall(__NR_pidfd_getfd, pidfd, fds[1], 0);
306 + self->tfd = syscall(__NR_pidfd_getfd, pidfd, fds[2], 0);
307 + self->ufd = syscall(__NR_pidfd_getfd, pidfd, fds[3], 0);
308 + close(pidfd);
309 + ASSERT_GE(self->dfd, 0)
310 + cover_cleanup(self);
311 + ASSERT_GE(self->cfd, 0)
312 + cover_cleanup(self);
313 + ASSERT_GE(self->tfd, 0)
314 + cover_cleanup(self);
315 + ASSERT_GE(self->ufd, 0)
316 + cover_cleanup(self);
317 +
318 + /* unmounts P and C, C leaves its cover behind */
319 + ASSERT_EQ(rmdir(dir), 0)
320 + cover_cleanup(self);
321 + /* unmounts T and U with their children, two covers on one mountpoint */
322 + snprintf(dir, sizeof(dir), "%s/t", self->base);
323 + ASSERT_EQ(rmdir(dir), 0)
324 + cover_cleanup(self);
325 + snprintf(dir, sizeof(dir), "%s/u", self->base);
326 + ASSERT_EQ(rmdir(dir), 0)
327 + cover_cleanup(self);
328 +
329 + self->fd = openat(self->dfd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
330 + ASSERT_GE(self->fd, 0)
331 + cover_cleanup(self);
332 + ASSERT_EQ(fstatfs(self->fd, &sf), 0)
333 + cover_cleanup(self);
334 + ASSERT_EQ(sf.f_type, NULL_FS_MAGIC)
335 + cover_cleanup(self);
336 + }
337 +
338 + FIXTURE_TEARDOWN(mount_cover)
339 + {
340 + cover_cleanup(self);
341 + }
342 +
343 + TEST_F(mount_cover, not_watchable)
344 + {
345 + char p[PATH_LEN];
346 + int ifd;
347 +
348 + snprintf(p, sizeof(p), "/proc/self/fd/%d", self->fd);
349 +
350 + ifd = inotify_init1(IN_CLOEXEC);
351 + if (ifd < 0 && errno == ENOSYS) {
352 + TH_LOG("no inotify in this kernel, skipping that part");
353 + } else {
354 + ASSERT_GE(ifd, 0);
355 + EXPECT_EQ(inotify_add_watch(ifd, p, IN_OPEN), -1);
356 + EXPECT_EQ(errno, EINVAL);
357 + close(ifd);
358 + }
359 +
360 + /* dnotify ends up at the same place */
361 + EXPECT_EQ(fcntl(self->fd, F_NOTIFY, DN_ACCESS), -1);
362 + EXPECT_EQ(errno, EINVAL);
363 +
364 + if (self->fan < 0) {
365 + TH_LOG("no fanotify group without CAP_SYS_ADMIN in the initial user namespace, skipping the fanotify part");
366 + return;
367 + }
368 + EXPECT_EQ(fanotify_mark(self->fan, FAN_MARK_ADD, FAN_OPEN, self->fd, NULL), -1);
369 + EXPECT_EQ(errno, EINVAL);
370 + }
371 +
372 + TEST_F(mount_cover, not_lockable)
373 + {
374 + struct flock fl = {
375 + .l_type = F_RDLCK,
376 + .l_whence = SEEK_SET,
377 + };
378 +
379 + EXPECT_EQ(flock(self->fd, LOCK_EX | LOCK_NB), -1);
380 + EXPECT_EQ(errno, ENOLCK);
381 + EXPECT_EQ(fcntl(self->fd, F_SETLK, &fl), -1);
382 + EXPECT_EQ(errno, ENOLCK);
383 + EXPECT_EQ(fcntl(self->fd, F_GETLK, &fl), -1);
384 + EXPECT_EQ(errno, ENOLCK);
385 + }
386 +
387 + /* a lease is refused for the owner and for everybody else alike */
388 + TEST_F(mount_cover, not_leasable)
389 + {
390 + struct delegation_req deleg = {
391 + .d_type = F_RDLCK,
392 + };
393 +
394 + EXPECT_EQ(fcntl(self->fd, F_SETLEASE, F_RDLCK), -1);
395 + EXPECT_TRUE(errno == EINVAL || errno == EACCES);
396 + EXPECT_EQ(fcntl(self->fd, F_SETDELEG, &deleg), -1);
397 + EXPECT_TRUE(errno == EINVAL || errno == EACCES);
398 + }
399 +
400 + TEST_F(mount_cover, not_mountable)
401 + {
402 + char p[PATH_LEN];
403 +
404 + snprintf(p, sizeof(p), "/proc/self/fd/%d", self->fd);
405 + EXPECT_EQ(mount("tmpfs", p, "tmpfs", 0, NULL), -1);
406 + EXPECT_EQ(errno, ENOENT);
407 + }
408 +
409 + TEST_F(mount_cover, read_only)
410 + {
411 + struct statvfs sv;
412 +
413 + EXPECT_EQ(mkdirat(self->fd, "x", 0755), -1);
414 + EXPECT_EQ(errno, ENOENT);
415 + EXPECT_EQ(fchmod(self->fd, 0777), -1);
416 + EXPECT_EQ(errno, EROFS);
417 + /* the immutable inode is checked before the read-only mount */
418 + EXPECT_EQ(faccessat(self->fd, ".", W_OK, 0), -1);
419 + EXPECT_EQ(errno, EPERM);
420 + ASSERT_EQ(fstatvfs(self->fd, &sv), 0);
421 + EXPECT_TRUE(sv.f_flag & ST_RDONLY);
422 + }
423 +
424 + /* the stand-in is a root of its own, ".." stays put */
425 + TEST_F(mount_cover, island)
426 + {
427 + int fd;
428 +
429 + fd = openat(self->fd, "..", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
430 + ASSERT_GE(fd, 0);
431 + EXPECT_TRUE(same_file(fd, self->fd));
432 + close(fd);
433 + }
434 +
435 + /*
436 + * C is alive for as long as the child holds it, but it can't be reached
437 + * through P anymore and it's a root of its own as well.
438 + */
439 + TEST_F(mount_cover, held_child_detached)
440 + {
441 + struct statfs sf;
442 + int fd;
443 +
444 + ASSERT_EQ(fstatfs(self->cfd, &sf), 0);
445 + EXPECT_EQ(sf.f_type, TMPFS_MAGIC);
446 +
447 + fd = openat(self->cfd, "..", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
448 + ASSERT_GE(fd, 0);
449 + EXPECT_TRUE(same_file(fd, self->cfd));
450 + close(fd);
451 +
452 + fd = openat(self->dfd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
453 + ASSERT_GE(fd, 0);
454 + ASSERT_EQ(fstatfs(fd, &sf), 0);
455 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
456 + close(fd);
457 + }
458 +
459 + /*
460 + * The cover goes with its mountpoint: once the child has removed C's
461 + * mountpoint through the bind of P, the name is gone from P as well.
462 + * What was opened through the cover before stays open.
463 + */
464 + TEST_F(mount_cover, cover_goes_with_mountpoint)
465 + {
466 + char cmd = CMD_RMDIR;
467 + struct statfs sf;
468 + int ret;
469 +
470 + ASSERT_EQ(write(self->to_child, &cmd, 1), 1);
471 + ASSERT_EQ(read(self->from_child, &ret, sizeof(ret)), sizeof(ret));
472 + ASSERT_EQ(ret, 0);
473 +
474 + EXPECT_EQ(openat(self->dfd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC), -1);
475 + EXPECT_EQ(errno, ENOENT);
476 + ASSERT_EQ(fstatfs(self->fd, &sf), 0);
477 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
478 + }
479 +
480 + /*
481 + * A readdir of the stand-in holds nothing that others wait for: one holder
482 + * sticks in the page fault of its buffer, and a create and a lookup of
483 + * another come back meanwhile.
484 + */
485 + TEST_F(mount_cover, readdir_blocks_nobody)
486 + {
487 + bool stalled;
488 +
489 + if (self->hold.uffd < 0)
490 + SKIP(return, "test requires userfaultfd");
491 + ASSERT_EQ(readdir_hold_check(&self->hold, self->fd, &stalled), 0);
492 + EXPECT_FALSE(stalled);
493 + }
494 +
495 + /* where a file was mounted, the stand-in is an empty regular file */
496 + TEST_F(mount_cover, file_stand_in)
497 + {
498 + char src[PATH_LEN], p[PATH_LEN];
499 + struct statfs sf;
500 + struct stat st;
501 + char c;
502 + int fd;
503 +
504 + fd = openat(self->dfd, "file", O_RDONLY | O_CLOEXEC);
505 + ASSERT_GE(fd, 0);
506 + ASSERT_EQ(fstat(fd, &st), 0);
507 + EXPECT_TRUE(S_ISREG(st.st_mode));
508 + ASSERT_EQ(fstatfs(fd, &sf), 0);
509 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
510 + /* the two stand-ins are two inodes */
511 + EXPECT_FALSE(same_file(fd, self->fd));
512 + EXPECT_EQ(read(fd, &c, 1), 0);
513 + EXPECT_EQ(flock(fd, LOCK_EX | LOCK_NB), -1);
514 + EXPECT_EQ(errno, ENOLCK);
515 +
516 + snprintf(src, sizeof(src), "%s/src", self->base);
517 + ASSERT_EQ(touch(src), 0);
518 + snprintf(p, sizeof(p), "/proc/self/fd/%d", fd);
519 + EXPECT_EQ(mount(src, p, NULL, MS_BIND, NULL), -1);
520 + EXPECT_EQ(errno, ENOENT);
521 + close(fd);
522 +
523 + /* writes and truncates go nowhere, like /dev/null */
524 + fd = openat(self->dfd, "file", O_WRONLY | O_TRUNC | O_CLOEXEC);
525 + ASSERT_GE(fd, 0);
526 + EXPECT_EQ(write(fd, "xy", 2), 2);
527 + EXPECT_EQ(ftruncate(fd, 4), 0);
528 + ASSERT_EQ(fstat(fd, &st), 0);
529 + EXPECT_EQ(st.st_size, 0);
530 + /* the shared inode keeps its identity */
531 + EXPECT_EQ(fchmod(fd, 0600), -1);
532 + EXPECT_EQ(errno, EPERM);
533 + close(fd);
534 + fd = openat(self->dfd, "file", O_RDONLY | O_CLOEXEC);
535 + ASSERT_GE(fd, 0);
536 + EXPECT_EQ(read(fd, &c, 1), 0);
537 + close(fd);
538 +
539 + EXPECT_EQ(openat(self->dfd, "file", O_RDONLY | O_DIRECTORY | O_CLOEXEC), -1);
540 + EXPECT_EQ(errno, ENOTDIR);
541 + }
542 +
543 + /*
544 + * Two unmounted parents left covers on the same dentry. A lookup on
545 + * either finds a stand-in, and U's cover stays when T goes.
546 + */
547 + TEST_F(mount_cover, shared_mountpoint)
548 + {
549 + char cmd = CMD_CLOSE_T;
550 + struct statfs sf;
551 + int fd, ret;
552 +
553 + fd = openat(self->tfd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
554 + ASSERT_GE(fd, 0);
555 + ASSERT_EQ(fstatfs(fd, &sf), 0);
556 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
557 + close(fd);
558 +
559 + fd = openat(self->ufd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
560 + ASSERT_GE(fd, 0);
561 + ASSERT_EQ(fstatfs(fd, &sf), 0);
562 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
563 + close(fd);
564 +
565 + /* the last references to T go, with T its cover */
566 + ASSERT_EQ(write(self->to_child, &cmd, 1), 1);
567 + ASSERT_EQ(read(self->from_child, &ret, sizeof(ret)), sizeof(ret));
568 + ASSERT_EQ(ret, 0);
569 + close(self->tfd);
570 + self->tfd = -1;
571 +
572 + fd = openat(self->ufd, "covered", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
573 + ASSERT_GE(fd, 0);
574 + ASSERT_EQ(fstatfs(fd, &sf), 0);
575 + EXPECT_EQ(sf.f_type, NULL_FS_MAGIC);
576 + close(fd);
577 + }
578 +
579 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/nsfs_rbind_loop_test.c mode 100644
@@ -0,0 +1,193 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A recursive bind mount of a namespace file that lives in another mount
4 + * namespace copies whatever is stacked on top of it there. If that includes
5 + * the file of the caller's own mount namespace, or of an older one, the copy
6 + * would pin the namespace it is put in forever. The bind mount has to be
7 + * refused, a plain bind mount of the file itself still works.
8 + */
9 + #define _GNU_SOURCE
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <sched.h>
13 + #include <stdio.h>
14 + #include <stdlib.h>
15 + #include <string.h>
16 + #include <unistd.h>
17 + #include <sys/mount.h>
18 + #include <sys/stat.h>
19 + #include <sys/wait.h>
20 +
21 + #include "../../kselftest_harness.h"
22 +
23 + #define DIR_LEN 64
24 + #define PATH_LEN 128
25 +
26 + /* Child exit codes. */
27 + enum {
28 + CHILD_OK,
29 + CHILD_UNSHARE, /* could not create the newer mount namespace */
30 + CHILD_PIPE, /* the parent went away */
31 + CHILD_TMPFS, /* could not mount the tmpfs in the new namespace */
32 + CHILD_REC_ALLOWED, /* the recursive bind mount was not refused */
33 + CHILD_REC_ERRNO, /* it was refused with the wrong error */
34 + CHILD_PLAIN_REFUSED, /* the plain bind mount of the file was refused */
35 + };
36 +
37 + static int write_file(const char *path, const char *s)
38 + {
39 + ssize_t n = -1;
40 + int fd;
41 +
42 + fd = open(path, O_WRONLY | O_CLOEXEC);
43 + if (fd >= 0) {
44 + n = write(fd, s, strlen(s));
45 + close(fd);
46 + }
47 + return n == (ssize_t)strlen(s) ? 0 : -1;
48 + }
49 +
50 + static int create_file(const char *path)
51 + {
52 + int fd = open(path, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);
53 +
54 + if (fd < 0)
55 + return -1;
56 + close(fd);
57 + return 0;
58 + }
59 +
60 + /* Become root in a new user namespace with a private mount namespace. */
61 + static int enter_userns(void)
62 + {
63 + uid_t uid = getuid();
64 + gid_t gid = getgid();
65 + char map[32];
66 +
67 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
68 + return -1;
69 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
70 + return -1;
71 + snprintf(map, sizeof(map), "0 %d 1", uid);
72 + if (write_file("/proc/self/uid_map", map))
73 + return -1;
74 + snprintf(map, sizeof(map), "0 %d 1", gid);
75 + if (write_file("/proc/self/gid_map", map))
76 + return -1;
77 + if (setgid(0) || setuid(0))
78 + return -1;
79 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
80 + }
81 +
82 + static int send_msg(int fd, char msg)
83 + {
84 + return write(fd, &msg, 1) == 1 ? 0 : -1;
85 + }
86 +
87 + static char recv_msg(int fd)
88 + {
89 + char msg;
90 +
91 + if (read(fd, &msg, 1) != 1)
92 + return 0;
93 + return msg;
94 + }
95 +
96 + FIXTURE(nsfs_rbind_loop) {
97 + char dir[DIR_LEN];
98 + char x[PATH_LEN];
99 + };
100 +
101 + FIXTURE_SETUP(nsfs_rbind_loop)
102 + {
103 + snprintf(self->dir, sizeof(self->dir), "/tmp/nsfs_rbind_loop.XXXXXX");
104 + ASSERT_NE(mkdtemp(self->dir), NULL);
105 + if (enter_userns()) {
106 + rmdir(self->dir);
107 + SKIP(return, "test requires user namespaces");
108 + }
109 + ASSERT_EQ(mount("tmpfs", self->dir, "tmpfs", 0, NULL), 0);
110 + snprintf(self->x, sizeof(self->x), "%s/x", self->dir);
111 + ASSERT_EQ(create_file(self->x), 0);
112 + }
113 +
114 + FIXTURE_TEARDOWN(nsfs_rbind_loop)
115 + {
116 + umount2(self->dir, MNT_DETACH);
117 + rmdir(self->dir);
118 + }
119 +
120 + /*
121 + * The child in the newer mount namespace binds the network namespace file
122 + * mount of the parent through @fd. Recursively that would copy the mount of
123 + * its own mount namespace file that the parent stacked on top.
124 + */
125 + static int newer_ns_child(const char *dir, int fd, int to_parent, int from_parent)
126 + {
127 + char src[32], y[PATH_LEN];
128 +
129 + if (unshare(CLONE_NEWNS))
130 + return CHILD_UNSHARE;
131 + if (send_msg(to_parent, 'r') || recv_msg(from_parent) != 'g')
132 + return CHILD_PIPE;
133 +
134 + snprintf(y, sizeof(y), "%s/y", dir);
135 + if (mount("tmpfs", y, "tmpfs", 0, NULL))
136 + return CHILD_TMPFS;
137 + snprintf(src, sizeof(src), "/proc/self/fd/%d", fd);
138 + snprintf(y, sizeof(y), "%s/y/f", dir);
139 + if (create_file(y))
140 + return CHILD_TMPFS;
141 +
142 + if (!mount(src, y, NULL, MS_BIND | MS_REC, NULL))
143 + return CHILD_REC_ALLOWED;
144 + if (errno != EINVAL)
145 + return CHILD_REC_ERRNO;
146 + if (mount(src, y, NULL, MS_BIND, NULL))
147 + return CHILD_PLAIN_REFUSED;
148 + umount2(y, MNT_DETACH);
149 + return CHILD_OK;
150 + }
151 +
152 + TEST_F(nsfs_rbind_loop, own_ns_file_below_foreign_source)
153 + {
154 + int to_child[2], to_parent[2], fd, status;
155 + char p[PATH_LEN];
156 + pid_t pid;
157 +
158 + snprintf(p, sizeof(p), "%s/y", self->dir);
159 + ASSERT_EQ(mkdir(p, 0755), 0);
160 +
161 + /* M, a mount of our network namespace file, held by a descriptor */
162 + ASSERT_EQ(mount("/proc/self/ns/net", self->x, NULL, MS_BIND, NULL), 0);
163 + fd = open(self->x, O_PATH | O_CLOEXEC);
164 + ASSERT_GE(fd, 0);
165 +
166 + ASSERT_EQ(pipe(to_child), 0);
167 + ASSERT_EQ(pipe(to_parent), 0);
168 + pid = fork();
169 + ASSERT_GE(pid, 0);
170 + if (pid == 0) {
171 + close(to_child[1]);
172 + close(to_parent[0]);
173 + _exit(newer_ns_child(self->dir, fd, to_parent[1], to_child[0]));
174 + }
175 + close(to_child[0]);
176 + close(to_parent[1]);
177 + ASSERT_EQ(recv_msg(to_parent[0]), 'r');
178 +
179 + /* the child's mount namespace file on top of M */
180 + snprintf(p, sizeof(p), "/proc/%d/ns/mnt", pid);
181 + ASSERT_EQ(mount(p, self->x, NULL, MS_BIND, NULL), 0);
182 +
183 + ASSERT_EQ(send_msg(to_child[1], 'g'), 0);
184 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
185 + ASSERT_TRUE(WIFEXITED(status));
186 + ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
187 +
188 + close(fd);
189 + ASSERT_EQ(umount2(self->x, MNT_DETACH), 0);
190 + ASSERT_EQ(umount2(self->x, MNT_DETACH), 0);
191 + }
192 +
193 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/overmount_ns_file_test.c mode 100644
@@ -0,0 +1,190 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A mount namespace file bind-mounted on top of the mount that is moved
4 + * onto a shared mount isn't copied to the peers and slaves. The mount that
5 + * already sits at the destination in a slave has to end up on top of the
6 + * propagated copy, not below the root of the mount namespace file where no
7 + * path walk ever finds it.
8 + */
9 + #define _GNU_SOURCE
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <sched.h>
13 + #include <signal.h>
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <unistd.h>
18 + #include <sys/mount.h>
19 + #include <sys/stat.h>
20 + #include <sys/syscall.h>
21 + #include <sys/wait.h>
22 +
23 + #include "../wrappers.h"
24 + #include "../../kselftest_harness.h"
25 +
26 + #define DIR_LEN 64
27 + #define PATH_LEN 128
28 +
29 + static int write_file(const char *path, const char *s)
30 + {
31 + ssize_t n = -1;
32 + int fd;
33 +
34 + fd = open(path, O_WRONLY | O_CLOEXEC);
35 + if (fd >= 0) {
36 + n = write(fd, s, strlen(s));
37 + close(fd);
38 + }
39 + return n == (ssize_t)strlen(s) ? 0 : -1;
40 + }
41 +
42 + static int create_file(const char *path, const char *s)
43 + {
44 + ssize_t n = -1;
45 + int fd;
46 +
47 + fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
48 + if (fd >= 0) {
49 + n = write(fd, s, strlen(s));
50 + close(fd);
51 + }
52 + return n == (ssize_t)strlen(s) ? 0 : -1;
53 + }
54 +
55 + /* the first bytes of the file at @path, "" if it can't be read */
56 + static const char *read_file(const char *path, char *buf, size_t len)
57 + {
58 + ssize_t n = -1;
59 + int fd;
60 +
61 + fd = open(path, O_RDONLY | O_CLOEXEC);
62 + if (fd >= 0) {
63 + n = read(fd, buf, len - 1);
64 + close(fd);
65 + }
66 + buf[n > 0 ? n : 0] = '\0';
67 + return buf;
68 + }
69 +
70 + /* Become root in a new user namespace with a private mount namespace. */
71 + static int enter_userns(void)
72 + {
73 + uid_t uid = getuid();
74 + gid_t gid = getgid();
75 + char map[32];
76 +
77 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
78 + return -1;
79 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
80 + return -1;
81 + snprintf(map, sizeof(map), "0 %d 1", uid);
82 + if (write_file("/proc/self/uid_map", map))
83 + return -1;
84 + snprintf(map, sizeof(map), "0 %d 1", gid);
85 + if (write_file("/proc/self/gid_map", map))
86 + return -1;
87 + if (setgid(0) || setuid(0))
88 + return -1;
89 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
90 + }
91 +
92 + FIXTURE(overmount_ns_file) {
93 + char dir[DIR_LEN];
94 + pid_t child;
95 + };
96 +
97 + FIXTURE_SETUP(overmount_ns_file)
98 + {
99 + self->child = -1;
100 + snprintf(self->dir, sizeof(self->dir), "/tmp/overmount_ns_file.XXXXXX");
101 + ASSERT_NE(mkdtemp(self->dir), NULL);
102 + if (enter_userns()) {
103 + rmdir(self->dir);
104 + SKIP(return, "test requires user namespaces");
105 + }
106 + ASSERT_EQ(mount("tmpfs", self->dir, "tmpfs", 0, NULL), 0);
107 + }
108 +
109 + FIXTURE_TEARDOWN(overmount_ns_file)
110 + {
111 + if (self->child > 0) {
112 + kill(self->child, SIGKILL);
113 + waitpid(self->child, NULL, 0);
114 + }
115 + umount2(self->dir, MNT_DETACH);
116 + rmdir(self->dir);
117 + }
118 +
119 + /*
120 + * A is a shared tmpfs and B its slave with Q, a bind mount of a file, on
121 + * B/file. S is a bind mount of a file with N, a bind mount of a newer mount
122 + * namespace's file, on top of it. S is moved onto A/file. Its copy S' lands
123 + * on B/file below Q, without N. B/file keeps reading Q and once Q is
124 + * unmounted it reads S'.
125 + */
126 + TEST_F(overmount_ns_file, existing_mount_stays_on_top)
127 + {
128 + char a[PATH_LEN], b[PATH_LEN], s[PATH_LEN], p[PATH_LEN], buf[16];
129 + int fd, pfd[2];
130 + char c;
131 +
132 + snprintf(a, sizeof(a), "%s/A", self->dir);
133 + snprintf(b, sizeof(b), "%s/B", self->dir);
134 + snprintf(s, sizeof(s), "%s/s", self->dir);
135 + ASSERT_EQ(mkdir(a, 0755), 0);
136 + ASSERT_EQ(mkdir(b, 0755), 0);
137 + ASSERT_EQ(mkdir(s, 0755), 0);
138 +
139 + /* A shared, B its slave, Q on B/file */
140 + ASSERT_EQ(mount("tmpfs", a, "tmpfs", 0, NULL), 0);
141 + ASSERT_EQ(mount(NULL, a, NULL, MS_SHARED, NULL), 0);
142 + snprintf(p, sizeof(p), "%s/A/file", self->dir);
143 + ASSERT_EQ(create_file(p, "A"), 0);
144 + ASSERT_EQ(mount(a, b, NULL, MS_BIND, NULL), 0);
145 + ASSERT_EQ(mount(NULL, b, NULL, MS_SLAVE, NULL), 0);
146 + snprintf(p, sizeof(p), "%s/Q", self->dir);
147 + ASSERT_EQ(create_file(p, "Q"), 0);
148 + snprintf(b, sizeof(b), "%s/B/file", self->dir);
149 + ASSERT_EQ(mount(p, b, NULL, MS_BIND, NULL), 0);
150 +
151 + /* S on s/f, pinned by a file descriptor before N goes on top */
152 + ASSERT_EQ(mount("tmpfs", s, "tmpfs", 0, NULL), 0);
153 + snprintf(p, sizeof(p), "%s/s/f", self->dir);
154 + ASSERT_EQ(create_file(p, "f"), 0);
155 + snprintf(s, sizeof(s), "%s/s/S", self->dir);
156 + ASSERT_EQ(create_file(s, "S"), 0);
157 + ASSERT_EQ(mount(s, p, NULL, MS_BIND, NULL), 0);
158 + fd = open(p, O_PATH | O_CLOEXEC);
159 + ASSERT_GE(fd, 0);
160 +
161 + /* a newer mount namespace whose file can be bound */
162 + ASSERT_EQ(pipe(pfd), 0);
163 + self->child = fork();
164 + ASSERT_GE(self->child, 0);
165 + if (self->child == 0) {
166 + close(pfd[0]);
167 + if (unshare(CLONE_NEWNS) || write(pfd[1], "r", 1) != 1)
168 + _exit(1);
169 + pause();
170 + _exit(0);
171 + }
172 + close(pfd[1]);
173 + ASSERT_EQ(read(pfd[0], &c, 1), 1);
174 + close(pfd[0]);
175 + snprintf(s, sizeof(s), "/proc/%d/ns/mnt", self->child);
176 + ASSERT_EQ(mount(s, p, NULL, MS_BIND, NULL), 0);
177 +
178 + ASSERT_STREQ(read_file(b, buf, sizeof(buf)), "Q");
179 +
180 + snprintf(a, sizeof(a), "%s/A/file", self->dir);
181 + ASSERT_EQ(sys_move_mount(fd, "", AT_FDCWD, a, MOVE_MOUNT_F_EMPTY_PATH), 0);
182 + close(fd);
183 +
184 + /* Q is still on top of the copy in B and can be unmounted */
185 + EXPECT_STREQ(read_file(b, buf, sizeof(buf)), "Q");
186 + EXPECT_EQ(umount2(b, 0), 0);
187 + EXPECT_STREQ(read_file(b, buf, sizeof(buf)), "S");
188 + }
189 +
190 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/overmount_reparent_test.c mode 100644
@@ -0,0 +1,181 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * propagate_umount() slides a surviving overmount off a mount that is being
4 + * unmounted and unmounts that mount right after. If a file descriptor keeps
5 + * the unmounted mount alive its ->overmount is left pointing at the moved
6 + * mount, which is freed on its own schedule. move_mount(MOVE_MOUNT_BENEATH)
7 + * with such a file descriptor as the target walks ->overmount in
8 + * topmost_overmount() before it checks that the target is still mounted and
9 + * must not step into the freed mount.
10 + */
11 + #define _GNU_SOURCE
12 + #include <errno.h>
13 + #include <fcntl.h>
14 + #include <sched.h>
15 + #include <stdio.h>
16 + #include <stdlib.h>
17 + #include <string.h>
18 + #include <unistd.h>
19 + #include <sys/mount.h>
20 + #include <sys/stat.h>
21 + #include <sys/syscall.h>
22 +
23 + #include "../wrappers.h"
24 + #include "../../kselftest_harness.h"
25 +
26 + #ifndef MOVE_MOUNT_BENEATH
27 + #define MOVE_MOUNT_BENEATH 0x00000200
28 + #endif
29 +
30 + #ifndef FSCONFIG_CMD_CREATE
31 + #define FSCONFIG_CMD_CREATE 6
32 + #endif
33 +
34 + #define DIR_LEN 64
35 + #define PATH_LEN 128
36 +
37 + static int write_file(const char *path, const char *s)
38 + {
39 + ssize_t n = -1;
40 + int fd;
41 +
42 + fd = open(path, O_WRONLY | O_CLOEXEC);
43 + if (fd >= 0) {
44 + n = write(fd, s, strlen(s));
45 + close(fd);
46 + }
47 + return n == (ssize_t)strlen(s) ? 0 : -1;
48 + }
49 +
50 + /* Become root in a new user namespace with a private mount namespace. */
51 + static int enter_userns(void)
52 + {
53 + uid_t uid = getuid();
54 + gid_t gid = getgid();
55 + char map[32];
56 +
57 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
58 + return -1;
59 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
60 + return -1;
61 + snprintf(map, sizeof(map), "0 %d 1", uid);
62 + if (write_file("/proc/self/uid_map", map))
63 + return -1;
64 + snprintf(map, sizeof(map), "0 %d 1", gid);
65 + if (write_file("/proc/self/gid_map", map))
66 + return -1;
67 + if (setgid(0) || setuid(0))
68 + return -1;
69 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
70 + }
71 +
72 + /* A detached tmpfs mount to serve as the source of a move. */
73 + static int detached_tmpfs(void)
74 + {
75 + int sfd, mfd;
76 +
77 + sfd = sys_fsopen("tmpfs", 0);
78 + if (sfd < 0)
79 + return -1;
80 + if (sys_fsconfig(sfd, FSCONFIG_CMD_CREATE, NULL, NULL, 0)) {
81 + close(sfd);
82 + return -1;
83 + }
84 + mfd = sys_fsmount(sfd, 0, 0);
85 + close(sfd);
86 + return mfd;
87 + }
88 +
89 + FIXTURE(overmount_reparent) {
90 + char dir[DIR_LEN];
91 + };
92 +
93 + FIXTURE_SETUP(overmount_reparent)
94 + {
95 + snprintf(self->dir, sizeof(self->dir), "/tmp/overmount_reparent.XXXXXX");
96 + ASSERT_NE(mkdtemp(self->dir), NULL);
97 + if (enter_userns()) {
98 + rmdir(self->dir);
99 + SKIP(return, "test requires user namespaces");
100 + }
101 + }
102 +
103 + FIXTURE_TEARDOWN(overmount_reparent)
104 + {
105 + char p[PATH_LEN];
106 +
107 + snprintf(p, sizeof(p), "%s/b", self->dir);
108 + umount2(p, MNT_DETACH);
109 + snprintf(p, sizeof(p), "%s/a", self->dir);
110 + umount2(p, MNT_DETACH);
111 + }
112 +
113 + /*
114 + * A shared mount base_a is bind-mounted to base_b as its peer. A mount X on
115 + * base_a/mp propagates a copy X_b onto base_b/mp. A file descriptor pins X_b,
116 + * then X_b is made private and an overmount is stacked on its root.
117 + *
118 + * A lazy unmount of X propagates to X_b: X_b is committed to the unmount while
119 + * its overmount survives, so propagate_umount() reparents the overmount onto
120 + * base_b and unmounts X_b, which the file descriptor keeps alive. Unmounting
121 + * the reparented overmount frees it. X_b->overmount now dangles unless
122 + * mnt_change_mountpoint() reset it.
123 + *
124 + * move_mount(MOVE_MOUNT_BENEATH) through the file descriptor makes
125 + * do_lock_mount() follow X_b->overmount in topmost_overmount() before it
126 + * notices that X_b is no longer mounted. With the pointer reset the move fails
127 + * cleanly with ENOENT; otherwise it reads the freed overmount.
128 + */
129 + TEST_F(overmount_reparent, dead_overmount_holder_not_followed)
130 + {
131 + char a[PATH_LEN], b[PATH_LEN], amp[PATH_LEN], bmp[PATH_LEN];
132 + int fd, mfd, ret;
133 +
134 + snprintf(a, sizeof(a), "%s/a", self->dir);
135 + snprintf(b, sizeof(b), "%s/b", self->dir);
136 + ASSERT_EQ(mkdir(a, 0755), 0);
137 + ASSERT_EQ(mkdir(b, 0755), 0);
138 +
139 + ASSERT_EQ(mount("tmpfs", a, "tmpfs", 0, NULL), 0);
140 + ASSERT_EQ(mount(NULL, a, NULL, MS_SHARED, NULL), 0);
141 + ASSERT_EQ(mount(a, b, NULL, MS_BIND, NULL), 0);
142 +
143 + snprintf(amp, sizeof(amp), "%s/a/mp", self->dir);
144 + snprintf(bmp, sizeof(bmp), "%s/b/mp", self->dir);
145 + /* base_a and base_b share one superblock, so this dir is in both. */
146 + ASSERT_EQ(mkdir(amp, 0755), 0);
147 +
148 + /* X on base_a/mp propagates a copy X_b onto base_b/mp. */
149 + ASSERT_EQ(mount("tmpfs", amp, "tmpfs", 0, NULL), 0);
150 +
151 + /* Pin X_b before anything is stacked on top of it. */
152 + fd = open(bmp, O_PATH | O_CLOEXEC);
153 + ASSERT_GE(fd, 0);
154 +
155 + /* Keep the overmount local to X_b. */
156 + ASSERT_EQ(mount(NULL, bmp, NULL, MS_PRIVATE, NULL), 0);
157 +
158 + /* The overmount on X_b's root: X_b->overmount points at it. */
159 + ASSERT_EQ(mount("tmpfs", bmp, "tmpfs", 0, NULL), 0);
160 +
161 + /* Reparents the overmount onto base_b and unmounts X_b. */
162 + ASSERT_EQ(umount2(amp, MNT_DETACH), 0);
163 +
164 + /* Free the reparented overmount. */
165 + ASSERT_EQ(umount2(bmp, MNT_DETACH), 0);
166 + usleep(100000);
167 +
168 + mfd = detached_tmpfs();
169 + ASSERT_GE(mfd, 0);
170 +
171 + ret = sys_move_mount(mfd, "", fd, "",
172 + MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_T_EMPTY_PATH |
173 + MOVE_MOUNT_BENEATH);
174 + EXPECT_EQ(ret, -1);
175 + EXPECT_EQ(errno, ENOENT);
176 +
177 + close(mfd);
178 + close(fd);
179 + }
180 +
181 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/mount_cycle/settings mode 100644
@@ -0,0 +1 @@
1 + timeout=300
added tools/testing/selftests/filesystems/mount_cycle/unmounted_tree_test.c mode 100644
@@ -0,0 +1,484 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * An unmounted mount tree that a file descriptor keeps alive is put and
4 + * vacated behind the root's back, so nothing may walk it under
5 + * namespace_sem: it can't be copied recursively and its propagation can't
6 + * be changed. The mount at its root alone can still be copied and that copy
7 + * is an ordinary mount.
8 + */
9 + #define _GNU_SOURCE
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <sched.h>
13 + #include <stdio.h>
14 + #include <stdlib.h>
15 + #include <string.h>
16 + #include <sys/mount.h>
17 + #include <sys/stat.h>
18 + #include <sys/syscall.h>
19 + #include <sys/wait.h>
20 + #include <unistd.h>
21 + #include <linux/mount.h>
22 +
23 + #include "../wrappers.h"
24 + #include "../../kselftest_harness.h"
25 +
26 + #ifndef __NR_mount_setattr
27 + #define __NR_mount_setattr 442
28 + #endif
29 +
30 + #ifndef __NR_pidfd_open
31 + #define __NR_pidfd_open 434
32 + #endif
33 +
34 + #define PATH_LEN 64
35 +
36 + static inline int sys_mount_setattr(int dfd, const char *path, unsigned int flags,
37 + struct mount_attr *attr, size_t size)
38 + {
39 + return syscall(__NR_mount_setattr, dfd, path, flags, attr, size);
40 + }
41 +
42 + static inline int sys_pidfd_open(pid_t pid, unsigned int flags)
43 + {
44 + return syscall(__NR_pidfd_open, pid, flags);
45 + }
46 +
47 + static int write_file(const char *path, const char *s)
48 + {
49 + ssize_t n = -1;
50 + int fd;
51 +
52 + fd = open(path, O_WRONLY | O_CLOEXEC);
53 + if (fd >= 0) {
54 + n = write(fd, s, strlen(s));
55 + close(fd);
56 + }
57 + return n == (ssize_t)strlen(s) ? 0 : -1;
58 + }
59 +
60 + static int touch(const char *path)
61 + {
62 + int fd;
63 +
64 + fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
65 + if (fd < 0)
66 + return -1;
67 + close(fd);
68 + return 0;
69 + }
70 +
71 + /* Become root in a new user namespace with a private mount namespace. */
72 + static int enter_userns(void)
73 + {
74 + uid_t uid = getuid();
75 + gid_t gid = getgid();
76 + char map[32];
77 +
78 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
79 + return -1;
80 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
81 + return -1;
82 + snprintf(map, sizeof(map), "0 %d 1", uid);
83 + if (write_file("/proc/self/uid_map", map))
84 + return -1;
85 + snprintf(map, sizeof(map), "0 %d 1", gid);
86 + if (write_file("/proc/self/gid_map", map))
87 + return -1;
88 + if (setgid(0) || setuid(0))
89 + return -1;
90 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
91 + }
92 +
93 + /* A private mount namespace of our own, all mounts private. */
94 + static int own_mntns(void)
95 + {
96 + if (unshare(CLONE_NEWNS))
97 + return -1;
98 + return mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL);
99 + }
100 +
101 + FIXTURE(unmounted_tree) {
102 + char dir[PATH_LEN];
103 + };
104 +
105 + FIXTURE_SETUP(unmounted_tree)
106 + {
107 + snprintf(self->dir, sizeof(self->dir), "/tmp/unmounted_tree.XXXXXX");
108 + ASSERT_NE(mkdtemp(self->dir), NULL);
109 + if (enter_userns()) {
110 + rmdir(self->dir);
111 + SKIP(return, "test requires user namespaces");
112 + }
113 + ASSERT_EQ(mount("tmpfs", self->dir, "tmpfs", 0, NULL), 0);
114 + }
115 +
116 + FIXTURE_TEARDOWN(unmounted_tree)
117 + {
118 + umount2(self->dir, MNT_DETACH);
119 + rmdir(self->dir);
120 + }
121 +
122 + /* A recursive copy of the mount @fd refers to must fail with EINVAL. */
123 + static void assert_not_walked(struct __test_metadata *_metadata, int fd,
124 + const char *target)
125 + {
126 + char link[PATH_LEN];
127 + int tfd;
128 +
129 + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
130 + EXPECT_EQ(mount(link, target, NULL, MS_BIND | MS_REC, NULL), -1);
131 + EXPECT_EQ(errno, EINVAL);
132 +
133 + tfd = sys_open_tree(fd, "", AT_EMPTY_PATH | AT_RECURSIVE | OPEN_TREE_CLONE |
134 + OPEN_TREE_CLOEXEC);
135 + EXPECT_LT(tfd, 0);
136 + EXPECT_EQ(errno, EINVAL);
137 + if (tfd >= 0)
138 + close(tfd);
139 + }
140 +
141 + /* The mount @fd refers to can be copied on its own and mounted on @target. */
142 + static void assert_root_copied(struct __test_metadata *_metadata, int fd,
143 + const char *target)
144 + {
145 + int tfd;
146 +
147 + tfd = sys_open_tree(fd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
148 + ASSERT_GE(tfd, 0);
149 + ASSERT_EQ(sys_move_mount(tfd, "", AT_FDCWD, target, MOVE_MOUNT_F_EMPTY_PATH), 0);
150 + close(tfd);
151 + ASSERT_EQ(umount2(target, MNT_DETACH), 0);
152 + }
153 +
154 + /*
155 + * A lazily unmounted bind mount of an nsfs file, kept alive by an fd, can't
156 + * be copied recursively anymore. Copying the mount itself still works and
157 + * so does copying a mounted bind mount of the same file.
158 + */
159 + TEST_F(unmounted_tree, detached_nsfs_bind_not_walked)
160 + {
161 + char x[PATH_LEN], y[PATH_LEN], z[PATH_LEN], link[PATH_LEN];
162 + int fd, tfd;
163 +
164 + snprintf(x, sizeof(x), "%s/x", self->dir);
165 + snprintf(y, sizeof(y), "%s/y", self->dir);
166 + snprintf(z, sizeof(z), "%s/z", self->dir);
167 + ASSERT_EQ(touch(x), 0);
168 + ASSERT_EQ(touch(y), 0);
169 + ASSERT_EQ(touch(z), 0);
170 +
171 + ASSERT_EQ(mount("/proc/self/ns/net", x, NULL, MS_BIND, NULL), 0);
172 + fd = open(x, O_PATH | O_CLOEXEC);
173 + ASSERT_GE(fd, 0);
174 + ASSERT_EQ(umount2(x, MNT_DETACH), 0);
175 +
176 + assert_not_walked(_metadata, fd, y);
177 +
178 + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
179 + ASSERT_EQ(mount(link, y, NULL, MS_BIND, NULL), 0);
180 + ASSERT_EQ(umount2(y, MNT_DETACH), 0);
181 + assert_root_copied(_metadata, fd, y);
182 + /* opening it is fine too */
183 + tfd = sys_open_tree(fd, "", AT_EMPTY_PATH | OPEN_TREE_CLOEXEC);
184 + ASSERT_GE(tfd, 0);
185 + close(tfd);
186 + close(fd);
187 +
188 + ASSERT_EQ(mount("/proc/self/ns/net", y, NULL, MS_BIND, NULL), 0);
189 + ASSERT_EQ(mount(y, z, NULL, MS_BIND | MS_REC, NULL), 0);
190 + tfd = sys_open_tree(AT_FDCWD, y, AT_RECURSIVE | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
191 + ASSERT_GE(tfd, 0);
192 + close(tfd);
193 + }
194 +
195 + /* Bind-mount the pidfd @pidfd on @target the way pidfd_bind_mount does. */
196 + static int bind_pidfd(int pidfd, const char *target)
197 + {
198 + int tfd, ret;
199 +
200 + tfd = sys_open_tree(pidfd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
201 + if (tfd < 0)
202 + return -1;
203 + ret = sys_move_mount(tfd, "", AT_FDCWD, target, MOVE_MOUNT_F_EMPTY_PATH);
204 + close(tfd);
205 + return ret;
206 + }
207 +
208 + /* The same for a bind mount of a pidfd. */
209 + TEST_F(unmounted_tree, detached_pidfs_bind_not_walked)
210 + {
211 + char x[PATH_LEN], y[PATH_LEN];
212 + int pidfd, fd, tfd;
213 +
214 + snprintf(x, sizeof(x), "%s/x", self->dir);
215 + snprintf(y, sizeof(y), "%s/y", self->dir);
216 + ASSERT_EQ(touch(x), 0);
217 + ASSERT_EQ(touch(y), 0);
218 +
219 + pidfd = sys_pidfd_open(getpid(), 0);
220 + ASSERT_GE(pidfd, 0);
221 + ASSERT_EQ(bind_pidfd(pidfd, x), 0);
222 + fd = open(x, O_PATH | O_CLOEXEC);
223 + ASSERT_GE(fd, 0);
224 + ASSERT_EQ(umount2(x, MNT_DETACH), 0);
225 +
226 + assert_not_walked(_metadata, fd, y);
227 + assert_root_copied(_metadata, fd, y);
228 + close(fd);
229 +
230 + ASSERT_EQ(bind_pidfd(pidfd, y), 0);
231 + tfd = sys_open_tree(AT_FDCWD, y, AT_RECURSIVE | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
232 + ASSERT_GE(tfd, 0);
233 + close(tfd);
234 + close(pidfd);
235 + }
236 +
237 + /* What a child in its own mount namespace reports back. */
238 + enum {
239 + CHILD_OK,
240 + CHILD_NS, /* could not set up the mount namespace */
241 + CHILD_MOUNT, /* could not set up the mounts */
242 + CHILD_PIPE, /* the parent went away */
243 + CHILD_WALKED, /* the detached tree was copied recursively */
244 + CHILD_ROOT_REFUSED, /* the mount at its root wasn't copied */
245 + CHILD_STILL_MOUNTED, /* the copy survived the unlink of its mountpoint */
246 + CHILD_ERRNO, /* refused, but not with EINVAL */
247 + };
248 +
249 + static const char *child_reason(int code)
250 + {
251 + static const char *const reasons[] = {
252 + [CHILD_OK] = "ok",
253 + [CHILD_NS] = "could not set up the mount namespace",
254 + [CHILD_MOUNT] = "could not set up the mounts",
255 + [CHILD_PIPE] = "the parent went away",
256 + [CHILD_WALKED] = "the detached tree was copied recursively",
257 + [CHILD_ROOT_REFUSED] = "the mount at its root wasn't copied",
258 + [CHILD_STILL_MOUNTED] = "the copy survived the unlink of its mountpoint",
259 + [CHILD_ERRNO] = "refused, but not with EINVAL",
260 + };
261 +
262 + if (code < 0 || code >= (int)(sizeof(reasons) / sizeof(reasons[0])))
263 + return "child died";
264 + return reasons[code];
265 + }
266 +
267 + struct child_args {
268 + const char *x; /* the nsfs bind mount goes here */
269 + const char *s; /* a file to bind on top of it */
270 + const char *y; /* a target to copy to */
271 + };
272 +
273 + /*
274 + * Run @fn in a child in a mount namespace of its own. Once the child
275 + * reports that its mounts are in place, unlink @victim here, where it is a
276 + * plain file, and let the child carry on. Returns what the child reported.
277 + */
278 + static int run_child(struct __test_metadata *_metadata,
279 + int (*fn)(const struct child_args *, int, int),
280 + const struct child_args *a, const char *victim)
281 + {
282 + int to_parent[2], to_child[2], status;
283 + pid_t pid;
284 + char c;
285 +
286 + if (pipe(to_parent) || pipe(to_child))
287 + return -1;
288 + pid = fork();
289 + if (pid < 0)
290 + return -1;
291 + if (pid == 0) {
292 + close(to_parent[0]);
293 + close(to_child[1]);
294 + _exit(fn(a, to_parent[1], to_child[0]));
295 + }
296 + close(to_parent[1]);
297 + close(to_child[0]);
298 + if (read(to_parent[0], &c, 1) == 1) {
299 + /* not a mountpoint in this namespace, so the file can go */
300 + EXPECT_EQ(unlink(victim), 0);
301 + EXPECT_EQ(write(to_child[1], "", 1), 1);
302 + }
303 + close(to_parent[0]);
304 + close(to_child[1]);
305 + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
306 + return -1;
307 + return WEXITSTATUS(status);
308 + }
309 +
310 + /*
311 + * An nsfs bind mount on @x, an fd on it and a bind mount of @s on top. Once
312 + * the parent has unlinked @x underneath, the first mount is detached and the
313 + * second one, which stayed attached to it, has been vacated. The tree may
314 + * not be walked, the mount at its root may still be copied.
315 + */
316 + static int vacant_child(const struct child_args *a, int to_parent, int from_parent)
317 + {
318 + char link[PATH_LEN];
319 + int fd, tfd;
320 + char c;
321 +
322 + if (own_mntns())
323 + return CHILD_NS;
324 + if (mount("/proc/self/ns/net", a->x, NULL, MS_BIND, NULL))
325 + return CHILD_MOUNT;
326 + fd = open(a->x, O_PATH | O_CLOEXEC);
327 + if (fd < 0 || mount(a->s, a->x, NULL, MS_BIND, NULL))
328 + return CHILD_MOUNT;
329 +
330 + if (write(to_parent, "", 1) != 1 || read(from_parent, &c, 1) != 1)
331 + return CHILD_PIPE;
332 +
333 + tfd = sys_open_tree(fd, "", AT_EMPTY_PATH | AT_RECURSIVE | OPEN_TREE_CLONE |
334 + OPEN_TREE_CLOEXEC);
335 + if (tfd >= 0) {
336 + close(tfd);
337 + return CHILD_WALKED;
338 + }
339 + if (errno != EINVAL)
340 + return CHILD_ERRNO;
341 + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
342 + if (!mount(link, a->y, NULL, MS_BIND | MS_REC, NULL))
343 + return CHILD_WALKED;
344 + if (errno != EINVAL)
345 + return CHILD_ERRNO;
346 +
347 + tfd = sys_open_tree(fd, "", AT_EMPTY_PATH | OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
348 + if (tfd < 0)
349 + return CHILD_ROOT_REFUSED;
350 + close(tfd);
351 + /* the last reference on the detached mount collects the vacant one */
352 + close(fd);
353 + return CHILD_OK;
354 + }
355 +
356 + /*
357 + * unlink() of the child's mountpoint from here, where it is a plain file,
358 + * detaches the child's nsfs bind mount with the mount on top left attached
359 + * to it. The mount on top loses its last reference right there and is
360 + * vacated. The child must not be able to walk that tree.
361 + */
362 + TEST_F(unmounted_tree, vacant_child_not_copied)
363 + {
364 + char x[PATH_LEN], s[PATH_LEN], y[PATH_LEN];
365 + struct child_args a = { .x = x, .s = s, .y = y };
366 + int ret;
367 +
368 + snprintf(x, sizeof(x), "%s/x", self->dir);
369 + snprintf(s, sizeof(s), "%s/s", self->dir);
370 + snprintf(y, sizeof(y), "%s/y", self->dir);
371 + ASSERT_EQ(touch(x), 0);
372 + ASSERT_EQ(touch(s), 0);
373 + ASSERT_EQ(touch(y), 0);
374 +
375 + ret = run_child(_metadata, vacant_child, &a, x);
376 + ASSERT_EQ(ret, CHILD_OK)
377 + TH_LOG("child: %s", child_reason(ret));
378 + }
379 +
380 + /*
381 + * An nsfs bind mount on @x, lazily unmounted but kept alive by an fd, and a
382 + * copy of it on @y. That copy is a mount like any other: once the parent has
383 + * unlinked @y underneath, it is unmounted and its attributes can't be changed
384 + * anymore. A copy that took the flag along is only unhooked, stays in the
385 + * namespace and still takes the change.
386 + */
387 + static int ordinary_copy(const struct child_args *a, int to_parent, int from_parent)
388 + {
389 + struct mount_attr attr = {
390 + .attr_set = MOUNT_ATTR_NOSUID,
391 + };
392 + char link[PATH_LEN];
393 + int fd, fdy;
394 + char c;
395 +
396 + if (own_mntns())
397 + return CHILD_NS;
398 + if (mount("/proc/self/ns/net", a->x, NULL, MS_BIND, NULL))
399 + return CHILD_MOUNT;
400 + fd = open(a->x, O_PATH | O_CLOEXEC);
401 + if (fd < 0 || umount2(a->x, MNT_DETACH))
402 + return CHILD_MOUNT;
403 + snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
404 + if (mount(link, a->y, NULL, MS_BIND, NULL))
405 + return CHILD_MOUNT;
406 + fdy = open(a->y, O_PATH | O_CLOEXEC);
407 + if (fdy < 0)
408 + return CHILD_MOUNT;
409 +
410 + if (write(to_parent, "", 1) != 1 || read(from_parent, &c, 1) != 1)
411 + return CHILD_PIPE;
412 +
413 + if (!sys_mount_setattr(fdy, "", AT_EMPTY_PATH, &attr, sizeof(attr)))
414 + return CHILD_STILL_MOUNTED;
415 + if (errno != EINVAL)
416 + return CHILD_ERRNO;
417 + close(fdy);
418 + close(fd);
419 + return CHILD_OK;
420 + }
421 +
422 + /*
423 + * A copy of a detached nsfs bind mount must not take after its source and
424 + * read as unmounted. unlink() of its mountpoint from here unmounts it like
425 + * any other mount, so the child can't change its attributes anymore.
426 + */
427 + TEST_F(unmounted_tree, copy_of_detached_bind_is_ordinary)
428 + {
429 + char x[PATH_LEN], y[PATH_LEN];
430 + struct child_args a = { .x = x, .y = y };
431 + int ret;
432 +
433 + snprintf(x, sizeof(x), "%s/x", self->dir);
434 + snprintf(y, sizeof(y), "%s/y", self->dir);
435 + ASSERT_EQ(touch(x), 0);
436 + ASSERT_EQ(touch(y), 0);
437 +
438 + ret = run_child(_metadata, ordinary_copy, &a, y);
439 + ASSERT_EQ(ret, CHILD_OK)
440 + TH_LOG("child: %s", child_reason(ret));
441 + }
442 +
443 + /*
444 + * mount_setattr() may change the propagation of a detached tree while that
445 + * tree is still the root of an anonymous mount namespace, but not once the
446 + * tree has been dissolved and only a second fd keeps its root alive.
447 + */
448 + TEST_F(unmounted_tree, detached_tree_setattr_refused)
449 + {
450 + struct mount_attr attr = {
451 + .propagation = MS_SHARED,
452 + };
453 + char a[PATH_LEN], b[PATH_LEN];
454 + int tfd, fd;
455 +
456 + snprintf(a, sizeof(a), "%s/a", self->dir);
457 + snprintf(b, sizeof(b), "%s/a/b", self->dir);
458 + ASSERT_EQ(mkdir(a, 0755), 0);
459 + ASSERT_EQ(mount("tmpfs", a, "tmpfs", 0, NULL), 0);
460 + ASSERT_EQ(mkdir(b, 0755), 0);
461 + ASSERT_EQ(mount("tmpfs", b, "tmpfs", 0, NULL), 0);
462 +
463 + tfd = sys_open_tree(AT_FDCWD, self->dir, AT_RECURSIVE | OPEN_TREE_CLONE |
464 + OPEN_TREE_CLOEXEC);
465 + ASSERT_GE(tfd, 0);
466 + ASSERT_EQ(sys_mount_setattr(tfd, "", AT_EMPTY_PATH | AT_RECURSIVE, &attr, sizeof(attr)), 0);
467 + attr.propagation = MS_PRIVATE;
468 + ASSERT_EQ(sys_mount_setattr(tfd, "", AT_EMPTY_PATH | AT_RECURSIVE, &attr, sizeof(attr)), 0);
469 +
470 + /* a second reference on the root, then dissolve the tree */
471 + fd = sys_open_tree(tfd, "", AT_EMPTY_PATH | OPEN_TREE_CLOEXEC);
472 + ASSERT_GE(fd, 0);
473 + close(tfd);
474 +
475 + attr.propagation = MS_SHARED;
476 + ASSERT_EQ(sys_mount_setattr(fd, "", AT_EMPTY_PATH | AT_RECURSIVE, &attr, sizeof(attr)), -1);
477 + ASSERT_EQ(errno, EINVAL);
478 + attr.propagation = MS_PRIVATE;
479 + ASSERT_EQ(sys_mount_setattr(fd, "", AT_EMPTY_PATH, &attr, sizeof(attr)), -1);
480 + ASSERT_EQ(errno, EINVAL);
481 + close(fd);
482 + }
483 +
484 + TEST_HARNESS_MAIN
modified tools/testing/selftests/filesystems/open_tree_ns/.gitignore
@@ -1 +1,2 @@
1 1 open_tree_ns_test
2 + open_tree_ns_covered_test
modified tools/testing/selftests/filesystems/open_tree_ns/Makefile
@@ -1,5 +1,5 @@
1 1 # SPDX-License-Identifier: GPL-2.0
2 - TEST_GEN_PROGS := open_tree_ns_test
2 + TEST_GEN_PROGS := open_tree_ns_test open_tree_ns_covered_test
3 3
4 4 CFLAGS += -Wall -O0 -g $(KHDR_INCLUDES) $(TOOLS_INCLUDES)
5 5 LDLIBS := -lcap
added tools/testing/selftests/filesystems/open_tree_ns/open_tree_ns_covered_test.c mode 100644
@@ -0,0 +1,195 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * open_tree(OPEN_TREE_NAMESPACE) by a caller that isn't privileged over the
4 + * mount namespace it copies from must not reveal what the mounts below the
5 + * copied mount cover. Without AT_RECURSIVE the copy is refused when there's
6 + * anything mounted below the requested directory. With AT_RECURSIVE
7 + * unbindable mounts are copied as well.
8 + */
9 + #define _GNU_SOURCE
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <sched.h>
13 + #include <stdio.h>
14 + #include <stdlib.h>
15 + #include <string.h>
16 + #include <unistd.h>
17 + #include <sys/mount.h>
18 + #include <sys/stat.h>
19 + #include <sys/wait.h>
20 +
21 + #include "../wrappers.h"
22 + #include "../../kselftest_harness.h"
23 +
24 + #ifndef OPEN_TREE_NAMESPACE
25 + #define OPEN_TREE_NAMESPACE (1 << 1)
26 + #endif
27 +
28 + #define DIR_LEN 64
29 + #define PATH_LEN 128
30 +
31 + /* Child exit codes. */
32 + enum {
33 + CHILD_OK,
34 + CHILD_USERNS, /* could not create the child user namespace */
35 + CHILD_NONREC_ALLOWED, /* the non-recursive copy was not refused */
36 + CHILD_NONREC_ERRNO, /* it was refused with the wrong error */
37 + CHILD_REC_REFUSED, /* the recursive copy failed */
38 + CHILD_SETNS, /* could not enter the new mount namespace */
39 + CHILD_NO_COVER, /* the covering mount is missing in the copy */
40 + CHILD_REVEALED, /* the covered file is visible in the copy */
41 + };
42 +
43 + static int write_file(const char *path, const char *s)
44 + {
45 + ssize_t n = -1;
46 + int fd;
47 +
48 + fd = open(path, O_WRONLY | O_CLOEXEC);
49 + if (fd >= 0) {
50 + n = write(fd, s, strlen(s));
51 + close(fd);
52 + }
53 + return n == (ssize_t)strlen(s) ? 0 : -1;
54 + }
55 +
56 + static int create_file(const char *path, const char *s)
57 + {
58 + ssize_t n = -1;
59 + int fd;
60 +
61 + fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
62 + if (fd >= 0) {
63 + n = write(fd, s, strlen(s));
64 + close(fd);
65 + }
66 + return n == (ssize_t)strlen(s) ? 0 : -1;
67 + }
68 +
69 + /* Become root in a new user namespace, the uid @uid is mapped to 0. */
70 + static int enter_userns(uid_t uid, gid_t gid)
71 + {
72 + char map[32];
73 +
74 + if (unshare(CLONE_NEWUSER))
75 + return -1;
76 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
77 + return -1;
78 + snprintf(map, sizeof(map), "0 %d 1", uid);
79 + if (write_file("/proc/self/uid_map", map))
80 + return -1;
81 + snprintf(map, sizeof(map), "0 %d 1", gid);
82 + if (write_file("/proc/self/gid_map", map))
83 + return -1;
84 + return setgid(0) || setuid(0) ? -1 : 0;
85 + }
86 +
87 + FIXTURE(open_tree_ns_covered) {
88 + char dir[DIR_LEN];
89 + char cover[PATH_LEN];
90 + };
91 +
92 + FIXTURE_VARIANT(open_tree_ns_covered) {
93 + int propagation;
94 + };
95 +
96 + FIXTURE_VARIANT_ADD(open_tree_ns_covered, private_cover) {
97 + .propagation = MS_PRIVATE,
98 + };
99 +
100 + FIXTURE_VARIANT_ADD(open_tree_ns_covered, unbindable_cover) {
101 + .propagation = MS_UNBINDABLE,
102 + };
103 +
104 + /*
105 + * Root in a user namespace owns a private mount namespace with a tmpfs
106 + * on @dir and a second tmpfs covering @dir/covered/under.txt.
107 + */
108 + FIXTURE_SETUP(open_tree_ns_covered)
109 + {
110 + char p[PATH_LEN];
111 + int fd;
112 +
113 + snprintf(self->dir, sizeof(self->dir), "/tmp/open_tree_ns_covered.XXXXXX");
114 + ASSERT_NE(mkdtemp(self->dir), NULL);
115 + if (enter_userns(getuid(), getgid()) || unshare(CLONE_NEWNS)) {
116 + rmdir(self->dir);
117 + SKIP(return, "test requires user namespaces");
118 + }
119 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
120 + ASSERT_EQ(mount("tmpfs", self->dir, "tmpfs", 0, NULL), 0);
121 +
122 + /* the flag has to exist before its rules can be checked */
123 + fd = sys_open_tree(AT_FDCWD, self->dir,
124 + OPEN_TREE_NAMESPACE | OPEN_TREE_CLOEXEC);
125 + if (fd < 0 && (errno == EINVAL || errno == ENOSYS)) {
126 + umount2(self->dir, MNT_DETACH);
127 + rmdir(self->dir);
128 + SKIP(return, "OPEN_TREE_NAMESPACE not supported");
129 + }
130 + ASSERT_GE(fd, 0);
131 + close(fd);
132 +
133 + snprintf(self->cover, sizeof(self->cover), "%s/covered", self->dir);
134 + ASSERT_EQ(mkdir(self->cover, 0755), 0);
135 + snprintf(p, sizeof(p), "%s/covered/under.txt", self->dir);
136 + ASSERT_EQ(create_file(p, "hidden"), 0);
137 + ASSERT_EQ(mount("tmpfs", self->cover, "tmpfs", 0, NULL), 0);
138 + ASSERT_EQ(mount(NULL, self->cover, NULL, variant->propagation, NULL), 0);
139 + }
140 +
141 + FIXTURE_TEARDOWN(open_tree_ns_covered)
142 + {
143 + umount2(self->dir, MNT_DETACH);
144 + rmdir(self->dir);
145 + }
146 +
147 + /* A caller in a new user namespace that doesn't own the mount namespace. */
148 + static int foreign_child(const char *dir)
149 + {
150 + struct stat st;
151 + int fd;
152 +
153 + if (enter_userns(0, 0))
154 + return CHILD_USERNS;
155 +
156 + fd = sys_open_tree(AT_FDCWD, dir, OPEN_TREE_NAMESPACE | OPEN_TREE_CLOEXEC);
157 + if (fd >= 0)
158 + return CHILD_NONREC_ALLOWED;
159 + if (errno != EINVAL)
160 + return CHILD_NONREC_ERRNO;
161 +
162 + fd = sys_open_tree(AT_FDCWD, dir,
163 + OPEN_TREE_NAMESPACE | OPEN_TREE_CLOEXEC | AT_RECURSIVE);
164 + if (fd < 0)
165 + return CHILD_REC_REFUSED;
166 + if (setns(fd, CLONE_NEWNS))
167 + return CHILD_SETNS;
168 + if (stat("/covered", &st))
169 + return CHILD_NO_COVER;
170 + if (!access("/covered/under.txt", F_OK) || errno != ENOENT)
171 + return CHILD_REVEALED;
172 + return CHILD_OK;
173 + }
174 +
175 + TEST_F(open_tree_ns_covered, foreign_user_namespace)
176 + {
177 + int status, fd;
178 + pid_t pid;
179 +
180 + pid = fork();
181 + ASSERT_GE(pid, 0);
182 + if (pid == 0)
183 + _exit(foreign_child(self->dir));
184 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
185 + ASSERT_TRUE(WIFEXITED(status));
186 + ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
187 +
188 + /* the owner of the mount namespace keeps bind mount semantics */
189 + fd = sys_open_tree(AT_FDCWD, self->dir,
190 + OPEN_TREE_NAMESPACE | OPEN_TREE_CLOEXEC);
191 + ASSERT_GE(fd, 0);
192 + close(fd);
193 + }
194 +
195 + TEST_HARNESS_MAIN
modified tools/testing/selftests/filesystems/overlayfs/.gitignore
@@ -2,3 +2,4 @@
2 2 dev_in_maps
3 3 set_layers_via_fds
4 4 idmapped_mounts
5 + automount_in_layer
modified tools/testing/selftests/filesystems/overlayfs/Makefile
@@ -9,6 +9,7 @@ LOCAL_HDRS += ../wrappers.h log.h
9 9 TEST_GEN_PROGS := dev_in_maps
10 10 TEST_GEN_PROGS += set_layers_via_fds
11 11 TEST_GEN_PROGS += idmapped_mounts
12 + TEST_GEN_PROGS += automount_in_layer
12 13
13 14 include ../../lib.mk
14 15
added tools/testing/selftests/filesystems/overlayfs/automount_in_layer.c mode 100644
@@ -0,0 +1,174 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A layer of an overlay is a private clone of the mount it was given and
4 + * belongs to no mount namespace. fanotify hands out descriptors on it. An
5 + * automount triggered through one has no namespace to go into: the open has
6 + * to fail, not oops with namespace_sem held.
7 + */
8 + #define _GNU_SOURCE
9 + #include <dirent.h>
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <poll.h>
13 + #include <sched.h>
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <unistd.h>
18 + #include <linux/magic.h>
19 + #include <sys/fanotify.h>
20 + #include <sys/mount.h>
21 + #include <sys/stat.h>
22 + #include <sys/vfs.h>
23 +
24 + #include "../../kselftest_harness.h"
25 +
26 + #define DIR_LEN 64
27 + #define PATH_LEN 192
28 +
29 + static bool have_fs(const char *name)
30 + {
31 + char line[128];
32 + bool found = false;
33 + FILE *f;
34 +
35 + f = fopen("/proc/filesystems", "re");
36 + if (!f)
37 + return false;
38 + while (fgets(line, sizeof(line), f)) {
39 + char *nl = strchr(line, '\n');
40 + char *tab = strchr(line, '\t');
41 +
42 + if (nl)
43 + *nl = 0;
44 + if (tab && !strcmp(tab + 1, name))
45 + found = true;
46 + }
47 + fclose(f);
48 + return found;
49 + }
50 +
51 + static int mnt_id_of(int fd)
52 + {
53 + char path[64], buf[4096], *p;
54 + ssize_t n;
55 + int info;
56 +
57 + snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
58 + info = open(path, O_RDONLY | O_CLOEXEC);
59 + if (info < 0)
60 + return -1;
61 + n = read(info, buf, sizeof(buf) - 1);
62 + close(info);
63 + if (n <= 0)
64 + return -1;
65 + buf[n] = 0;
66 + p = strstr(buf, "mnt_id:");
67 + return p ? atoi(p + strlen("mnt_id:")) : -1;
68 + }
69 +
70 + static bool on_debugfs(int fd)
71 + {
72 + struct statfs sf;
73 +
74 + return !fstatfs(fd, &sf) && sf.f_type == DEBUGFS_MAGIC;
75 + }
76 +
77 + FIXTURE(layer) {
78 + char base[DIR_LEN];
79 + int fan;
80 + int evfd; /* on the layer clone of the lower debugfs */
81 + };
82 +
83 + FIXTURE_SETUP(layer)
84 + {
85 + char lower[PATH_LEN], other[PATH_LEN], ovl[PATH_LEN], opts[2 * PATH_LEN + 16];
86 + struct fanotify_event_metadata *ev;
87 + struct pollfd pfd;
88 + char buf[4096];
89 + int lfd, lower_id;
90 + ssize_t n;
91 + DIR *d;
92 +
93 + self->fan = -1;
94 + self->evfd = -1;
95 + if (geteuid())
96 + SKIP(return, "test requires root");
97 + if (!have_fs("debugfs") || !have_fs("tracefs"))
98 + SKIP(return, "test requires debugfs with the tracefs automount");
99 + if (!have_fs("overlay"))
100 + SKIP(return, "test requires overlayfs");
101 +
102 + snprintf(self->base, sizeof(self->base), "/tmp/layer.XXXXXX");
103 + ASSERT_NE(mkdtemp(self->base), NULL);
104 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
105 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
106 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, "mode=0755"), 0);
107 + snprintf(lower, sizeof(lower), "%s/lower", self->base);
108 + snprintf(other, sizeof(other), "%s/other", self->base);
109 + snprintf(ovl, sizeof(ovl), "%s/ovl", self->base);
110 + ASSERT_EQ(mkdir(lower, 0755), 0);
111 + ASSERT_EQ(mkdir(other, 0755), 0);
112 + ASSERT_EQ(mkdir(ovl, 0755), 0);
113 + ASSERT_EQ(mount("debugfs", lower, "debugfs", 0, NULL), 0);
114 + snprintf(opts, sizeof(opts), "lowerdir=%s:%s", lower, other);
115 + ASSERT_EQ(mount("overlay", ovl, "overlay", MS_RDONLY, opts), 0);
116 +
117 + self->fan = fanotify_init(FAN_CLASS_NOTIF | FAN_NONBLOCK | FAN_CLOEXEC,
118 + O_RDONLY | O_CLOEXEC);
119 + ASSERT_GE(self->fan, 0);
120 + ASSERT_EQ(fanotify_mark(self->fan, FAN_MARK_ADD | FAN_MARK_FILESYSTEM,
121 + FAN_OPEN | FAN_ONDIR, AT_FDCWD, lower), 0);
122 + lfd = open(lower, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
123 + ASSERT_GE(lfd, 0);
124 + lower_id = mnt_id_of(lfd);
125 + close(lfd);
126 +
127 + /* the overlay opens its lower directory through the layer clone */
128 + d = opendir(ovl);
129 + ASSERT_NE(d, NULL);
130 + closedir(d);
131 + pfd.fd = self->fan;
132 + pfd.events = POLLIN;
133 + ASSERT_EQ(poll(&pfd, 1, 5000), 1);
134 + n = read(self->fan, buf, sizeof(buf));
135 + ASSERT_GT(n, 0);
136 + for (ev = (void *)buf; FAN_EVENT_OK(ev, n); ev = FAN_EVENT_NEXT(ev, n)) {
137 + if (ev->fd < 0)
138 + continue;
139 + if (self->evfd < 0 && on_debugfs(ev->fd) &&
140 + mnt_id_of(ev->fd) != lower_id)
141 + self->evfd = ev->fd;
142 + else
143 + close(ev->fd);
144 + }
145 + ASSERT_GE(self->evfd, 0)
146 + TH_LOG("no event on the layer clone");
147 + }
148 +
149 + FIXTURE_TEARDOWN(layer)
150 + {
151 + if (self->evfd >= 0)
152 + close(self->evfd);
153 + if (self->fan >= 0)
154 + close(self->fan);
155 + umount2(self->base, MNT_DETACH);
156 + rmdir(self->base);
157 + }
158 +
159 + TEST_F(layer, automount_below_the_clone_is_refused)
160 + {
161 + struct stat st;
162 + int fd;
163 +
164 + /* the automount point is there */
165 + ASSERT_EQ(fstatat(self->evfd, "tracing", &st, AT_NO_AUTOMOUNT), 0);
166 + /* the clone is in no namespace, so the automount has nowhere to go */
167 + fd = openat(self->evfd, "tracing", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
168 + EXPECT_LT(fd, 0);
169 + EXPECT_EQ(errno, EINVAL);
170 + if (fd >= 0)
171 + close(fd);
172 + }
173 +
174 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/readdir_hold.h mode 100644
@@ -0,0 +1,224 @@
1 + /* SPDX-License-Identifier: GPL-2.0 */
2 + /*
3 + * Hold a readdir of a directory in the page fault of its buffer and see
4 + * whether a create and a lookup in that directory wait for it. For a
5 + * directory that is permanently empty they must not.
6 + */
7 + #ifndef __SELFTESTS_READDIR_HOLD_H
8 + #define __SELFTESTS_READDIR_HOLD_H
9 +
10 + #include <errno.h>
11 + #include <fcntl.h>
12 + #include <poll.h>
13 + #include <pthread.h>
14 + #include <stdbool.h>
15 + #include <stdio.h>
16 + #include <stdlib.h>
17 + #include <string.h>
18 + #include <unistd.h>
19 + #include <linux/userfaultfd.h>
20 + #include <sys/ioctl.h>
21 + #include <sys/mman.h>
22 + #include <sys/stat.h>
23 + #include <sys/syscall.h>
24 +
25 + #define HOLD_FAULT_MS 5000 /* for the reader to reach the fault */
26 + #define HOLD_QUEUE_MS 2000 /* for the create to queue up behind it */
27 + #define HOLD_LOOKUP_MS 5000 /* for the lookup to come back */
28 +
29 + struct readdir_hold {
30 + int uffd;
31 + int taskdir; /* /proc/self/task, from before any namespace change */
32 + long page_size;
33 + char *page; /* faults until released */
34 + int dfd;
35 + pid_t creator_tid;
36 + int created;
37 + int done[2]; /* the finder writes a byte when it is back */
38 + };
39 +
40 + /*
41 + * The fault happens in the kernel, so the userfaultfd needs CAP_SYS_PTRACE
42 + * in the initial user namespace or vm.unprivileged_userfaultfd. Call this
43 + * before entering a user namespace.
44 + */
45 + static inline int readdir_hold_init(struct readdir_hold *h)
46 + {
47 + struct uffdio_api api = { .api = UFFD_API };
48 +
49 + h->page = MAP_FAILED;
50 + h->page_size = sysconf(_SC_PAGESIZE);
51 + h->taskdir = open("/proc/self/task", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
52 + h->uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
53 + if (h->uffd < 0 || h->taskdir < 0 || ioctl(h->uffd, UFFDIO_API, &api)) {
54 + if (h->uffd >= 0)
55 + close(h->uffd);
56 + if (h->taskdir >= 0)
57 + close(h->taskdir);
58 + h->uffd = h->taskdir = -1;
59 + return -1;
60 + }
61 + return 0;
62 + }
63 +
64 + static inline void readdir_hold_destroy(struct readdir_hold *h)
65 + {
66 + if (h->uffd >= 0)
67 + close(h->uffd);
68 + if (h->taskdir >= 0)
69 + close(h->taskdir);
70 + h->uffd = h->taskdir = -1;
71 + }
72 +
73 + static inline void *readdir_hold_reader(void *arg)
74 + {
75 + struct readdir_hold *h = arg;
76 +
77 + /* the first byte written to the buffer faults until released */
78 + syscall(__NR_getdents64, h->dfd, h->page, h->page_size);
79 + return NULL;
80 + }
81 +
82 + static inline void *readdir_hold_creator(void *arg)
83 + {
84 + struct readdir_hold *h = arg;
85 +
86 + h->creator_tid = syscall(__NR_gettid);
87 + /* takes the directory lock exclusive before it fails */
88 + mkdirat(h->dfd, "x", 0755);
89 + __atomic_store_n(&h->created, 1, __ATOMIC_RELEASE);
90 + return NULL;
91 + }
92 +
93 + static inline void *readdir_hold_finder(void *arg)
94 + {
95 + struct readdir_hold *h = arg;
96 + int fd;
97 +
98 + /* a lookup that misses the dcache takes the lock shared */
99 + fd = openat(h->dfd, "no_such_name", O_RDONLY | O_CLOEXEC);
100 + if (fd >= 0)
101 + close(fd);
102 + if (write(h->done[1], "x", 1) != 1)
103 + perror("readdir_hold: finder");
104 + return NULL;
105 + }
106 +
107 + /* the creator is back, or waits in the kernel for the lock */
108 + static inline bool readdir_hold_creator_settled(struct readdir_hold *h)
109 + {
110 + char path[32], buf[256], *p;
111 + ssize_t n;
112 + int fd;
113 +
114 + if (__atomic_load_n(&h->created, __ATOMIC_ACQUIRE))
115 + return true;
116 + if (!h->creator_tid)
117 + return false;
118 + snprintf(path, sizeof(path), "%d/stat", h->creator_tid);
119 + fd = openat(h->taskdir, path, O_RDONLY | O_CLOEXEC);
120 + if (fd < 0)
121 + return false;
122 + n = read(fd, buf, sizeof(buf) - 1);
123 + close(fd);
124 + if (n <= 0)
125 + return false;
126 + buf[n] = 0;
127 + /* "pid (comm) state ..." */
128 + p = strrchr(buf, ')');
129 + return p && p[1] == ' ' && p[2] == 'D';
130 + }
131 +
132 + static inline bool readdir_hold_faulted(struct readdir_hold *h)
133 + {
134 + struct pollfd pfd = { .fd = h->uffd, .events = POLLIN };
135 + struct uffd_msg msg;
136 +
137 + if (poll(&pfd, 1, HOLD_FAULT_MS) != 1)
138 + return false;
139 + if (read(h->uffd, &msg, sizeof(msg)) != sizeof(msg))
140 + return false;
141 + return msg.event == UFFD_EVENT_PAGEFAULT;
142 + }
143 +
144 + /* let the reader go on */
145 + static inline void readdir_hold_release(struct readdir_hold *h)
146 + {
147 + struct uffdio_copy cp = {
148 + .dst = (unsigned long)h->page,
149 + .len = h->page_size,
150 + };
151 + void *zero;
152 +
153 + zero = calloc(1, h->page_size);
154 + if (!zero)
155 + return;
156 + cp.src = (unsigned long)zero;
157 + if (ioctl(h->uffd, UFFDIO_COPY, &cp) && errno != EEXIST)
158 + perror("readdir_hold: UFFDIO_COPY");
159 + free(zero);
160 + }
161 +
162 + /*
163 + * A readdir of @dfd that sticks in the fault of its buffer, then a create
164 + * and a lookup in @dfd. Whether the lookup came back while the readdir was
165 + * still stuck goes to @stalled. Returns -1 when that could not be found
166 + * out.
167 + */
168 + static inline int readdir_hold_check(struct readdir_hold *h, int dfd,
169 + bool *stalled)
170 + {
171 + pthread_t reader, creator, finder;
172 + struct uffdio_register reg = {};
173 + struct pollfd pfd;
174 + int ret = -1, i;
175 +
176 + h->dfd = dfd;
177 + h->created = 0;
178 + h->creator_tid = 0;
179 + h->page = mmap(NULL, h->page_size, PROT_READ | PROT_WRITE,
180 + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
181 + if (h->page == MAP_FAILED)
182 + return -1;
183 + reg.range.start = (unsigned long)h->page;
184 + reg.range.len = h->page_size;
185 + reg.mode = UFFDIO_REGISTER_MODE_MISSING;
186 + if (ioctl(h->uffd, UFFDIO_REGISTER, &reg) || pipe2(h->done, O_CLOEXEC))
187 + goto out_page;
188 +
189 + if (pthread_create(&reader, NULL, readdir_hold_reader, h))
190 + goto out_pipe;
191 + if (!readdir_hold_faulted(h))
192 + goto out_reader;
193 + if (pthread_create(&creator, NULL, readdir_hold_creator, h))
194 + goto out_reader;
195 + for (i = 0; i < HOLD_QUEUE_MS / 10 && !readdir_hold_creator_settled(h); i++)
196 + usleep(10000);
197 + if (pthread_create(&finder, NULL, readdir_hold_finder, h))
198 + goto out_creator;
199 +
200 + pfd.fd = h->done[0];
201 + pfd.events = POLLIN;
202 + *stalled = poll(&pfd, 1, HOLD_LOOKUP_MS) != 1;
203 + ret = 0;
204 +
205 + readdir_hold_release(h);
206 + pthread_join(finder, NULL);
207 + out_creator:
208 + if (ret)
209 + readdir_hold_release(h);
210 + pthread_join(creator, NULL);
211 + out_reader:
212 + if (ret)
213 + readdir_hold_release(h);
214 + pthread_join(reader, NULL);
215 + out_pipe:
216 + close(h->done[0]);
217 + close(h->done[1]);
218 + out_page:
219 + munmap(h->page, h->page_size);
220 + h->page = MAP_FAILED;
221 + return ret;
222 + }
223 +
224 + #endif /* __SELFTESTS_READDIR_HOLD_H */
added tools/testing/selftests/filesystems/rw_hint_test.c mode 100644
@@ -0,0 +1,129 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * F_SET_RW_HINT is refused on an immutable inode. Nothing is ever written
4 + * to it and it may be shared with everybody, like a namespace file or the
5 + * root of an empty mount namespace.
6 + */
7 + #define _GNU_SOURCE
8 + #include <errno.h>
9 + #include <fcntl.h>
10 + #include <sched.h>
11 + #include <stdint.h>
12 + #include <stdio.h>
13 + #include <stdlib.h>
14 + #include <string.h>
15 + #include <unistd.h>
16 + #include <sys/ioctl.h>
17 + #include <sys/stat.h>
18 + #include <sys/wait.h>
19 +
20 + #include "../kselftest_harness.h"
21 +
22 + /* <linux/fs.h> and <linux/fcntl.h> don't mix with the libc headers */
23 + #ifndef FS_IOC_GETFLAGS
24 + #define FS_IOC_GETFLAGS _IOR('f', 1, long)
25 + #define FS_IOC_SETFLAGS _IOW('f', 2, long)
26 + #endif
27 + #ifndef FS_IMMUTABLE_FL
28 + #define FS_IMMUTABLE_FL 0x00000010
29 + #endif
30 + #ifndef F_LINUX_SPECIFIC_BASE
31 + #define F_LINUX_SPECIFIC_BASE 1024
32 + #endif
33 + #ifndef F_GET_RW_HINT
34 + #define F_GET_RW_HINT (F_LINUX_SPECIFIC_BASE + 11)
35 + #define F_SET_RW_HINT (F_LINUX_SPECIFIC_BASE + 12)
36 + #endif
37 + #ifndef RWH_WRITE_LIFE_SHORT
38 + #define RWH_WRITE_LIFE_SHORT 2
39 + #endif
40 + #ifndef UNSHARE_EMPTY_MNTNS
41 + #define UNSHARE_EMPTY_MNTNS 0x00100000
42 + #endif
43 +
44 + static int set_hint(int fd, uint64_t hint)
45 + {
46 + return fcntl(fd, F_SET_RW_HINT, &hint);
47 + }
48 +
49 + static long get_hint(int fd)
50 + {
51 + uint64_t hint;
52 +
53 + if (fcntl(fd, F_GET_RW_HINT, &hint))
54 + return -1;
55 + return hint;
56 + }
57 +
58 + TEST(immutable_file)
59 + {
60 + char path[] = "/tmp/rw_hint.XXXXXX";
61 + int fd, flags;
62 +
63 + if (geteuid())
64 + SKIP(return, "test requires root");
65 +
66 + fd = mkstemp(path);
67 + ASSERT_GE(fd, 0);
68 + unlink(path);
69 + ASSERT_EQ(set_hint(fd, RWH_WRITE_LIFE_SHORT), 0);
70 + EXPECT_EQ(get_hint(fd), RWH_WRITE_LIFE_SHORT);
71 +
72 + if (ioctl(fd, FS_IOC_GETFLAGS, &flags)) {
73 + close(fd);
74 + SKIP(return, "no file attributes on this filesystem");
75 + }
76 + flags |= FS_IMMUTABLE_FL;
77 + ASSERT_EQ(ioctl(fd, FS_IOC_SETFLAGS, &flags), 0);
78 + EXPECT_EQ(set_hint(fd, RWH_WRITE_LIFE_SHORT), -1);
79 + EXPECT_EQ(errno, EPERM);
80 + flags &= ~FS_IMMUTABLE_FL;
81 + ASSERT_EQ(ioctl(fd, FS_IOC_SETFLAGS, &flags), 0);
82 + EXPECT_EQ(set_hint(fd, RWH_WRITE_LIFE_SHORT), 0);
83 + close(fd);
84 + }
85 +
86 + TEST(namespace_file)
87 + {
88 + int fd;
89 +
90 + if (geteuid())
91 + SKIP(return, "test requires root");
92 +
93 + fd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
94 + ASSERT_GE(fd, 0);
95 + EXPECT_EQ(set_hint(fd, RWH_WRITE_LIFE_SHORT), -1);
96 + EXPECT_EQ(errno, EPERM);
97 + close(fd);
98 + }
99 +
100 + TEST(empty_mntns_root)
101 + {
102 + int status;
103 + pid_t pid;
104 +
105 + if (geteuid())
106 + SKIP(return, "test requires root");
107 +
108 + pid = fork();
109 + ASSERT_GE(pid, 0);
110 + if (pid == 0) {
111 + int fd;
112 +
113 + if (unshare(UNSHARE_EMPTY_MNTNS))
114 + _exit(errno == EINVAL ? 100 : 1);
115 + fd = open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
116 + if (fd < 0)
117 + _exit(2);
118 + if (set_hint(fd, RWH_WRITE_LIFE_SHORT) == 0)
119 + _exit(3);
120 + _exit(errno == EPERM ? 0 : 4);
121 + }
122 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
123 + ASSERT_TRUE(WIFEXITED(status));
124 + if (WEXITSTATUS(status) == 100)
125 + SKIP(return, "UNSHARE_EMPTY_MNTNS not supported");
126 + EXPECT_EQ(WEXITSTATUS(status), 0);
127 + }
128 +
129 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/umount_propagation/Makefile mode 100644
@@ -0,0 +1,6 @@
1 + # SPDX-License-Identifier: GPL-2.0
2 + TEST_GEN_PROGS := umount_propagation_test shrink_submounts_test locked_mount_test
3 +
4 + CFLAGS += -Wall -O2 -g $(KHDR_INCLUDES)
5 +
6 + include ../../lib.mk
added tools/testing/selftests/filesystems/umount_propagation/locked_mount_test.c mode 100644
@@ -0,0 +1,554 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * MNT_LOCKED keeps the owner of a user namespace from revealing what a
4 + * mount covers. The lock has to be set on the copy in that namespace and
5 + * only there, it has to survive the expiry of a mount placed beneath the
6 + * locked one, and it has to survive the propagated umount of such a copy.
7 + */
8 + #define _GNU_SOURCE
9 + #include <errno.h>
10 + #include <fcntl.h>
11 + #include <sched.h>
12 + #include <stdbool.h>
13 + #include <signal.h>
14 + #include <stdio.h>
15 + #include <stdlib.h>
16 + #include <string.h>
17 + #include <unistd.h>
18 + #include <sys/mount.h>
19 + #include <sys/prctl.h>
20 + #include <sys/stat.h>
21 + #include <sys/syscall.h>
22 + #include <sys/wait.h>
23 +
24 + #include "../../kselftest_harness.h"
25 +
26 + #ifndef MOVE_MOUNT_F_EMPTY_PATH
27 + #define MOVE_MOUNT_F_EMPTY_PATH 0x00000004
28 + #endif
29 + #ifndef MOVE_MOUNT_BENEATH
30 + #define MOVE_MOUNT_BENEATH 0x00000200
31 + #endif
32 + #ifndef OPEN_TREE_CLONE
33 + #define OPEN_TREE_CLONE 1
34 + #endif
35 + #ifndef OPEN_TREE_CLOEXEC
36 + #define OPEN_TREE_CLOEXEC O_CLOEXEC
37 + #endif
38 +
39 + #define DIR_LEN 64
40 + #define PATH_LEN 192
41 + #define FLAGS (MS_NOSUID | MS_NODEV | MS_NOEXEC)
42 +
43 + /* exit codes of the children, each test says what they mean */
44 + enum {
45 + CHILD_OK,
46 + CHILD_SETUP,
47 + CHILD_STEP1,
48 + CHILD_STEP2,
49 + CHILD_STEP3,
50 + CHILD_STEP4,
51 + };
52 +
53 + static int write_file(const char *path, const char *s)
54 + {
55 + ssize_t n = -1;
56 + int fd;
57 +
58 + fd = open(path, O_WRONLY | O_CLOEXEC);
59 + if (fd >= 0) {
60 + n = write(fd, s, strlen(s));
61 + close(fd);
62 + }
63 + return n == (ssize_t)strlen(s) ? 0 : -1;
64 + }
65 +
66 + static int create_file(const char *path, const char *s)
67 + {
68 + ssize_t n = -1;
69 + int fd;
70 +
71 + fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
72 + if (fd >= 0) {
73 + n = write(fd, s, strlen(s));
74 + close(fd);
75 + }
76 + return n == (ssize_t)strlen(s) ? 0 : -1;
77 + }
78 +
79 + /* Root in a new user namespace with a copy of the mount namespace. */
80 + static int enter_userns(void)
81 + {
82 + uid_t uid = getuid();
83 + gid_t gid = getgid();
84 + char map[32];
85 +
86 + prctl(PR_SET_DUMPABLE, 1);
87 + if (unshare(CLONE_NEWUSER | CLONE_NEWNS))
88 + return -1;
89 + if (write_file("/proc/self/setgroups", "deny") && errno != ENOENT)
90 + return -1;
91 + snprintf(map, sizeof(map), "0 %d 1", uid);
92 + if (write_file("/proc/self/uid_map", map))
93 + return -1;
94 + snprintf(map, sizeof(map), "0 %d 1", gid);
95 + if (write_file("/proc/self/gid_map", map))
96 + return -1;
97 + return setgid(0) || setuid(0) ? -1 : 0;
98 + }
99 +
100 + static int wait_child(pid_t pid)
101 + {
102 + int status;
103 +
104 + if (waitpid(pid, &status, 0) != pid || !WIFEXITED(status))
105 + return -1;
106 + return WEXITSTATUS(status);
107 + }
108 +
109 + static int wait_byte(int fd)
110 + {
111 + char c;
112 +
113 + return read(fd, &c, 1) == 1 ? 0 : -1;
114 + }
115 +
116 + static int send_byte(int fd)
117 + {
118 + return write(fd, "x", 1) == 1 ? 0 : -1;
119 + }
120 +
121 + /* A read of @path fails: the file is covered. */
122 + static bool covered(const char *path)
123 + {
124 + int fd = open(path, O_RDONLY | O_CLOEXEC);
125 +
126 + if (fd >= 0)
127 + close(fd);
128 + return fd < 0;
129 + }
130 +
131 + /* What @path reads, "" if it can't be read. */
132 + static int read_word(const char *path, char *buf, size_t len)
133 + {
134 + ssize_t n = 0;
135 + int fd;
136 +
137 + fd = open(path, O_RDONLY | O_CLOEXEC);
138 + if (fd >= 0) {
139 + n = read(fd, buf, len - 1);
140 + close(fd);
141 + }
142 + buf[n > 0 ? n : 0] = 0;
143 + return fd < 0 ? -1 : 0;
144 + }
145 +
146 + /* Put a clone of the mount at @src beneath the top mount at @where. */
147 + static int move_beneath(const char *src, const char *where)
148 + {
149 + int fd, ret;
150 +
151 + fd = syscall(__NR_open_tree, AT_FDCWD, src, OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC);
152 + if (fd < 0)
153 + return -1;
154 + ret = syscall(__NR_move_mount, fd, "", AT_FDCWD, where,
155 + MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_BENEATH);
156 + close(fd);
157 + return ret;
158 + }
159 +
160 + FIXTURE(locked_mount) {
161 + char base[DIR_LEN];
162 + bool tracing; /* debugfs with the tracefs automount is there */
163 + };
164 +
165 + FIXTURE_SETUP(locked_mount)
166 + {
167 + char p[PATH_LEN];
168 + struct stat st;
169 +
170 + if (geteuid())
171 + SKIP(return, "test requires root");
172 +
173 + snprintf(self->base, sizeof(self->base), "/tmp/locked_mount.XXXXXX");
174 + ASSERT_NE(mkdtemp(self->base), NULL);
175 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
176 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
177 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, "mode=0755"), 0);
178 +
179 + /* an automount that a user can name: the tracefs below debugfs */
180 + snprintf(p, sizeof(p), "%s/dbg", self->base);
181 + ASSERT_EQ(mkdir(p, 0755), 0);
182 + self->tracing = !mount("debugfs", p, "debugfs", FLAGS, NULL);
183 + if (self->tracing) {
184 + /* the cases trigger it themselves */
185 + snprintf(p, sizeof(p), "%s/dbg/tracing", self->base);
186 + self->tracing = !fstatat(AT_FDCWD, p, &st, AT_NO_AUTOMOUNT) &&
187 + S_ISDIR(st.st_mode);
188 + }
189 + }
190 +
191 + FIXTURE_TEARDOWN(locked_mount)
192 + {
193 + umount2(self->base, MNT_DETACH);
194 + rmdir(self->base);
195 + }
196 +
197 + /*
198 + * The child keeps a directory descriptor on the host's debugfs mount, moves
199 + * to a user namespace of its own and triggers the automount through the
200 + * descriptor. The mount goes below the host's mount and propagates into the
201 + * child's copy. The child's copy has to be locked, the host's not.
202 + */
203 + static int automount_child(const char *base, int dfd, int to_host, int from_host)
204 + {
205 + char p[PATH_LEN];
206 + struct stat st;
207 +
208 + if (enter_userns())
209 + return CHILD_SETUP;
210 + if (fstatat(dfd, "tracing/.", &st, 0))
211 + return CHILD_STEP1;
212 + if (send_byte(to_host) || wait_byte(from_host))
213 + return CHILD_SETUP;
214 + /* the flags of the copy are locked: EPERM */
215 + snprintf(p, sizeof(p), "%s/dbg/tracing", base);
216 + if (!mount(NULL, p, NULL, MS_REMOUNT | MS_BIND, NULL) || errno != EPERM)
217 + return CHILD_STEP2;
218 + return CHILD_OK;
219 + }
220 +
221 + TEST_F(locked_mount, automount_locked_in_the_triggering_namespace)
222 + {
223 + int to_host[2], from_host[2], dfd, ret;
224 + char p[PATH_LEN];
225 + pid_t pid;
226 +
227 + if (!self->tracing)
228 + SKIP(return, "test requires debugfs with the tracefs automount");
229 +
230 + snprintf(p, sizeof(p), "%s/dbg", self->base);
231 + ASSERT_EQ(mount(NULL, p, NULL, MS_SHARED, NULL), 0);
232 + dfd = open(p, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
233 + ASSERT_GE(dfd, 0);
234 + ASSERT_EQ(pipe(to_host), 0);
235 + ASSERT_EQ(pipe(from_host), 0);
236 +
237 + pid = fork();
238 + ASSERT_GE(pid, 0);
239 + if (pid == 0)
240 + _exit(automount_child(self->base, dfd, to_host[1], from_host[0]));
241 + close(dfd);
242 + ASSERT_EQ(wait_byte(to_host[0]), 0);
243 +
244 + /* the host's own mount isn't locked: the flags can go */
245 + snprintf(p, sizeof(p), "%s/dbg/tracing", self->base);
246 + EXPECT_EQ(mount(NULL, p, NULL, MS_REMOUNT | MS_BIND, NULL), 0);
247 +
248 + ASSERT_EQ(send_byte(from_host[1]), 0);
249 + ret = wait_child(pid);
250 + TH_LOG("child exit code %d", ret);
251 + EXPECT_EQ(ret, CHILD_OK);
252 + }
253 +
254 + /*
255 + * A copy of a tree with a locked cover. The child puts a shrinkable mount
256 + * beneath the cover, which hands the lock down, unmounts the cover and then
257 + * asks for the umount of an unlocked ancestor. That expires the shrinkable
258 + * mount on a kernel that doesn't look at the lock, and the covered
259 + * directory is bare.
260 + */
261 + static int expiry_child(const char *base)
262 + {
263 + char srv[PATH_LEN], shr[PATH_LEN], x[PATH_LEN], c[PATH_LEN];
264 + char hidden[PATH_LEN], secret[PATH_LEN];
265 +
266 + snprintf(srv, sizeof(srv), "%s/srv", base);
267 + snprintf(shr, sizeof(shr), "%s/shr", base);
268 + snprintf(x, sizeof(x), "%s/x", base);
269 + snprintf(c, sizeof(c), "%s/c", base);
270 + snprintf(hidden, sizeof(hidden), "%s/x/hidden", base);
271 + snprintf(secret, sizeof(secret), "%s/x/hidden/secret", base);
272 +
273 + if (enter_userns())
274 + return CHILD_SETUP;
275 + if (mount(srv, x, NULL, MS_BIND | MS_REC, NULL) ||
276 + mount(shr, c, NULL, MS_BIND, NULL))
277 + return CHILD_SETUP;
278 + /* the cover is locked */
279 + if (!umount2(hidden, 0) || errno != EINVAL)
280 + return CHILD_STEP1;
281 + if (syscall(__NR_move_mount, AT_FDCWD, c, AT_FDCWD, hidden, MOVE_MOUNT_BENEATH))
282 + return CHILD_STEP2;
283 + /* the lock moved down, the cover may go */
284 + if (umount2(hidden, 0))
285 + return CHILD_STEP3;
286 + /* the holder of the lock may not, in any way */
287 + if (!umount2(hidden, 0) || errno != EINVAL)
288 + return CHILD_STEP4;
289 + if (chdir(x))
290 + return CHILD_SETUP;
291 + umount2(x, 0);
292 + return covered(secret) ? CHILD_OK : CHILD_STEP4;
293 + }
294 +
295 + TEST_F(locked_mount, expiry_leaves_a_locked_mount_alone)
296 + {
297 + char p[PATH_LEN], q[PATH_LEN];
298 + pid_t pid;
299 + int ret;
300 +
301 + if (!self->tracing)
302 + SKIP(return, "test requires debugfs with the tracefs automount");
303 +
304 + snprintf(p, sizeof(p), "%s/dbg/tracing", self->base);
305 + snprintf(q, sizeof(q), "%s/shr", self->base);
306 + ASSERT_EQ(mkdir(q, 0755), 0);
307 + /* a bind of an automount is shrinkable as well */
308 + ASSERT_EQ(mount(p, q, NULL, MS_BIND, NULL), 0);
309 + snprintf(p, sizeof(p), "%s/srv", self->base);
310 + ASSERT_EQ(mkdir(p, 0755), 0);
311 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, "mode=0755"), 0);
312 + snprintf(p, sizeof(p), "%s/srv/hidden", self->base);
313 + ASSERT_EQ(mkdir(p, 0755), 0);
314 + snprintf(p, sizeof(p), "%s/srv/hidden/secret", self->base);
315 + ASSERT_EQ(create_file(p, "covered-by-root\n"), 0);
316 + snprintf(p, sizeof(p), "%s/srv/hidden", self->base);
317 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, "mode=0755"), 0);
318 + snprintf(p, sizeof(p), "%s/x", self->base);
319 + ASSERT_EQ(mkdir(p, 0755), 0);
320 + snprintf(p, sizeof(p), "%s/c", self->base);
321 + ASSERT_EQ(mkdir(p, 0755), 0);
322 +
323 + pid = fork();
324 + ASSERT_GE(pid, 0);
325 + if (pid == 0)
326 + _exit(expiry_child(self->base));
327 + ret = wait_child(pid);
328 + TH_LOG("child exit code %d", ret);
329 + EXPECT_EQ(ret, CHILD_OK);
330 + }
331 +
332 + /*
333 + * The copy of the mount tree that a user namespace gets at its creation has
334 + * the automounts in it locked unless they are on an expiry list. A bind of
335 + * such a tree inside the namespace copies the lock to the automount but not
336 + * to the root of the bind, so the child may ask for the umount of that root.
337 + * That must not expire the locked automount below it: the root is busy, the
338 + * umount fails and the automount has to be there afterwards.
339 + */
340 + static int copied_tree_child(const char *base)
341 + {
342 + char dbg[PATH_LEN], x[PATH_LEN], tracing[PATH_LEN];
343 + struct stat root, st;
344 +
345 + snprintf(dbg, sizeof(dbg), "%s/dbg", base);
346 + snprintf(x, sizeof(x), "%s/x", base);
347 + snprintf(tracing, sizeof(tracing), "%s/x/tracing", base);
348 +
349 + if (enter_userns())
350 + return CHILD_SETUP;
351 + if (mount(dbg, x, NULL, MS_BIND | MS_REC, NULL))
352 + return CHILD_SETUP;
353 + /* the copy of the automount carries the lock */
354 + if (!umount2(tracing, 0) || errno != EINVAL)
355 + return CHILD_STEP1;
356 + /* the root of the bind doesn't; keep it busy */
357 + if (chdir(x))
358 + return CHILD_SETUP;
359 + if (!umount2(x, 0) || errno != EBUSY)
360 + return CHILD_STEP2;
361 + /* the automount below it must not have gone */
362 + if (stat(x, &root) || fstatat(AT_FDCWD, tracing, &st, AT_NO_AUTOMOUNT))
363 + return CHILD_SETUP;
364 + return st.st_dev != root.st_dev ? CHILD_OK : CHILD_STEP3;
365 + }
366 +
367 + TEST_F(locked_mount, umount_of_a_bind_leaves_a_locked_automount_alone)
368 + {
369 + char p[PATH_LEN];
370 + struct stat st;
371 + pid_t pid;
372 + int ret;
373 +
374 + if (!self->tracing)
375 + SKIP(return, "test requires debugfs with the tracefs automount");
376 +
377 + /* the copy the child gets has to contain the automount */
378 + snprintf(p, sizeof(p), "%s/dbg/tracing/.", self->base);
379 + ASSERT_EQ(stat(p, &st), 0);
380 + snprintf(p, sizeof(p), "%s/x", self->base);
381 + ASSERT_EQ(mkdir(p, 0755), 0);
382 +
383 + pid = fork();
384 + ASSERT_GE(pid, 0);
385 + if (pid == 0)
386 + _exit(copied_tree_child(self->base));
387 + ret = wait_child(pid);
388 + TH_LOG("child exit code %d", ret);
389 + EXPECT_EQ(ret, CHILD_OK);
390 + }
391 +
392 + /*
393 + * Z is a user namespace with a copy of a tree in which P/d is covered by a
394 + * locked mount. The host mounts X on P/d, which propagates beneath Z's
395 + * cover, and unmounts it again. Z's cover has to be locked afterwards as
396 + * it was before.
397 + */
398 + static int propagation_child(const char *base, int to_host, int from_host)
399 + {
400 + char d[PATH_LEN], secret[PATH_LEN];
401 +
402 + snprintf(d, sizeof(d), "%s/P/d", base);
403 + snprintf(secret, sizeof(secret), "%s/P/d/secret", base);
404 +
405 + if (enter_userns())
406 + return CHILD_SETUP;
407 + /* the cover is locked */
408 + if (!umount2(d, 0) || errno != EINVAL)
409 + return CHILD_STEP1;
410 + if (send_byte(to_host) || wait_byte(from_host))
411 + return CHILD_SETUP;
412 + /* X came and went beneath it: still locked */
413 + if (!umount2(d, 0) || errno != EINVAL)
414 + return CHILD_STEP2;
415 + return covered(secret) ? CHILD_OK : CHILD_STEP3;
416 + }
417 +
418 + TEST_F(locked_mount, propagated_copy_keeps_the_cover_locked)
419 + {
420 + int to_host[2], from_host[2], ret;
421 + char p[PATH_LEN];
422 + pid_t pid;
423 +
424 + snprintf(p, sizeof(p), "%s/P", self->base);
425 + ASSERT_EQ(mkdir(p, 0755), 0);
426 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, "mode=0755"), 0);
427 + ASSERT_EQ(mount(NULL, p, NULL, MS_SHARED, NULL), 0);
428 + snprintf(p, sizeof(p), "%s/P/d", self->base);
429 + ASSERT_EQ(mkdir(p, 0755), 0);
430 + snprintf(p, sizeof(p), "%s/P/d/secret", self->base);
431 + ASSERT_EQ(create_file(p, "covered-by-root\n"), 0);
432 + ASSERT_EQ(pipe(to_host), 0);
433 + ASSERT_EQ(pipe(from_host), 0);
434 +
435 + pid = fork();
436 + ASSERT_GE(pid, 0);
437 + if (pid == 0) {
438 + /* M: a manager's namespace that covers P/d for Z */
439 + pid_t z;
440 +
441 + if (unshare(CLONE_NEWNS))
442 + _exit(CHILD_SETUP);
443 + snprintf(p, sizeof(p), "%s/P", self->base);
444 + if (mount(NULL, p, NULL, MS_SLAVE, NULL))
445 + _exit(CHILD_SETUP);
446 + snprintf(p, sizeof(p), "%s/P/d", self->base);
447 + if (mount("tmpfs", p, "tmpfs", 0, "mode=0755"))
448 + _exit(CHILD_SETUP);
449 + z = fork();
450 + if (z < 0)
451 + _exit(CHILD_SETUP);
452 + if (z == 0)
453 + _exit(propagation_child(self->base, to_host[1], from_host[0]));
454 + _exit(wait_child(z));
455 + }
456 + ASSERT_EQ(wait_byte(to_host[0]), 0);
457 +
458 + /* the host mounts on P/d and unmounts again; both propagate */
459 + snprintf(p, sizeof(p), "%s/P/d", self->base);
460 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, "mode=0755"), 0);
461 + ASSERT_EQ(umount2(p, 0), 0);
462 +
463 + ASSERT_EQ(send_byte(from_host[1]), 0);
464 + ret = wait_child(pid);
465 + TH_LOG("child exit code %d", ret);
466 + EXPECT_EQ(ret, CHILD_OK);
467 + }
468 +
469 + /*
470 + * A mount of a mount namespace file is left out of the copy that
471 + * unshare(CLONE_NEWNS) makes, together with everything mounted on it, so
472 + * it can't take over the lock of a cover it is moved beneath. The child
473 + * tries just that with the namespace file of a grandchild and gets EINVAL.
474 + * A bind of an ordinary file takes the lock over, and the file is still
475 + * covered in the next copy of the mount namespace.
476 + */
477 + static int ns_file_child(const char *base)
478 + {
479 + char secret[PATH_LEN], mine[PATH_LEN], nsfile[PATH_LEN], buf[32];
480 + int ret = CHILD_OK, pfd[2];
481 + pid_t pid;
482 +
483 + snprintf(secret, sizeof(secret), "%s/P/secret", base);
484 + snprintf(mine, sizeof(mine), "%s/mine", base);
485 +
486 + if (enter_userns() || pipe(pfd))
487 + return CHILD_SETUP;
488 + /* the cover is locked */
489 + if (!umount2(secret, 0) || errno != EINVAL)
490 + return CHILD_STEP1;
491 +
492 + /* a mount namespace newer than our own, so that a bind of it is allowed */
493 + pid = fork();
494 + if (pid < 0)
495 + return CHILD_SETUP;
496 + if (pid == 0) {
497 + if (unshare(CLONE_NEWNS) || send_byte(pfd[1]))
498 + _exit(1);
499 + pause();
500 + _exit(0);
501 + }
502 + if (wait_byte(pfd[0]))
503 + return CHILD_SETUP;
504 + snprintf(nsfile, sizeof(nsfile), "/proc/%d/ns/mnt", pid);
505 + if (!move_beneath(nsfile, secret) || errno != EINVAL)
506 + ret = CHILD_STEP2;
507 + kill(pid, SIGKILL);
508 + waitpid(pid, NULL, 0);
509 + if (ret)
510 + return ret;
511 +
512 + /* an ordinary file beneath the cover takes the lock over */
513 + if (move_beneath(mine, secret))
514 + return CHILD_STEP3;
515 + if (umount2(secret, 0))
516 + return CHILD_STEP3;
517 + if (!umount2(secret, 0) || errno != EINVAL)
518 + return CHILD_STEP3;
519 + /* and it is in the next copy of the namespace */
520 + if (unshare(CLONE_NEWNS))
521 + return CHILD_SETUP;
522 + if (read_word(secret, buf, sizeof(buf)) || strcmp(buf, "mine"))
523 + return CHILD_STEP4;
524 + return CHILD_OK;
525 + }
526 +
527 + TEST_F(locked_mount, mount_namespace_file_cant_take_the_lock)
528 + {
529 + char p[PATH_LEN], q[PATH_LEN];
530 + pid_t pid;
531 + int ret;
532 +
533 + snprintf(p, sizeof(p), "%s/P", self->base);
534 + ASSERT_EQ(mkdir(p, 0755), 0);
535 + ASSERT_EQ(mount("tmpfs", p, "tmpfs", 0, "mode=0755"), 0);
536 + snprintf(p, sizeof(p), "%s/P/secret", self->base);
537 + ASSERT_EQ(create_file(p, "covered-by-root\n"), 0);
538 + snprintf(q, sizeof(q), "%s/P/empty", self->base);
539 + ASSERT_EQ(create_file(q, ""), 0);
540 + /* the cover: an empty file over the secret */
541 + ASSERT_EQ(mount(q, p, NULL, MS_BIND, NULL), 0);
542 + snprintf(q, sizeof(q), "%s/mine", self->base);
543 + ASSERT_EQ(create_file(q, "mine"), 0);
544 +
545 + pid = fork();
546 + ASSERT_GE(pid, 0);
547 + if (pid == 0)
548 + _exit(ns_file_child(self->base));
549 + ret = wait_child(pid);
550 + TH_LOG("child exit code %d", ret);
551 + EXPECT_EQ(ret, CHILD_OK);
552 + }
553 +
554 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/umount_propagation/shrink_submounts_test.c mode 100644
@@ -0,0 +1,211 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A synchronous umount first unmounts the shrinkable submounts of the
4 + * victim that aren't busy. Every one of them has to be checked right
5 + * before it is unmounted: unmounting one can slide a busy mount to where
6 + * the propagated copy of the next one is looked up.
7 + */
8 + #define _GNU_SOURCE
9 + #include <errno.h>
10 + #include <fcntl.h>
11 + #include <sched.h>
12 + #include <stdio.h>
13 + #include <stdlib.h>
14 + #include <string.h>
15 + #include <unistd.h>
16 + #include <sys/fanotify.h>
17 + #include <sys/mount.h>
18 + #include <sys/stat.h>
19 + #include <sys/statfs.h>
20 + #include <sys/vfs.h>
21 + #include <linux/magic.h>
22 +
23 + #include "../../kselftest_harness.h"
24 +
25 + #ifndef FAN_REPORT_MNT
26 + #define FAN_REPORT_MNT 0x00004000
27 + #endif
28 + #ifndef FAN_MARK_MNTNS
29 + #define FAN_MARK_MNTNS 0x00000110
30 + #endif
31 + #ifndef FAN_MNT_ATTACH
32 + #define FAN_MNT_ATTACH 0x01000000
33 + #endif
34 + #ifndef FAN_MNT_DETACH
35 + #define FAN_MNT_DETACH 0x02000000
36 + #endif
37 +
38 + #define DIR_LEN 64
39 + #define PATH_LEN 128
40 +
41 + FIXTURE(shrink_submounts) {
42 + char base[DIR_LEN];
43 + char automount[PATH_LEN];
44 + bool mounted;
45 + int fan;
46 + };
47 +
48 + /*
49 + * Shrinkable mounts come from an automount. The tracefs mount below debugfs
50 + * is one and bind mounts inherit the flag.
51 + */
52 + FIXTURE_SETUP(shrink_submounts)
53 + {
54 + struct stat st;
55 + char p[PATH_LEN];
56 +
57 + self->mounted = false;
58 + self->fan = -1;
59 +
60 + if (geteuid() != 0)
61 + SKIP(return, "test requires CAP_SYS_ADMIN");
62 +
63 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
64 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
65 +
66 + snprintf(self->base, sizeof(self->base), "/tmp/shrink_submounts.XXXXXX");
67 + ASSERT_NE(mkdtemp(self->base), NULL);
68 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, NULL), 0);
69 + self->mounted = true;
70 + ASSERT_EQ(mount(NULL, self->base, NULL, MS_PRIVATE, NULL), 0);
71 +
72 + snprintf(p, sizeof(p), "%s/dbg", self->base);
73 + ASSERT_EQ(mkdir(p, 0755), 0);
74 + if (mount("debugfs", p, "debugfs", 0, NULL)) {
75 + umount2(self->base, MNT_DETACH);
76 + rmdir(self->base);
77 + SKIP(return, "test requires debugfs");
78 + }
79 + snprintf(self->automount, sizeof(self->automount), "%s/dbg/tracing",
80 + self->base);
81 + snprintf(p, sizeof(p), "%s/dbg/tracing/.", self->base);
82 + if (stat(p, &st)) {
83 + umount2(self->base, MNT_DETACH);
84 + rmdir(self->base);
85 + SKIP(return, "test requires the tracefs automount");
86 + }
87 + }
88 +
89 + FIXTURE_TEARDOWN(shrink_submounts)
90 + {
91 + if (self->fan >= 0)
92 + close(self->fan);
93 + chdir("/");
94 + if (self->mounted)
95 + umount2(self->base, MNT_DETACH);
96 + rmdir(self->base);
97 + }
98 +
99 + static bool mounted_tmpfs(const char *path)
100 + {
101 + struct statfs st;
102 +
103 + return !statfs(path, &st) && st.f_type == TMPFS_MAGIC;
104 + }
105 +
106 + /*
107 + * P is a shared bind mount of the automount, P1 a slave of P that is shared
108 + * in turn and P2 its peer. B, another bind mount of the automount, goes on
109 + * P/options and propagates copies Bc1 and Bc2 onto P1/options and
110 + * P2/options. R, a tmpfs and our working directory, sits on top of Bc2 which
111 + * is made private first. P, with B on it, is moved to P1/instances.
112 + *
113 + * A synchronous umount of P1 unmounts the shrinkable submounts Bc1 and B
114 + * first. Unmounting Bc1 takes Bc2 along and slides R to P2/options where
115 + * the propagated copy of B is looked up next. R is busy, so B has to stay
116 + * and the umount fails with EBUSY.
117 + */
118 + TEST_F(shrink_submounts, busy_mount_moved_into_reach)
119 + {
120 + char p[PATH_LEN], p1[PATH_LEN], p2[PATH_LEN], r[PATH_LEN], cwd[PATH_LEN];
121 + int nsfd;
122 +
123 + snprintf(p, sizeof(p), "%s/p", self->base);
124 + snprintf(p1, sizeof(p1), "%s/p1", self->base);
125 + snprintf(p2, sizeof(p2), "%s/p2", self->base);
126 + ASSERT_EQ(mkdir(p, 0755), 0);
127 + ASSERT_EQ(mkdir(p1, 0755), 0);
128 + ASSERT_EQ(mkdir(p2, 0755), 0);
129 +
130 + /* watch the mount namespace so that the detached mounts get queued */
131 + self->fan = fanotify_init(FAN_REPORT_MNT, O_RDONLY);
132 + if (self->fan >= 0) {
133 + nsfd = open("/proc/self/ns/mnt", O_RDONLY | O_CLOEXEC);
134 + ASSERT_GE(nsfd, 0);
135 + EXPECT_EQ(fanotify_mark(self->fan, FAN_MARK_ADD | FAN_MARK_MNTNS,
136 + FAN_MNT_ATTACH | FAN_MNT_DETACH, nsfd, NULL), 0);
137 + close(nsfd);
138 + }
139 +
140 + ASSERT_EQ(mount(self->automount, p, NULL, MS_BIND, NULL), 0);
141 + ASSERT_EQ(mount(NULL, p, NULL, MS_SHARED, NULL), 0);
142 + ASSERT_EQ(mount(p, p1, NULL, MS_BIND, NULL), 0);
143 + ASSERT_EQ(mount(NULL, p1, NULL, MS_SLAVE, NULL), 0);
144 + ASSERT_EQ(mount(NULL, p1, NULL, MS_SHARED, NULL), 0);
145 + ASSERT_EQ(mount(p1, p2, NULL, MS_BIND, NULL), 0);
146 +
147 + /* B on P/options, copies on P1/options and P2/options */
148 + snprintf(r, sizeof(r), "%s/p/options", self->base);
149 + ASSERT_EQ(mount(self->automount, r, NULL, MS_BIND, NULL), 0);
150 +
151 + /* R on top of Bc2 */
152 + snprintf(r, sizeof(r), "%s/p2/options", self->base);
153 + ASSERT_EQ(mount(NULL, r, NULL, MS_PRIVATE, NULL), 0);
154 + ASSERT_EQ(mount("R", r, "tmpfs", 0, NULL), 0);
155 + ASSERT_EQ(chdir(r), 0);
156 +
157 + /* P, with B on it, below the victim */
158 + snprintf(cwd, sizeof(cwd), "%s/p1/instances", self->base);
159 + ASSERT_EQ(mount(p, cwd, NULL, MS_MOVE, NULL), 0);
160 +
161 + ASSERT_TRUE(mounted_tmpfs(r));
162 + ASSERT_EQ(umount2(p1, 0), -1);
163 + EXPECT_EQ(errno, EBUSY);
164 +
165 + /* R is still mounted and still our working directory */
166 + EXPECT_TRUE(mounted_tmpfs(r));
167 + ASSERT_NE(getcwd(cwd, sizeof(cwd)), NULL);
168 + EXPECT_STREQ(cwd, r);
169 + }
170 +
171 + /*
172 + * T is shared and Q, a slave of T, has T moved into it, so Q receives
173 + * propagation from its own child. M, another bind mount of the automount, is
174 + * on T/options and that is the dentry T sits on in Q. Unmounting M makes T
175 + * the propagated victim at that dentry in Q and takes T along. The shrink
176 + * walk of V has just unmounted M and continues in the children of T.
177 + */
178 + TEST_F(shrink_submounts, parent_goes_with_child)
179 + {
180 + char v[PATH_LEN], t[PATH_LEN], q[PATH_LEN], p[PATH_LEN];
181 + struct stat before, after;
182 +
183 + snprintf(v, sizeof(v), "%s/v", self->base);
184 + snprintf(t, sizeof(t), "%s/v/t", self->base);
185 + snprintf(q, sizeof(q), "%s/v/q", self->base);
186 + ASSERT_EQ(mkdir(v, 0755), 0);
187 + ASSERT_EQ(mount("V", v, "tmpfs", 0, NULL), 0);
188 + ASSERT_EQ(mount(NULL, v, NULL, MS_PRIVATE, NULL), 0);
189 + ASSERT_EQ(stat(v, &before), 0);
190 + ASSERT_EQ(mkdir(t, 0755), 0);
191 + ASSERT_EQ(mkdir(q, 0755), 0);
192 +
193 + /* T shared, M on T/options before anything receives from T */
194 + ASSERT_EQ(mount(self->automount, t, NULL, MS_BIND, NULL), 0);
195 + ASSERT_EQ(mount(NULL, t, NULL, MS_SHARED, NULL), 0);
196 + snprintf(p, sizeof(p), "%s/v/t/options", self->base);
197 + ASSERT_EQ(mount(self->automount, p, NULL, MS_BIND, NULL), 0);
198 +
199 + /* Q, a slave of T, and T moved into Q at the dentry M sits on */
200 + ASSERT_EQ(mount(t, q, NULL, MS_BIND, NULL), 0);
201 + ASSERT_EQ(mount(NULL, q, NULL, MS_SLAVE, NULL), 0);
202 + snprintf(p, sizeof(p), "%s/v/q/options", self->base);
203 + ASSERT_EQ(mount(t, p, NULL, MS_MOVE, NULL), 0);
204 +
205 + /* M, T and then Q go, V is empty and can be unmounted */
206 + ASSERT_EQ(umount2(v, 0), 0);
207 + ASSERT_EQ(stat(v, &after), 0);
208 + EXPECT_NE(before.st_dev, after.st_dev);
209 + }
210 +
211 + TEST_HARNESS_MAIN
added tools/testing/selftests/filesystems/umount_propagation/umount_propagation_test.c mode 100644
@@ -0,0 +1,226 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * A synchronous umount fails with EBUSY when a mount it would pull out by
4 + * propagation is still in use.
5 + */
6 + #define _GNU_SOURCE
7 + #include <errno.h>
8 + #include <fcntl.h>
9 + #include <sched.h>
10 + #include <stdio.h>
11 + #include <stdlib.h>
12 + #include <string.h>
13 + #include <sys/mount.h>
14 + #include <sys/stat.h>
15 + #include <sys/syscall.h>
16 + #include <sys/wait.h>
17 + #include <unistd.h>
18 + #include <linux/mount.h>
19 + #include <linux/stat.h>
20 +
21 + #include "../../kselftest_harness.h"
22 +
23 + #ifndef OPEN_TREE_CLONE
24 + #define OPEN_TREE_CLONE 1
25 + #endif
26 + #ifndef OPEN_TREE_CLOEXEC
27 + #define OPEN_TREE_CLOEXEC O_CLOEXEC
28 + #endif
29 + #ifndef AT_RECURSIVE
30 + #define AT_RECURSIVE 0x8000
31 + #endif
32 + #ifndef MOVE_MOUNT_F_EMPTY_PATH
33 + #define MOVE_MOUNT_F_EMPTY_PATH 0x00000004
34 + #endif
35 + #ifndef MOVE_MOUNT_BENEATH
36 + #define MOVE_MOUNT_BENEATH 0x00000200
37 + #endif
38 + #ifndef STATX_MNT_ID
39 + #define STATX_MNT_ID 0x00001000U
40 + #endif
41 +
42 + static int sys_open_tree(int dfd, const char *filename, unsigned int flags)
43 + {
44 + return syscall(__NR_open_tree, dfd, filename, flags);
45 + }
46 +
47 + static int sys_move_mount(int from_dfd, const char *from_pathname,
48 + int to_dfd, const char *to_pathname,
49 + unsigned int flags)
50 + {
51 + return syscall(__NR_move_mount, from_dfd, from_pathname, to_dfd,
52 + to_pathname, flags);
53 + }
54 +
55 + /* Child exit codes. */
56 + enum {
57 + CHILD_OK,
58 + CHILD_UNSHARE, /* could not set up the slave namespace */
59 + CHILD_OPEN_TREE, /* open_tree() failed */
60 + CHILD_MOVE_MOUNT, /* move_mount() failed */
61 + CHILD_STATX, /* statx() failed */
62 + CHILD_PIPE, /* the parent went away */
63 + };
64 +
65 + /* Messages between parent and child. */
66 + enum {
67 + MSG_READY = 'r', /* child: the copy is mounted and referenced */
68 + MSG_CHECK = 'c', /* parent: check that the copy is still attached */
69 + MSG_ATTACHED = 'a', /* child: it is */
70 + MSG_DETACHED = 'd', /* child: it is not */
71 + MSG_CLOSE = 'x', /* parent: drop the reference */
72 + MSG_CLOSED = 'y', /* child: dropped */
73 + MSG_EXIT = 'e', /* parent: done */
74 + };
75 +
76 + FIXTURE(umount_propagation)
77 + {
78 + char base[64];
79 + char victim[80];
80 + bool mounted;
81 + };
82 +
83 + FIXTURE_SETUP(umount_propagation)
84 + {
85 + self->mounted = false;
86 +
87 + if (geteuid() != 0)
88 + SKIP(return, "test requires CAP_SYS_ADMIN");
89 +
90 + ASSERT_EQ(unshare(CLONE_NEWNS), 0);
91 + ASSERT_EQ(mount("", "/", NULL, MS_REC | MS_PRIVATE, NULL), 0);
92 +
93 + snprintf(self->base, sizeof(self->base), "/tmp/umount_propagation.XXXXXX");
94 + ASSERT_NE(mkdtemp(self->base), NULL);
95 + ASSERT_EQ(mount("tmpfs", self->base, "tmpfs", 0, NULL), 0);
96 + self->mounted = true;
97 + ASSERT_EQ(mount(NULL, self->base, NULL, MS_SHARED, NULL), 0);
98 +
99 + snprintf(self->victim, sizeof(self->victim), "%s/victim", self->base);
100 + ASSERT_EQ(mkdir(self->victim, 0755), 0);
101 + ASSERT_EQ(mount("tmpfs", self->victim, "tmpfs", 0, NULL), 0);
102 + }
103 +
104 + FIXTURE_TEARDOWN(umount_propagation)
105 + {
106 + if (self->mounted)
107 + umount2(self->base, MNT_DETACH);
108 + rmdir(self->base);
109 + }
110 +
111 + static int send_msg(int fd, char msg)
112 + {
113 + return write(fd, &msg, 1) == 1 ? 0 : -1;
114 + }
115 +
116 + static char recv_msg(int fd)
117 + {
118 + char msg;
119 +
120 + if (read(fd, &msg, 1) != 1)
121 + return 0;
122 + return msg;
123 + }
124 +
125 + /* Is the mount with id @mnt_id attached in this mount namespace? */
126 + static bool mount_attached(__u64 mnt_id)
127 + {
128 + char line[4096];
129 + bool found = false;
130 + FILE *f;
131 +
132 + f = fopen("/proc/self/mountinfo", "re");
133 + if (!f)
134 + return false;
135 +
136 + while (fgets(line, sizeof(line), f)) {
137 + if (strtoull(line, NULL, 10) == mnt_id) {
138 + found = true;
139 + break;
140 + }
141 + }
142 + fclose(f);
143 + return found;
144 + }
145 +
146 + /*
147 + * The slave namespace: take a detached copy of the shared tree and move it
148 + * beneath the propagated copy of the victim, keeping the open_tree()
149 + * descriptor as a reference on it.
150 + */
151 + static int slave_child(const char *base, const char *victim, int to_parent,
152 + int from_parent)
153 + {
154 + struct statx stx;
155 + int fd;
156 +
157 + if (unshare(CLONE_NEWNS))
158 + return CHILD_UNSHARE;
159 + if (mount("", "/", NULL, MS_REC | MS_SLAVE, NULL))
160 + return CHILD_UNSHARE;
161 +
162 + fd = sys_open_tree(AT_FDCWD, base,
163 + OPEN_TREE_CLONE | OPEN_TREE_CLOEXEC | AT_RECURSIVE);
164 + if (fd < 0)
165 + return CHILD_OPEN_TREE;
166 + if (sys_move_mount(fd, "", AT_FDCWD, victim,
167 + MOVE_MOUNT_F_EMPTY_PATH | MOVE_MOUNT_BENEATH))
168 + return CHILD_MOVE_MOUNT;
169 + if (statx(fd, "", AT_EMPTY_PATH, STATX_MNT_ID, &stx))
170 + return CHILD_STATX;
171 +
172 + if (send_msg(to_parent, MSG_READY) || recv_msg(from_parent) != MSG_CHECK)
173 + return CHILD_PIPE;
174 + if (send_msg(to_parent, mount_attached(stx.stx_mnt_id) ?
175 + MSG_ATTACHED : MSG_DETACHED))
176 + return CHILD_PIPE;
177 +
178 + if (recv_msg(from_parent) != MSG_CLOSE)
179 + return CHILD_PIPE;
180 + close(fd);
181 + if (send_msg(to_parent, MSG_CLOSED) || recv_msg(from_parent) != MSG_EXIT)
182 + return CHILD_PIPE;
183 + return CHILD_OK;
184 + }
185 +
186 + TEST_F(umount_propagation, busy_copy_pulled_out)
187 + {
188 + int to_child[2], to_parent[2];
189 + int status;
190 + pid_t pid;
191 +
192 + ASSERT_EQ(pipe(to_child), 0);
193 + ASSERT_EQ(pipe(to_parent), 0);
194 +
195 + pid = fork();
196 + ASSERT_GE(pid, 0);
197 + if (pid == 0) {
198 + close(to_child[1]);
199 + close(to_parent[0]);
200 + _exit(slave_child(self->base, self->victim, to_parent[1],
201 + to_child[0]));
202 + }
203 + close(to_child[0]);
204 + close(to_parent[1]);
205 +
206 + ASSERT_EQ(recv_msg(to_parent[0]), MSG_READY);
207 +
208 + /* the copy in the slave namespace is in use */
209 + ASSERT_EQ(umount2(self->victim, 0), -1);
210 + ASSERT_EQ(errno, EBUSY);
211 +
212 + ASSERT_EQ(send_msg(to_child[1], MSG_CHECK), 0);
213 + ASSERT_EQ(recv_msg(to_parent[0]), MSG_ATTACHED);
214 +
215 + /* and once it is not, the umount goes through */
216 + ASSERT_EQ(send_msg(to_child[1], MSG_CLOSE), 0);
217 + ASSERT_EQ(recv_msg(to_parent[0]), MSG_CLOSED);
218 + ASSERT_EQ(umount2(self->victim, 0), 0);
219 +
220 + ASSERT_EQ(send_msg(to_child[1], MSG_EXIT), 0);
221 + ASSERT_EQ(waitpid(pid, &status, 0), pid);
222 + ASSERT_TRUE(WIFEXITED(status));
223 + ASSERT_EQ(WEXITSTATUS(status), CHILD_OK);
224 + }
225 +
226 + TEST_HARNESS_MAIN
modified tools/testing/selftests/mm/hugetlb-mmap.c
@@ -122,7 +122,7 @@ int main(int argc, char **argv)
122 122 hugepage_size = default_huge_page_size();
123 123 if (!hugepage_size)
124 124 ksft_exit_skip("Could not detect default hugetlb page size.");
125 - ksft_print_msg("Default size hugepages (%lu kB)\n", hugepage_size >> 10);
125 + ksft_print_msg("Default size hugepages (%zu kB)\n", hugepage_size >> 10);
126 126 }
127 127
128 128 /* munmap will fail if the length is not page aligned */
@@ -131,7 +131,7 @@ int main(int argc, char **argv)
131 131
132 132 hugetlb_set_nr_pages(hugepage_size, nr);
133 133 if (hugetlb_free_pages(hugepage_size) < nr)
134 - ksft_exit_skip("Not enough %lu Kb pages\n", hugepage_size >> 10);
134 + ksft_exit_skip("Not enough %zu Kb pages\n", hugepage_size >> 10);
135 135
136 136 ksft_set_plan(2);
137 137 ksft_print_msg("Mapping %lu Mbytes\n", (unsigned long)length >> 20);
modified tools/testing/selftests/move_mount_set_group/move_mount_set_group_test.c
@@ -146,17 +146,19 @@ static void null_endofword(char *word)
146 146 *word = '\0';
147 147 }
148 148
149 - static bool is_shared_mount(const char *path)
149 + /* Does the mount on @path carry the optional field @field in mountinfo? */
150 + static bool mount_has_field(const char *path, const char *field)
150 151 {
151 152 size_t len = 0;
152 153 char *line = NULL;
153 154 FILE *f = NULL;
155 + bool found = false;
154 156
155 157 f = fopen("/proc/self/mountinfo", "re");
156 158 if (!f)
157 159 return false;
158 160
159 - while (getline(&line, &len, f) != -1) {
161 + while (!found && getline(&line, &len, f) != -1) {
160 162 char *opts, *target;
161 163
162 164 target = get_field(line, 4);
@@ -172,15 +174,29 @@ static bool is_shared_mount(const char *path)
172 174 if (strcmp(target, path) != 0)
173 175 continue;
174 176
175 - null_endofword(opts);
176 - if (strstr(opts, "shared:"))
177 - return true;
177 + /* the optional fields end at the "-" separator */
178 + while (opts && *opts != '-') {
179 + char *next = strchr(opts, ' ');
180 +
181 + if (next)
182 + *next++ = '\0';
183 + if (!strncmp(opts, field, strlen(field))) {
184 + found = true;
185 + break;
186 + }
187 + opts = next;
188 + }
178 189 }
179 190
180 191 free(line);
181 192 fclose(f);
182 193
183 - return false;
194 + return found;
195 + }
196 +
197 + static bool is_shared_mount(const char *path)
198 + {
199 + return mount_has_field(path, "shared:");
184 200 }
185 201
186 202 /* Attempt to de-conflict with the selftests tree. */
@@ -372,4 +388,50 @@ TEST_F(move_mount_set_group, complex_sharing_copying)
372 388 ASSERT_EQ(is_shared_mount(SET_GROUP_A), 1);
373 389 }
374 390
391 + #define SET_GROUP_B "/tmp/B"
392 + #define SET_GROUP_C "/tmp/C"
393 +
394 + /*
395 + * An unbindable mount is neither shared nor a slave, so it must not be
396 + * accepted as the target: with a slave source it would end up unbindable
397 + * and a slave at the same time.
398 + */
399 + TEST_F(move_mount_set_group, unbindable_target)
400 + {
401 + bool ret;
402 +
403 + ret = move_mount_set_group_supported();
404 + ASSERT_GE(ret, 0);
405 + if (!ret)
406 + SKIP(return, "move_mount(MOVE_MOUNT_SET_GROUP) is not supported");
407 +
408 + ASSERT_EQ(mount(NULL, SET_GROUP_A, NULL, MS_SHARED, 0), 0);
409 +
410 + /* B: a slave of A's peer group */
411 + ASSERT_EQ(mkdir(SET_GROUP_B, 0777), 0);
412 + ASSERT_EQ(mount(SET_GROUP_A, SET_GROUP_B, NULL, MS_BIND, NULL), 0);
413 + ASSERT_EQ(mount(NULL, SET_GROUP_B, NULL, MS_SLAVE, 0), 0);
414 + ASSERT_TRUE(mount_has_field(SET_GROUP_B, "master:"));
415 +
416 + /* C: unbindable */
417 + ASSERT_EQ(mkdir(SET_GROUP_C, 0777), 0);
418 + ASSERT_EQ(mount(SET_GROUP_A, SET_GROUP_C, NULL, MS_BIND, NULL), 0);
419 + ASSERT_EQ(mount(NULL, SET_GROUP_C, NULL, MS_UNBINDABLE, 0), 0);
420 + ASSERT_TRUE(mount_has_field(SET_GROUP_C, "unbindable"));
421 +
422 + /* from a slave */
423 + ASSERT_EQ(syscall(__NR_move_mount, AT_FDCWD, SET_GROUP_B,
424 + AT_FDCWD, SET_GROUP_C, MOVE_MOUNT_SET_GROUP), -1);
425 + ASSERT_EQ(errno, EINVAL);
426 + ASSERT_FALSE(mount_has_field(SET_GROUP_C, "master:"));
427 + ASSERT_TRUE(mount_has_field(SET_GROUP_C, "unbindable"));
428 +
429 + /* from a shared mount */
430 + ASSERT_EQ(syscall(__NR_move_mount, AT_FDCWD, SET_GROUP_A,
431 + AT_FDCWD, SET_GROUP_C, MOVE_MOUNT_SET_GROUP), -1);
432 + ASSERT_EQ(errno, EINVAL);
433 + ASSERT_FALSE(mount_has_field(SET_GROUP_C, "shared:"));
434 + ASSERT_TRUE(mount_has_field(SET_GROUP_C, "unbindable"));
435 + }
436 +
375 437 TEST_HARNESS_MAIN
modified tools/testing/selftests/net/amt.sh
@@ -150,6 +150,13 @@ setup_interface()
150 150 ip netns exec "${RELAY}" ip a a 10.0.0.2/24 dev relay_gw
151 151 ip netns exec "${RELAY}" ip link add amtr type amt mode relay \
152 152 local 10.0.0.2 dev relay_gw relay_port 2268 max_tunnels 4
153 + # Count the IGMP and MLD queries that leave the relay through its own
154 + # amt device; test_query_egress expects none.
155 + ip netns exec "${RELAY}" tc qdisc add dev amtr clsact
156 + ip netns exec "${RELAY}" tc filter add dev amtr egress pref 1 \
157 + protocol ip flower ip_proto 0x2 action pass
158 + ip netns exec "${RELAY}" tc filter add dev amtr egress pref 2 \
159 + protocol ipv6 flower ip_proto icmpv6 type 130 action pass
153 160 ip netns exec "${RELAY}" ip a a 172.17.0.1/24 dev relay_src
154 161 ip netns exec "${RELAY}" ip a a 2001:db8:3::1/64 dev relay_src
155 162 ip netns exec "${SOURCE}" ip a a 172.17.0.2/24 dev src_relay
@@ -246,6 +253,27 @@ test_ipv6_forward()
246 253 fi
247 254 }
248 255
256 + # The relay sends its General Queries straight from the receive path, in
257 + # the same context that found the tunnel. A query queued on the amt device
258 + # instead could outlive the tunnel it was built for. The forwarding tests
259 + # above show that the gateway got its queries.
260 + test_query_egress()
261 + {
262 + local n4 n6
263 +
264 + n4=$(ip netns exec "${RELAY}" tc -s -j filter show dev amtr egress \
265 + pref 1 | jq '[.[].options.actions[0].stats.packets // empty] | add // 0')
266 + n6=$(ip netns exec "${RELAY}" tc -s -j filter show dev amtr egress \
267 + pref 2 | jq '[.[].options.actions[0].stats.packets // empty] | add // 0')
268 + if [ "$n4" -eq 0 ] && [ "$n6" -eq 0 ]; then
269 + printf "TEST: %-60s [ OK ]\n" "amt relay queries bypass the amt device"
270 + else
271 + printf "TEST: %-60s [FAIL]\n" "amt relay queries bypass the amt device"
272 + echo "IGMP queries on amtr egress: $n4, MLD queries: $n6" >&2
273 + ERR=1
274 + fi
275 + }
276 +
249 277 send_mcast4()
250 278 {
251 279 sleep 5
@@ -287,6 +315,7 @@ wait $pid || err=$?
287 315 if [ $err -eq 1 ]; then
288 316 ERR=1
289 317 fi
318 + test_query_egress
290 319 printf "TEST: %-50s" "IPv4 amt traffic forwarding torture"
291 320 send_mcast_torture4
292 321 printf " [ OK ]\n"
modified tools/testing/selftests/net/tun.c
@@ -9,6 +9,7 @@
9 9 #include <string.h>
10 10 #include <unistd.h>
11 11 #include <linux/if_tun.h>
12 + #include <netinet/tcp.h>
12 13 #include <sys/ioctl.h>
13 14 #include <sys/socket.h>
14 15
@@ -542,6 +543,141 @@ TEST_F(tun, reattach_close_delete)
542 543 EXPECT_EQ(tun_delete(self->ifname), 0);
543 544 }
544 545
546 + FIXTURE(tun_vnet_gso)
547 + {
548 + char ifname[IFNAMSIZ];
549 + int fd;
550 + };
551 +
552 + FIXTURE_SETUP(tun_vnet_gso)
553 + {
554 + int flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
555 +
556 + memset(self->ifname, 0, sizeof(self->ifname));
557 + self->fd = tun_open(self->ifname, flags, 0, 0, NULL);
558 + ASSERT_GE(self->fd, 0);
559 + }
560 +
561 + FIXTURE_TEARDOWN(tun_vnet_gso)
562 + {
563 + if (self->fd >= 0)
564 + close(self->fd);
565 + }
566 +
567 + static int build_vlan_tcpv4_gso_packet(uint8_t *buf, int payload_len)
568 + {
569 + uint16_t vlan_tag[2] = { htons(100), htons(ETH_P_IP) };
570 + uint8_t *cur = buf + sizeof(struct virtio_net_hdr);
571 + struct virtio_net_hdr vh = { 0 };
572 + struct tcphdr tcph = { 0 };
573 + uint32_t sum;
574 +
575 + cur += build_eth(cur, ETH_P_8021Q, param_hwaddr_outer_src,
576 + param_hwaddr_outer_dst);
577 +
578 + /* 802.1Q tag: VID=100, inner protocol=ETH_P_IP */
579 + memcpy(cur, vlan_tag, sizeof(vlan_tag));
580 + cur += sizeof(vlan_tag);
581 +
582 + cur += build_ipv4_header(cur, IPPROTO_TCP,
583 + sizeof(tcph) + payload_len,
584 + &param_ipaddr4_outer_src,
585 + &param_ipaddr4_outer_dst);
586 +
587 + tcph.source = htons(12345);
588 + tcph.dest = htons(80);
589 + tcph.seq = htonl(1);
590 + tcph.doff = sizeof(tcph) / 4;
591 + tcph.ack = 1;
592 + tcph.window = htons(65535);
593 + memcpy(cur, &tcph, sizeof(tcph));
594 + memset(cur + sizeof(tcph), PKT_DATA, payload_len);
595 +
596 + sum = add_csum((const uint8_t *)&param_ipaddr4_outer_src,
597 + sizeof(param_ipaddr4_outer_src));
598 + sum += add_csum((const uint8_t *)&param_ipaddr4_outer_dst,
599 + sizeof(param_ipaddr4_outer_dst));
600 + sum += htons(IPPROTO_TCP) + htons(sizeof(tcph) + payload_len);
601 + sum += add_csum(cur, sizeof(tcph) + payload_len);
602 + tcph.check = finish_ip_csum(sum);
603 + memcpy(cur, &tcph, sizeof(tcph));
604 + cur += sizeof(tcph) + payload_len;
605 +
606 + vh.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
607 + vh.gso_size = 1400;
608 + vh.hdr_len = (cur - buf) - sizeof(vh) - payload_len;
609 + memcpy(buf, &vh, sizeof(vh));
610 +
611 + return cur - buf;
612 + }
613 +
614 + TEST_F(tun_vnet_gso, vlan_tcpv4_gso_no_csum)
615 + {
616 + struct virtio_net_hdr vh;
617 + uint8_t pkt[4096] = { 0 };
618 + int len, ret;
619 +
620 + len = build_vlan_tcpv4_gso_packet(pkt, 2800);
621 + memcpy(&vh, pkt, sizeof(vh));
622 +
623 + /* Valid VLAN-tagged TCPv4 GSO with flags = 0 (no NEEDS_CSUM) */
624 + vh.flags = 0;
625 + memcpy(pkt, &vh, sizeof(vh));
626 + ret = write(self->fd, pkt, len);
627 + ASSERT_EQ(ret, len);
628 +
629 + /* Valid VLAN-tagged TCPv4 GSO with flags = DATA_VALID */
630 + vh.flags = VIRTIO_NET_HDR_F_DATA_VALID;
631 + memcpy(pkt, &vh, sizeof(vh));
632 + ret = write(self->fd, pkt, len);
633 + ASSERT_EQ(ret, len);
634 +
635 + /* Mismatched GSO type (TCPV6 on VLAN-tagged IPv4 packet) */
636 + vh.flags = 0;
637 + vh.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
638 + memcpy(pkt, &vh, sizeof(vh));
639 + ret = write(self->fd, pkt, len);
640 + ASSERT_EQ(ret, -1);
641 + ASSERT_EQ(errno, EINVAL);
642 +
643 + /* TCP header truncated after 10 bytes, without NEEDS_CSUM.
644 + * Requires the transport header offset found by flow dissection:
645 + * pulling only sizeof(struct iphdr) + sizeof(struct tcphdr) bytes
646 + * from the mac header would accept this frame.
647 + */
648 + vh.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
649 + vh.hdr_len = ETH_HLEN + 4 + sizeof(struct iphdr) + 10;
650 + memcpy(pkt, &vh, sizeof(vh));
651 + ret = write(self->fd, pkt, sizeof(vh) + vh.hdr_len);
652 + ASSERT_EQ(ret, -1);
653 + ASSERT_EQ(errno, EINVAL);
654 + }
655 +
656 + TEST_F(tun_vnet_gso, vlan_tcpv4_gso_no_csum_64k)
657 + {
658 + /* Ethernet frame of 65540 bytes: skb->len is above U16_MAX when the
659 + * frame is flow-dissected, before eth_type_trans() pulls ETH_HLEN.
660 + */
661 + const int payload_len = 65540 - ETH_HLEN - 4 -
662 + sizeof(struct iphdr) - sizeof(struct tcphdr);
663 + struct virtio_net_hdr vh;
664 + uint8_t *pkt;
665 + int len, ret;
666 +
667 + pkt = calloc(1, sizeof(vh) + 65540);
668 + ASSERT_NE(pkt, NULL);
669 +
670 + len = build_vlan_tcpv4_gso_packet(pkt, payload_len);
671 + ASSERT_EQ(len, sizeof(vh) + 65540);
672 + memcpy(&vh, pkt, sizeof(vh));
673 +
674 + vh.flags = 0;
675 + memcpy(pkt, &vh, sizeof(vh));
676 + ret = write(self->fd, pkt, len);
677 + free(pkt);
678 + ASSERT_EQ(ret, len);
679 + }
680 +
545 681 FIXTURE(tun_vnet_udptnl)
546 682 {
547 683 char ifname[IFNAMSIZ];
modified tools/testing/selftests/net/veth.sh
@@ -9,6 +9,8 @@ readonly DST=1
9 9 readonly DST_NAT=100
10 10 readonly NS_SRC=$BASE$SRC
11 11 readonly NS_DST=$BASE$DST
12 + # shellcheck disable=SC2155 # prefer RO variable over return value from cmd
13 + readonly YNL="$(dirname "$(readlink -f "$0")")/../../../net/ynl/pyynl/cli.py"
12 14
13 15 # "baremetal" network used for raw UDP traffic
14 16 readonly BM_NET_V4=192.168.1.
@@ -74,6 +76,37 @@ chk_tso_flag() {
74 76 __chk_flag "$1" $2 $3 tcp-segmentation-offload
75 77 }
76 78
79 + chk_xdp_feature() {
80 + local msg="$1"
81 + local target=$2
82 + local expected=$3
83 + local feature=$4
84 + local ifindex
85 + local out
86 + local st
87 + local flag
88 +
89 + ifindex=`ip netns exec $BASE$target cat /sys/class/net/veth$target/ifindex`
90 + out=`ip netns exec $BASE$target "$YNL" --family netdev --do dev-get \
91 + --output-json --json "{\"ifindex\": $ifindex}" 2>&1`
92 + st=$?
93 +
94 + printf "%-60s" "$msg"
95 + if [ $st -ne 0 ]; then
96 + echo " fail - ynl cli error: $out"
97 + ret=1
98 + return
99 + fi
100 +
101 + flag=`echo "$out" | grep -c "\"$feature\""`
102 + if [ "$flag" = "$expected" ]; then
103 + echo " ok "
104 + else
105 + echo " fail - expected $expected found $flag"
106 + ret=1
107 + fi
108 + }
109 +
77 110 chk_channels() {
78 111 local msg="$1"
79 112 local target=$2
@@ -222,6 +255,7 @@ fi
222 255
223 256 [ $CPUS -lt 2 ] && echo "Only one CPU available, some tests will be skipped"
224 257 [ $STRESS -gt 0 -a $CPUS -lt 3 ] && echo " stress test will be skipped, too"
258 + [ ! -f "$YNL" ] && echo "ynl cli not found, ndo-xmit tests will be skipped"
225 259
226 260 create_ns
227 261 chk_gro_flag "default - gro flag" $SRC off
@@ -283,6 +317,18 @@ chk_gro_flag " - peer gro flag" $SRC off
283 317 chk_tso_flag " - tso flag" $SRC on
284 318 chk_tso_flag " - peer tso flag" $DST on
285 319 ip -n $NS_DST link set dev veth$DST up
320 + if [ -f "$YNL" ]; then
321 + chk_xdp_feature " - peer ndo-xmit" $SRC 1 ndo-xmit
322 + # make sure the peer flag is set before disabling gro while down
323 + ip netns exec $NS_DST ethtool -K veth$DST gro off
324 + ip netns exec $NS_DST ethtool -K veth$DST gro on
325 + chk_xdp_feature " - peer ndo-xmit re-armed" $SRC 1 ndo-xmit
326 + ip -n $NS_DST link set dev veth$DST down
327 + ip netns exec $NS_DST ethtool -K veth$DST gro off
328 + ip -n $NS_DST link set dev veth$DST up
329 + chk_xdp_feature " - peer ndo-xmit cleared" $SRC 0 ndo-xmit
330 + ip netns exec $NS_DST ethtool -K veth$DST gro on
331 + fi
286 332 ip netns exec $NS_SRC ethtool -K veth$SRC tx-udp-segmentation off
287 333 ip netns exec $NS_DST ethtool -K veth$DST rx-udp-gro-forwarding on
288 334 chk_gro " - aggregation with TSO off" 1
modified tools/testing/selftests/sched_ext/Makefile
@@ -165,6 +165,7 @@ auto-test-targets := \
165 165 create_dsq \
166 166 dequeue \
167 167 dequeue_iter \
168 + dequeue_remote \
168 169 enq_last_no_enq_fails \
169 170 ddsp_bogus_dsq_fail \
170 171 ddsp_vtimelocal_fail \
added tools/testing/selftests/sched_ext/dequeue_remote.bpf.c mode 100644
@@ -0,0 +1,270 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * Verify that ops.dequeue() is called when a task leaves the BPF scheduler's
4 + * custody by being moved to the local DSQ of a CPU other than the one whose
5 + * rq it's on (move_remote_task_to_local_dsq()).
6 + *
7 + * ops.enqueue() puts every task into custody and ops.dispatch() moves it to
8 + * the dispatching CPU's local DSQ, so most moves cross CPUs. With
9 + * @test_use_move_to_local, tasks are queued on a user DSQ and consumed with
10 + * scx_bpf_dsq_move_to_local(). Otherwise, they are queued in a BPF queue and
11 + * dispatched with SCX_DSQ_LOCAL_ON.
12 + *
13 + * Copyright (c) 2026 Google LLC.
14 + */
15 +
16 + #include <scx/common.bpf.h>
17 +
18 + #define SHARED_DSQ 0
19 + #define MAX_DISPATCH_POPS 8
20 +
21 + char _license[] SEC("license") = "GPL";
22 +
23 + UEI_DEFINE(uei);
24 +
25 + struct {
26 + __uint(type, BPF_MAP_TYPE_QUEUE);
27 + __uint(max_entries, 32768);
28 + __type(value, s32);
29 + } global_queue SEC(".maps");
30 +
31 + enum task_state {
32 + TASK_NONE = 0,
33 + TASK_ENQUEUED, /* in BPF custody, waiting for ops.dequeue() */
34 + TASK_DISPATCHED, /* left custody */
35 + };
36 +
37 + struct task_ctx {
38 + enum task_state state;
39 + s32 enq_cpu; /* scx_bpf_task_cpu() at ops.enqueue() */
40 + u64 enqueue_seq;
41 + };
42 +
43 + struct {
44 + __uint(type, BPF_MAP_TYPE_TASK_STORAGE);
45 + __uint(map_flags, BPF_F_NO_PREALLOC);
46 + __type(key, int);
47 + __type(value, struct task_ctx);
48 + } task_ctx_stor SEC(".maps");
49 +
50 + /* core_cookie only exists with CONFIG_SCHED_CORE */
51 + struct task_struct___core_sched {
52 + unsigned long core_cookie;
53 + } __attribute__((preserve_access_index));
54 +
55 + bool test_use_move_to_local;
56 +
57 + u64 enqueue_cnt, dequeue_cnt, dispatch_dequeue_cnt, change_dequeue_cnt;
58 + u64 remote_dispatch_cnt, remote_running_cnt, missed_dequeue_cnt;
59 + u64 core_sched_exec_dequeue_cnt;
60 +
61 + static struct task_ctx *lookup_task_ctx(struct task_struct *p)
62 + {
63 + return bpf_task_storage_get(&task_ctx_stor, p, 0, 0);
64 + }
65 +
66 + static bool task_has_core_cookie(struct task_struct *p)
67 + {
68 + struct task_struct___core_sched *t = (void *)p;
69 +
70 + if (!bpf_core_field_exists(t->core_cookie))
71 + return false;
72 + return BPF_CORE_READ(t, core_cookie);
73 + }
74 +
75 + s32 BPF_STRUCT_OPS(dequeue_remote_select_cpu, struct task_struct *p,
76 + s32 prev_cpu, u64 wake_flags)
77 + {
78 + /* no direct dispatch, always go through ops.enqueue() */
79 + return prev_cpu;
80 + }
81 +
82 + void BPF_STRUCT_OPS(dequeue_remote_enqueue, struct task_struct *p, u64 enq_flags)
83 + {
84 + struct task_ctx *tctx;
85 + s32 pid = p->pid;
86 +
87 + tctx = lookup_task_ctx(p);
88 + if (!tctx) {
89 + scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
90 + return;
91 + }
92 +
93 + /* the previous custody period must have ended with ops.dequeue() */
94 + if (tctx->state == TASK_ENQUEUED)
95 + scx_bpf_error("%d (%s): enqueue while in ENQUEUED state seq=%llu",
96 + p->pid, p->comm, tctx->enqueue_seq);
97 +
98 + /*
99 + * Mark @p as enqueued before making it visible to ops.dispatch() on
100 + * other CPUs, which skips queue entries of tasks not in ENQUEUED
101 + * state as stale.
102 + */
103 + tctx->state = TASK_ENQUEUED;
104 + tctx->enq_cpu = scx_bpf_task_cpu(p);
105 + tctx->enqueue_seq++;
106 +
107 + if (test_use_move_to_local) {
108 + scx_bpf_dsq_insert(p, SHARED_DSQ, SCX_SLICE_DFL, enq_flags);
109 + } else if (bpf_map_push_elem(&global_queue, &pid, 0)) {
110 + scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, enq_flags);
111 + tctx->state = TASK_DISPATCHED;
112 + tctx->enq_cpu = -1;
113 + goto out;
114 + }
115 +
116 + __sync_fetch_and_add(&enqueue_cnt, 1);
117 + out:
118 + scx_bpf_kick_cpu(scx_bpf_task_cpu(p), SCX_KICK_IDLE);
119 + }
120 +
121 + void BPF_STRUCT_OPS(dequeue_remote_dequeue, struct task_struct *p, u64 deq_flags)
122 + {
123 + struct task_ctx *tctx;
124 +
125 + __sync_fetch_and_add(&dequeue_cnt, 1);
126 +
127 + tctx = lookup_task_ctx(p);
128 + if (!tctx)
129 + return;
130 +
131 + /*
132 + * Only core scheduling can pick a task straight out of custody, and
133 + * only if the task has a core cookie. Otherwise, the custody exit was
134 + * missed when @p was inserted into a local DSQ and got deferred until
135 + * @p was picked.
136 + */
137 + if ((deq_flags & SCX_DEQ_CORE_SCHED_EXEC) && !task_has_core_cookie(p)) {
138 + __sync_fetch_and_add(&core_sched_exec_dequeue_cnt, 1);
139 + scx_bpf_error("%d (%s): late ops.dequeue() with SCX_DEQ_CORE_SCHED_EXEC (enq_cpu=%d cpu=%d seq=%llu)",
140 + p->pid, p->comm, tctx->enq_cpu,
141 + scx_bpf_task_cpu(p), tctx->enqueue_seq);
142 + }
143 +
144 + /* ops.dequeue() ends the custody period started by ops.enqueue() */
145 + if (tctx->state != TASK_ENQUEUED)
146 + scx_bpf_error("%d (%s): dequeue outside custody deq_flags=0x%llx state=%d seq=%llu",
147 + p->pid, p->comm, deq_flags, tctx->state,
148 + tctx->enqueue_seq);
149 +
150 + if (deq_flags & SCX_DEQ_SCHED_CHANGE) {
151 + __sync_fetch_and_add(&change_dequeue_cnt, 1);
152 + tctx->state = TASK_NONE;
153 + } else {
154 + __sync_fetch_and_add(&dispatch_dequeue_cnt, 1);
155 + tctx->state = TASK_DISPATCHED;
156 + }
157 + }
158 +
159 + void BPF_STRUCT_OPS(dequeue_remote_dispatch, s32 cpu, struct task_struct *prev)
160 + {
161 + struct task_ctx *tctx;
162 + struct task_struct *p;
163 + s32 pid;
164 + int i;
165 +
166 + if (test_use_move_to_local) {
167 + scx_bpf_dsq_move_to_local(SHARED_DSQ, 0);
168 + return;
169 + }
170 +
171 + /* pop past stale entries so that they don't leave this CPU idle */
172 + bpf_for(i, 0, MAX_DISPATCH_POPS) {
173 + if (bpf_map_pop_elem(&global_queue, &pid))
174 + return;
175 +
176 + p = bpf_task_from_pid(pid);
177 + if (!p)
178 + continue;
179 +
180 + /*
181 + * Entries are stale if @p left custody through a property
182 + * change dequeue or was dispatched from a duplicate entry.
183 + */
184 + tctx = lookup_task_ctx(p);
185 + if (!tctx || tctx->state != TASK_ENQUEUED) {
186 + bpf_task_release(p);
187 + continue;
188 + }
189 +
190 + if (bpf_cpumask_test_cpu(cpu, p->cpus_ptr)) {
191 + if (scx_bpf_task_cpu(p) != cpu)
192 + __sync_fetch_and_add(&remote_dispatch_cnt, 1);
193 + scx_bpf_dsq_insert(p, SCX_DSQ_LOCAL_ON | cpu,
194 + SCX_SLICE_DFL, 0);
195 + } else {
196 + scx_bpf_dsq_insert(p, SCX_DSQ_GLOBAL, SCX_SLICE_DFL, 0);
197 + }
198 +
199 + bpf_task_release(p);
200 + return;
201 + }
202 +
203 + /* out of pops with entries left, retry instead of idling this CPU */
204 + if (!bpf_map_peek_elem(&global_queue, &pid))
205 + scx_bpf_kick_cpu(cpu, SCX_KICK_IDLE);
206 + }
207 +
208 + void BPF_STRUCT_OPS(dequeue_remote_running, struct task_struct *p)
209 + {
210 + struct task_ctx *tctx;
211 +
212 + tctx = lookup_task_ctx(p);
213 + if (!tctx)
214 + return;
215 +
216 + /* tasks can only run from a local DSQ, i.e. after leaving custody */
217 + if (tctx->state == TASK_ENQUEUED) {
218 + __sync_fetch_and_add(&missed_dequeue_cnt, 1);
219 + scx_bpf_error("%d (%s): running without ops.dequeue() (enq_cpu=%d cpu=%d seq=%llu)",
220 + p->pid, p->comm, tctx->enq_cpu,
221 + scx_bpf_task_cpu(p), tctx->enqueue_seq);
222 + return;
223 + }
224 +
225 + if (tctx->enq_cpu >= 0 && tctx->enq_cpu != scx_bpf_task_cpu(p))
226 + __sync_fetch_and_add(&remote_running_cnt, 1);
227 + tctx->enq_cpu = -1;
228 + }
229 +
230 + s32 BPF_STRUCT_OPS(dequeue_remote_init_task, struct task_struct *p,
231 + struct scx_init_task_args *args)
232 + {
233 + struct task_ctx *tctx;
234 +
235 + tctx = bpf_task_storage_get(&task_ctx_stor, p, 0,
236 + BPF_LOCAL_STORAGE_GET_F_CREATE);
237 + if (!tctx)
238 + return -ENOMEM;
239 +
240 + /* task storage persists across attachments, start from scratch */
241 + tctx->state = TASK_NONE;
242 + tctx->enq_cpu = -1;
243 + tctx->enqueue_seq = 0;
244 +
245 + return 0;
246 + }
247 +
248 + s32 BPF_STRUCT_OPS_SLEEPABLE(dequeue_remote_init)
249 + {
250 + return scx_bpf_create_dsq(SHARED_DSQ, -1);
251 + }
252 +
253 + void BPF_STRUCT_OPS(dequeue_remote_exit, struct scx_exit_info *ei)
254 + {
255 + UEI_RECORD(uei, ei);
256 + }
257 +
258 + SEC(".struct_ops.link")
259 + struct sched_ext_ops dequeue_remote_ops = {
260 + .select_cpu = (void *)dequeue_remote_select_cpu,
261 + .enqueue = (void *)dequeue_remote_enqueue,
262 + .dequeue = (void *)dequeue_remote_dequeue,
263 + .dispatch = (void *)dequeue_remote_dispatch,
264 + .running = (void *)dequeue_remote_running,
265 + .init_task = (void *)dequeue_remote_init_task,
266 + .init = (void *)dequeue_remote_init,
267 + .exit = (void *)dequeue_remote_exit,
268 + .flags = SCX_OPS_ENQ_LAST,
269 + .name = "dequeue_remote",
270 + };
added tools/testing/selftests/sched_ext/dequeue_remote.c mode 100644
@@ -0,0 +1,204 @@
1 + // SPDX-License-Identifier: GPL-2.0
2 + /*
3 + * Verify that ops.dequeue() is called for tasks leaving BPF custody through
4 + * an SCX-internal cross-CPU migration (move_remote_task_to_local_dsq()).
5 + *
6 + * Copyright (c) 2026 Google LLC.
7 + */
8 + #define _GNU_SOURCE
9 + #include <stdio.h>
10 + #include <stdlib.h>
11 + #include <string.h>
12 + #include <unistd.h>
13 + #include <signal.h>
14 + #include <time.h>
15 + #include <sched.h>
16 + #include <bpf/bpf.h>
17 + #include <scx/common.h>
18 + #include <sys/wait.h>
19 + #include "scx_test.h"
20 + #include "dequeue_remote.bpf.skel.h"
21 +
22 + #define MAX_WORKERS 64
23 + #define RUN_MS 2000
24 +
25 + static int nr_cpus;
26 +
27 + static long long now_ms(void)
28 + {
29 + struct timespec ts;
30 +
31 + clock_gettime(CLOCK_MONOTONIC, &ts);
32 + return ts.tv_sec * 1000LL + ts.tv_nsec / 1000000;
33 + }
34 +
35 + /* mix of short bursts and sleeps to generate lots of enqueues and wakeups */
36 + static void worker_fn(int id)
37 + {
38 + long long end = now_ms() + RUN_MS;
39 + volatile unsigned long sum = 0;
40 +
41 + while (now_ms() < end) {
42 + unsigned long j;
43 +
44 + for (j = 0; j < 20000 + id * 1000; j++)
45 + sum += j;
46 + if (id & 1)
47 + usleep(100);
48 + else
49 + sched_yield();
50 + }
51 +
52 + exit(0);
53 + }
54 +
55 + static enum scx_test_status run_scenario(struct dequeue_remote *skel,
56 + bool use_move_to_local,
57 + const char *name)
58 + {
59 + enum scx_test_status ret = SCX_TEST_PASS;
60 + struct bpf_link *link;
61 + pid_t pids[MAX_WORKERS];
62 + int nr_workers, nr_forked, i;
63 +
64 + nr_workers = 2 * nr_cpus;
65 + if (nr_workers < 4)
66 + nr_workers = 4;
67 + if (nr_workers > MAX_WORKERS)
68 + nr_workers = MAX_WORKERS;
69 +
70 + skel->bss->test_use_move_to_local = use_move_to_local;
71 + skel->bss->enqueue_cnt = 0;
72 + skel->bss->dequeue_cnt = 0;
73 + skel->bss->dispatch_dequeue_cnt = 0;
74 + skel->bss->change_dequeue_cnt = 0;
75 + skel->bss->remote_dispatch_cnt = 0;
76 + skel->bss->remote_running_cnt = 0;
77 + skel->bss->missed_dequeue_cnt = 0;
78 + skel->bss->core_sched_exec_dequeue_cnt = 0;
79 + memset(&skel->data->uei, 0, sizeof(skel->data->uei));
80 +
81 + link = bpf_map__attach_struct_ops(skel->maps.dequeue_remote_ops);
82 + SCX_FAIL_IF(!link, "Failed to attach struct_ops for %s", name);
83 +
84 + fflush(stdout);
85 + fflush(stderr);
86 +
87 + for (nr_forked = 0; nr_forked < nr_workers; nr_forked++) {
88 + pid_t pid = fork();
89 +
90 + if (pid < 0) {
91 + SCX_ERR("Failed to fork worker %d", nr_forked);
92 + ret = SCX_TEST_FAIL;
93 + break;
94 + }
95 + if (pid == 0)
96 + worker_fn(nr_forked);
97 + pids[nr_forked] = pid;
98 + }
99 +
100 + /* on failure, kill the remaining workers but still reap them */
101 + for (i = 0; i < nr_forked; i++) {
102 + int status;
103 +
104 + if (ret != SCX_TEST_PASS)
105 + kill(pids[i], SIGKILL);
106 +
107 + if (waitpid(pids[i], &status, 0) != pids[i]) {
108 + SCX_ERR("Failed to wait for worker %d", i);
109 + ret = SCX_TEST_FAIL;
110 + } else if (ret == SCX_TEST_PASS && status != 0) {
111 + SCX_ERR("Worker %d exited with status %d", i, status);
112 + ret = SCX_TEST_FAIL;
113 + }
114 + }
115 +
116 + bpf_link__destroy(link);
117 +
118 + if (ret != SCX_TEST_PASS)
119 + return ret;
120 +
121 + printf("%s:\n", name);
122 + printf(" workers: %d\n", nr_workers);
123 + printf(" enqueues: %lu\n", (unsigned long)skel->bss->enqueue_cnt);
124 + printf(" dequeues: %lu (dispatch: %lu, property_change: %lu)\n",
125 + (unsigned long)skel->bss->dequeue_cnt,
126 + (unsigned long)skel->bss->dispatch_dequeue_cnt,
127 + (unsigned long)skel->bss->change_dequeue_cnt);
128 + if (!use_move_to_local)
129 + printf(" remote SCX_DSQ_LOCAL_ON dispatches: %lu\n",
130 + (unsigned long)skel->bss->remote_dispatch_cnt);
131 + printf(" ran on a CPU other than the enqueue CPU: %lu\n",
132 + (unsigned long)skel->bss->remote_running_cnt);
133 + printf(" ran without ops.dequeue(): %lu\n",
134 + (unsigned long)skel->bss->missed_dequeue_cnt);
135 + printf(" late SCX_DEQ_CORE_SCHED_EXEC dequeues: %lu\n",
136 + (unsigned long)skel->bss->core_sched_exec_dequeue_cnt);
137 +
138 + if (skel->data->uei.kind != EXIT_KIND(SCX_EXIT_UNREG))
139 + SCX_ERR("Scheduler exited with kind=%lld: %s",
140 + (long long)skel->data->uei.kind, skel->data->uei.msg);
141 + SCX_EQ(skel->data->uei.kind, EXIT_KIND(SCX_EXIT_UNREG));
142 +
143 + /* the test is meaningless if no task was moved across CPUs */
144 + SCX_GT(skel->bss->remote_running_cnt, 0);
145 + SCX_EQ(skel->bss->enqueue_cnt, skel->bss->dequeue_cnt);
146 +
147 + return SCX_TEST_PASS;
148 + }
149 +
150 + static enum scx_test_status setup(void **ctx)
151 + {
152 + struct dequeue_remote *skel;
153 + cpu_set_t cpus;
154 +
155 + SCX_FAIL_IF(sched_getaffinity(0, sizeof(cpus), &cpus),
156 + "Failed to get CPU affinity");
157 + nr_cpus = CPU_COUNT(&cpus);
158 + if (nr_cpus < 2) {
159 + fprintf(stderr, "Skipping: requires at least 2 usable CPUs\n");
160 + return SCX_TEST_SKIP;
161 + }
162 +
163 + skel = SCX_OPS_OPEN(dequeue_remote_ops, dequeue_remote);
164 + SCX_OPS_LOAD(skel, dequeue_remote_ops, dequeue_remote, uei);
165 +
166 + *ctx = skel;
167 +
168 + return SCX_TEST_PASS;
169 + }
170 +
171 + static enum scx_test_status run(void *ctx)
172 + {
173 + struct dequeue_remote *skel = ctx;
174 + enum scx_test_status status;
175 +
176 + status = run_scenario(skel, false,
177 + "BPF queue -> SCX_DSQ_LOCAL_ON | cpu");
178 + if (status != SCX_TEST_PASS)
179 + return status;
180 +
181 + status = run_scenario(skel, true,
182 + "user DSQ -> scx_bpf_dsq_move_to_local()");
183 + if (status != SCX_TEST_PASS)
184 + return status;
185 +
186 + return SCX_TEST_PASS;
187 + }
188 +
189 + static void cleanup(void *ctx)
190 + {
191 + struct dequeue_remote *skel = ctx;
192 +
193 + dequeue_remote__destroy(skel);
194 + }
195 +
196 + struct scx_test dequeue_remote_test = {
197 + .name = "dequeue_remote",
198 + .description = "Verify ops.dequeue() on SCX-internal cross-CPU migrations",
199 + .setup = setup,
200 + .run = run,
201 + .cleanup = cleanup,
202 + };
203 +
204 + REGISTER_SCX_TEST(&dequeue_remote_test)
modified tools/testing/selftests/tc-testing/tc-tests/filters/route.json
@@ -412,5 +412,51 @@
412 412 "teardown": [
413 413 "$TC qdisc del dev $DEV1 ingress"
414 414 ]
415 + },
416 + {
417 + "id": "4000",
418 + "name": "Change a wildcard route filter classid only (no routing attribute)",
419 + "category": [
420 + "filter",
421 + "route"
422 + ],
423 + "plugins": {
424 + "requires": "nsPlugin"
425 + },
426 + "setup": [
427 + "$TC qdisc add dev $DEV1 ingress",
428 + "$TC filter add dev $DEV1 parent ffff: protocol ip prio 100 route classid 1:1"
429 + ],
430 + "cmdUnderTest": "$TC filter change dev $DEV1 parent ffff: protocol ip prio 100 route classid 1:9",
431 + "expExitCode": "0",
432 + "verifyCmd": "$TC filter ls dev $DEV1 parent ffff:",
433 + "matchPattern": "fh 0xffff8000 flowid 1:9",
434 + "matchCount": "1",
435 + "teardown": [
436 + "$TC qdisc del dev $DEV1 ingress"
437 + ]
438 + },
439 + {
440 + "id": "907a",
441 + "name": "Try to change a route filter with no routing attribute and a non-wildcard handle",
442 + "category": [
443 + "filter",
444 + "route"
445 + ],
446 + "plugins": {
447 + "requires": "nsPlugin"
448 + },
449 + "setup": [
450 + "$TC qdisc add dev $DEV1 ingress",
451 + "$TC filter add dev $DEV1 parent ffff: protocol ip prio 100 route from 1 to 1 classid 1:1"
452 + ],
453 + "cmdUnderTest": "$TC filter change dev $DEV1 parent ffff: protocol ip prio 100 handle 0x10001 route classid 1:2",
454 + "expExitCode": "2",
455 + "verifyCmd": "$TC filter ls dev $DEV1 parent ffff:",
456 + "matchPattern": "fh 0x00010001 flowid 1:1 to 1 from 1",
457 + "matchCount": "1",
458 + "teardown": [
459 + "$TC qdisc del dev $DEV1 ingress"
460 + ]
415 461 }
416 462 ]
modified tools/testing/vma/tests/vma.c
@@ -40,7 +40,7 @@ static bool test_copy_vma(void)
40 40 vma = alloc_and_link_vma(&mm, 0x1000, 0x2000, 1, vma_flags);
41 41 vma_set_anonymous(vma);
42 42 vma_orig = vma;
43 - vma_new = copy_vma(&vma, 0x2000, 0x1000, 1, 1, &need_locks);
43 + vma_new = copy_vma(&vma, 0x2000, 0x1000, 1, 1, &need_locks, false);
44 44 ASSERT_EQ(vma_new, vma_orig);
45 45 ASSERT_EQ(vma, vma_orig);
46 46 ASSERT_EQ(vma_new->vm_start, 0x1000);
@@ -53,7 +53,7 @@ static bool test_copy_vma(void)
53 53 vma = alloc_and_link_vma(&mm, 0x2000, 0x3000, 2, vma_flags);
54 54 vma_set_anonymous(vma);
55 55 vma_orig = vma;
56 - vma_new = copy_vma(&vma, 0x1000, 0x1000, 2, 2, &need_locks);
56 + vma_new = copy_vma(&vma, 0x1000, 0x1000, 2, 2, &need_locks, false);
57 57 ASSERT_EQ(vma_new, vma_orig);
58 58 ASSERT_EQ(vma, vma_orig);
59 59 ASSERT_EQ(vma_new->vm_start, 0x1000);
@@ -71,7 +71,7 @@ static bool test_copy_vma(void)
71 71 vma = alloc_and_link_vma(&mm, 0x3000, 0x4000, 3, vma_flags);
72 72 vma_set_anonymous(vma);
73 73 vma_orig = vma;
74 - vma_new = copy_vma(&vma, 0x2000, 0x1000, 3, 3, &need_locks);
74 + vma_new = copy_vma(&vma, 0x2000, 0x1000, 3, 3, &need_locks, false);
75 75 ASSERT_NE(vma_new, vma_orig);
76 76 ASSERT_EQ(vma_new, vma);
77 77 ASSERT_EQ(vma_new->vm_start, 0x1000);
@@ -82,7 +82,7 @@ static bool test_copy_vma(void)
82 82 /* Move backwards and do not merge. */
83 83
84 84 vma = alloc_and_link_vma(&mm, 0x3000, 0x5000, 3, vma_flags);
85 - vma_new = copy_vma(&vma, 0, 0x2000, 0, 3, &need_locks);
85 + vma_new = copy_vma(&vma, 0, 0x2000, 0, 3, &need_locks, false);
86 86 ASSERT_NE(vma_new, vma);
87 87 ASSERT_EQ(vma_new->vm_start, 0);
88 88 ASSERT_EQ(vma_new->vm_end, 0x2000);
@@ -95,7 +95,7 @@ static bool test_copy_vma(void)
95 95
96 96 vma = alloc_and_link_vma(&mm, 0, 0x2000, 0, vma_flags);
97 97 vma_next = alloc_and_link_vma(&mm, 0x6000, 0x8000, 6, vma_flags);
98 - vma_new = copy_vma(&vma, 0x4000, 0x2000, 4, 4, &need_locks);
98 + vma_new = copy_vma(&vma, 0x4000, 0x2000, 4, 4, &need_locks, false);
99 99 vma_assert_attached(vma_new);
100 100
101 101 ASSERT_EQ(vma_new, vma_next);