6.12.119-rc1 review
Subsystems (3)
Greg Kroah-Hartman
maintainerPATCH 60/1756 hwmon: (chipcap2) Switch to guard() for mutext handling
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 232ba88182083b4410df41cf310c9a16b84e547e ]
Switch to guard() for mutex handling to simplify the code, getting rid of the 'ret = x, break; return ret;' construct and return the result of the operation instead.
Stable-dep-of: bed5f0c075eb ("hwmon: chipcap2: serialize access to the alarm indicators")
--- drivers/hwmon/chipcap2.c | 63 ++++++++++++---------------------------- 1 file changed, 18 insertions(+), 45 deletions(-)
drivers/hwmon/chipcap2.c +18 -45
@@ -13,6 +13,7 @@#include <linux/bitfield.h> #include <linux/bits.h> +#include <linux/cleanup.h> #include <linux/completion.h> #include <linux/delay.h> #include <linux/hwmon.h>
@@ -573,55 +574,40 @@ static int cc2_read(struct device *dev, enum hwmon_sensor_types type, u32 attr, int channel, long *val) { struct cc2_data *data = dev_get_drvdata(dev); -int ret =0 ; -mutex_lock (&data->dev_access_lock); +guard (mutex)(&data->dev_access_lock);switch (type) {case hwmon_temp: - ret =cc2_measurement (data, type, val); -break ; +return cc2_measurement (data, type, val);case hwmon_humidity:switch (attr) {case hwmon_humidity_input: - ret =cc2_measurement (data, type, val); -break ; +return cc2_measurement (data, type, val);case hwmon_humidity_min: - ret =cc2_get_reg_val (data,CC2_R_ALARM_L_ON , val); -break ; +return cc2_get_reg_val (data,CC2_R_ALARM_L_ON , val);case hwmon_humidity_min_hyst: - ret =cc2_get_reg_val (data,CC2_R_ALARM_L_OFF , val); -break ; +return cc2_get_reg_val (data,CC2_R_ALARM_L_OFF , val);case hwmon_humidity_max: - ret =cc2_get_reg_val (data,CC2_R_ALARM_H_ON , val); -break ; +return cc2_get_reg_val (data,CC2_R_ALARM_H_ON , val);case hwmon_humidity_max_hyst: - ret =cc2_get_reg_val (data,CC2_R_ALARM_H_OFF , val); -break ; +return cc2_get_reg_val (data,CC2_R_ALARM_H_OFF , val);case hwmon_humidity_min_alarm: - ret =cc2_humidity_min_alarm_status (data, val); -break ; +return cc2_humidity_min_alarm_status (data, val);case hwmon_humidity_max_alarm: - ret =cc2_humidity_max_alarm_status (data, val); -break ; +return cc2_humidity_max_alarm_status (data, val);default : - ret = -EOPNOTSUPP ; +return -EOPNOTSUPP ; } -break ;default : - ret = -EOPNOTSUPP ; +return -EOPNOTSUPP ; } - -mutex_unlock (&data->dev_access_lock); - -return ret; }static int cc2_write (struct device *dev,enum hwmon_sensor_types type,u32 attr,int channel,long val) {struct cc2_data *data =dev_get_drvdata (dev); -int ret;u16 arg;u8 cmd;
@@ -631,41 +617,28 @@ static int cc2_write(struct device *dev, enum hwmon_sensor_types type, u32 attr,if (val <0 || val >CC2_RH_MAX )return -EINVAL ; -mutex_lock (&data->dev_access_lock); +guard (mutex)(&data->dev_access_lock);switch (attr) {case hwmon_humidity_min: cmd =CC2_W_ALARM_L_ON ; arg =cc2_rh_to_reg (val); - ret =cc2_write_reg (data, cmd, arg); -break ; - +return cc2_write_reg (data, cmd, arg);case hwmon_humidity_min_hyst: cmd =CC2_W_ALARM_L_OFF ; arg =cc2_rh_to_reg (val); - ret =cc2_write_reg (data, cmd, arg); -break ; - +return cc2_write_reg (data, cmd, arg);case hwmon_humidity_max: cmd =CC2_W_ALARM_H_ON ; arg =cc2_rh_to_reg (val); - ret =cc2_write_reg (data, cmd, arg); -break ; - +return cc2_write_reg (data, cmd, arg);case hwmon_humidity_max_hyst: cmd =CC2_W_ALARM_H_OFF ; arg =cc2_rh_to_reg (val); - ret =cc2_write_reg (data, cmd, arg); -break ; - +return cc2_write_reg (data, cmd, arg);default : - ret = -EOPNOTSUPP ; -break ; +return -EOPNOTSUPP ; } - -mutex_unlock (&data->dev_access_lock); - -return ret; }static int cc2_get_irqs (struct cc2_data *data,struct device *dev)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 61/1756 hwmon: (chipcap2) Drop unnecessary include files
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 4c8d758d4ebff3780d09599f2c8db5d6af3ca2af ]
The driver does not perform any locking, does not execute or use any sleep related functionality, and does not allocate memory. Drop the unnecessary include files.
Stable-dep-of: bed5f0c075eb ("hwmon: chipcap2: serialize access to the alarm indicators")
--- drivers/hwmon/chipcap2.c | 7 ------- 1 file changed, 7 deletions(-)
drivers/hwmon/chipcap2.c +0 -7
@@ -82,7 +82,6 @@ struct cc2_data {struct completion complete;struct device *hwmon;struct i2c_client *client; -struct mutex dev_access_lock;/* device access lock */ struct regulator *regulator;const char *name;int irq_ready;
@@ -575,8 +574,6 @@ static int cc2_read(struct device *dev, enum hwmon_sensor_types type, u32 attr, {struct cc2_data *data =dev_get_drvdata (dev); -guard (mutex)(&data->dev_access_lock); -switch (type) {case hwmon_temp:return cc2_measurement (data, type, val);
@@ -617,8 +614,6 @@ static int cc2_write(struct device *dev, enum hwmon_sensor_types type, u32 attr,if (val <0 || val >CC2_RH_MAX )return -EINVAL ; -guard (mutex)(&data->dev_access_lock); -switch (attr) {case hwmon_humidity_min: cmd =CC2_W_ALARM_L_ON ;
@@ -712,8 +707,6 @@ static int cc2_probe(struct i2c_client *client)i2c_set_clientdata (client, data); -mutex_init (&data->dev_access_lock); - data->client = client; data->regulator =devm_regulator_get_exclusive (dev,"vdd" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 62/1756 hwmon: chipcap2: serialize access to the alarm indicators
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit bed5f0c075eb99442fca6a61c009a32752eceda2 ]
low_alarm and high_alarm are accessed from the threaded interrupt handlers and from sysfs without any locking, which can lead to lost alarms.
Add a mutex to serialize the access to the alarm indicators and to process_irqs, which the handlers use to decide whether an interrupt belongs to an ongoing operation.
--- drivers/hwmon/chipcap2.c | 58 +++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 21 deletions(-)
drivers/hwmon/chipcap2.c +37 -21
@@ -20,6 +20,7 @@#include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/irq.h> +#include <linux/mutex.h> #include <linux/module.h> #include <linux/unaligned.h> #include <linux/regulator/consumer.h>
@@ -88,6 +89,8 @@ struct cc2_data {int irq_low;int irq_high;bool process_irqs; +/* protects process_irqs and the alarm indicators */ +struct mutex irq_lock;bool regulator_enabled; };
@@ -119,7 +122,8 @@ static int cc2_enable(struct cc2_data *data)/* exclusive regulator, check in case a disable failed */ if (data->regulator_enabled) { - data->process_irqs = true; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = true;return 0 ; }
@@ -134,7 +138,8 @@ static int cc2_enable(struct cc2_data *data)usleep_range (CC2_STARTUP_TIME_US ,CC2_STARTUP_TIME_US +125 ); - data->process_irqs = true; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = true;return 0 ; }
@@ -151,7 +156,8 @@ static void cc2_disable(struct cc2_data *data)synchronize_irq (data->irq_high);/* ignore alarms triggered by voltage toggling when powering up */ - data->process_irqs = false; +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = false;/* exclusive regulator, check in case an enable failed */ if (!data->regulator_enabled)
@@ -507,10 +513,12 @@ static irqreturn_t cc2_low_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) { -hwmon_notify_event (cc2->hwmon, hwmon_humidity, - hwmon_humidity_min_alarm,0 ); - cc2->rh_alarm.low_alarm = true; + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) { +hwmon_notify_event (cc2->hwmon, hwmon_humidity, + hwmon_humidity_min_alarm,0 ); + cc2->rh_alarm.low_alarm = true; + } }return IRQ_HANDLED ;
@@ -520,10 +528,12 @@ static irqreturn_t cc2_high_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) { -hwmon_notify_event (cc2->hwmon, hwmon_humidity, - hwmon_humidity_max_alarm,0 ); - cc2->rh_alarm.high_alarm = true; + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) { +hwmon_notify_event (cc2->hwmon, hwmon_humidity, + hwmon_humidity_max_alarm,0 ); + cc2->rh_alarm.high_alarm = true; + } }return IRQ_HANDLED ;
@@ -539,11 +549,13 @@ static int cc2_humidity_min_alarm_status(struct cc2_data *data, long *val)if (ret <0 )return ret; -if (data->rh_alarm.low_alarm) { - *val = (measurement < min_hyst) ?1 :0 ; - data->rh_alarm.low_alarm = *val; - }else { - *val =0 ; + scoped_guard(mutex, &data->irq_lock) { +if (data->rh_alarm.low_alarm) { + *val = (measurement < min_hyst) ?1 :0 ; + data->rh_alarm.low_alarm = *val; + }else { + *val =0 ; + } }return 0 ;
@@ -559,11 +571,13 @@ static int cc2_humidity_max_alarm_status(struct cc2_data *data, long *val)if (ret <0 )return ret; -if (data->rh_alarm.high_alarm) { - *val = (measurement > max_hyst) ?1 :0 ; - data->rh_alarm.high_alarm = *val; - }else { - *val =0 ; + scoped_guard(mutex, &data->irq_lock) { +if (data->rh_alarm.high_alarm) { + *val = (measurement > max_hyst) ?1 :0 ; + data->rh_alarm.high_alarm = *val; + }else { + *val =0 ; + } }return 0 ;
@@ -707,6 +721,8 @@ static int cc2_probe(struct i2c_client *client)i2c_set_clientdata (client, data); +mutex_init (&data->irq_lock); + data->client = client; data->regulator =devm_regulator_get_exclusive (dev,"vdd" );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 63/1756 hwmon: chipcap2: synchronize ready IRQ state
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Javier Carrasco <[email protected]>
[ Upstream commit 8c02722be2caa6604a837b81faeaba78250eda4a ]
The ready IRQ handler can race with reinit_completion() in the enable path. In particular, a handler from an earlier operation can complete the completion after it is reset for a new operation.
Use irq_lock to serialize access to the completion and process_irqs. Disable IRQ processing and synchronize any running handler before resetting the completion for a new operation.
--- drivers/hwmon/chipcap2.c | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-)
drivers/hwmon/chipcap2.c +17 -5
@@ -120,6 +120,16 @@ static int cc2_enable(struct cc2_data *data) {int ret; +if (data->irq_ready >0 ) { +scoped_guard (mutex, &data->irq_lock) + data->process_irqs = false; + +synchronize_irq (data->irq_ready); + + scoped_guard(mutex, &data->irq_lock) +reinit_completion (&data->complete); + } +/* exclusive regulator, check in case a disable failed */ if (data->regulator_enabled) {scoped_guard (mutex, &data->irq_lock)
@@ -127,9 +137,6 @@ static int cc2_enable(struct cc2_data *data)return 0 ; } -/* clear any pending completion */ -try_wait_for_completion (&data->complete); - ret =regulator_enable (data->regulator);if (ret <0 )return ret;
@@ -159,6 +166,9 @@ static void cc2_disable(struct cc2_data *data)scoped_guard (mutex, &data->irq_lock) data->process_irqs = false; +if (data->irq_ready >0 ) +synchronize_irq (data->irq_ready); +/* exclusive regulator, check in case an enable failed */ if (!data->regulator_enabled)return ;
@@ -503,8 +513,10 @@ static irqreturn_t cc2_ready_interrupt(int irq, void *data) {struct cc2_data *cc2 = data; -if (cc2->process_irqs) -complete (&cc2->complete); + scoped_guard(mutex, &cc2->irq_lock) { +if (cc2->process_irqs) +complete (&cc2->complete); + }return IRQ_HANDLED ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 64/1756 ksmbd: do not read past the DACL in the access denied debug message
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Bridges <[email protected]>
[ Upstream commit 8296a64df5448548f410fb246c1d88a93609602b ]
When smb_check_perm_dacl() falls back to the POSIX ACL and then denies the request, its debug message prints the access mask of the ACE that the second DACL walk stopped at. On that path the walk ran to the end of the DACL, so the pointer is one past the last ACE. If the DACL is the last part of the stored security descriptor, the message reads 4 bytes past the buffer, and KASAN reports a slab-out-of-bounds read in smb_check_perm_dacl().
Print the requested and allowed masks instead. They are what the check compares.
--- fs/smb/server/smbacl.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/server/smbacl.c +2 -2
@@ -1650,8 +1650,8 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, check_access_bits:if (granted & ~(access_bits |FILE_READ_ATTRIBUTES |READ_CONTROL |WRITE_DAC |DELETE )) { -ksmbd_debug (SMB ,"Access denied with winACL, granted : %x, access_req : %x\n" , - granted,le32_to_cpu (ace->access_req)); +ksmbd_debug (SMB ,"Access denied with winACL, requested : %x, allowed : %x\n" , + granted, access_bits); rc = -EACCES ; goto err_out; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 65/1756 cipso: stop modifying live ip_options_rcu
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jann Horn <[email protected]>
[ Upstream commit 1f2c5183fc0902892648f0453e38c0951cef3fec ]
cipso_v4_delopt() operates on the ip_options_rcu of a socket or a request socket, and tries to remove CIPSO options from the middle by moving all subsequent options.
That's not allowed - ip_options_rcu can be read locklessly and must always be consistent. For example, ip_options_undo() reads trusted offsets and length values from the options buffer.
Fix it by doing the modification in a copy.
The core change is in cipso_v4_delopt(), the rest is ugly plumbing to propagate memory allocation failures.
Triggering this bug requires that the system is configured to use CIPSO. (Setting up CIPSO requires privileges in init_user_ns.)
--- include/net/cipso_ipv4.h | 11 ++++++----- include/net/netlabel.h | 11 ++++++----- net/ipv4/cipso_ipv4.c | 16 +++++++++++++--- net/netlabel/netlabel_kapi.c | 24 ++++++++++-------------- security/selinux/netlabel.c | 5 +++-- security/smack/smack_lsm.c | 14 +++++++++----- 6 files changed, 47 insertions(+), 34 deletions(-)
include/net/cipso_ipv4.h +6 -5
@@ -185,12 +185,12 @@ int cipso_v4_sock_setattr(struct sock *sk,const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void cipso_v4_sock_delattr (struct sock *sk); +int cipso_v4_sock_delattr (struct sock *sk);int cipso_v4_sock_getattr (struct sock *sk,struct netlbl_lsm_secattr *secattr);int cipso_v4_req_setattr (struct request_sock *req,const struct cipso_v4_doi *doi_def,const struct netlbl_lsm_secattr *secattr); -void cipso_v4_req_delattr (struct request_sock *req); +int cipso_v4_req_delattr (struct request_sock *req);int cipso_v4_skbuff_setattr (struct sk_buff *skb,const struct cipso_v4_doi *doi_def,const struct netlbl_lsm_secattr *secattr);
@@ -221,8 +221,9 @@ static inline int cipso_v4_sock_setattr(struct sock *sk,return -ENOSYS ; } -static inline void cipso_v4_sock_delattr (struct sock *sk) +static inline int cipso_v4_sock_delattr (struct sock *sk) { +return 0 ; } static inline int cipso_v4_sock_getattr(struct sock *sk,
@@ -238,9 +239,9 @@ static inline int cipso_v4_req_setattr(struct request_sock *req,return -ENOSYS ; } -static inline void cipso_v4_req_delattr (struct request_sock *req) +static inline int cipso_v4_req_delattr (struct request_sock *req) { -return ; +return 0 ; } static inline int cipso_v4_skbuff_setattr(struct sk_buff *skb,
include/net/netlabel.h +6 -5
@@ -476,7 +476,7 @@ int netlbl_sock_setattr(struct sock *sk,u16 family, const struct netlbl_lsm_secattr *secattr, bool sk_locked); -void netlbl_sock_delattr (struct sock *sk); +int netlbl_sock_delattr (struct sock *sk);int netlbl_sock_getattr (struct sock *sk,struct netlbl_lsm_secattr *secattr); int netlbl_conn_setattr(struct sock *sk,
@@ -484,7 +484,7 @@ int netlbl_conn_setattr(struct sock *sk, const struct netlbl_lsm_secattr *secattr);int netlbl_req_setattr (struct request_sock *req,const struct netlbl_lsm_secattr *secattr); -void netlbl_req_delattr (struct request_sock *req); +int netlbl_req_delattr (struct request_sock *req);int netlbl_skbuff_setattr (struct sk_buff *skb,u16 family,const struct netlbl_lsm_secattr *secattr);
@@ -625,8 +625,9 @@ static inline int netlbl_sock_setattr(struct sock *sk, {return -ENOSYS ; } -static inline void netlbl_sock_delattr (struct sock *sk) +static inline int netlbl_sock_delattr (struct sock *sk) { +return 0 ; }static inline int netlbl_sock_getattr (struct sock *sk,struct netlbl_lsm_secattr *secattr)
@@ -644,9 +645,9 @@ static inline int netlbl_req_setattr(struct request_sock *req, {return -ENOSYS ; } -static inline void netlbl_req_delattr (struct request_sock *req) +static inline int netlbl_req_delattr (struct request_sock *req) { -return ; +return 0 ; } static inline int netlbl_skbuff_setattr(struct sk_buff *skb, u16 family,
net/ipv4/cipso_ipv4.c +13 -3
@@ -2006,11 +2006,16 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)if (!opt || opt->opt.cipso ==0 )return 0 ;if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) { +struct ip_options_rcu *old_opt = opt;u8 cipso_len;u8 cipso_off;unsigned char *cipso_ptr;int optlen_new; +/* ip_options_rcu must not be modified in place, use a copy */ + opt =kmemdup (opt,sizeof (*opt) + opt->opt.optlen,GFP_ATOMIC ); +if (!opt) +return -ENOMEM ; cipso_off = opt->opt.cipso -sizeof (struct iphdr ); cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1 ];
@@ -2038,6 +2043,8 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)memset (&opt->opt.__data[optlen_new],IPOPT_END , opt->opt.optlen - optlen_new); +rcu_assign_pointer (*opt_ptr, opt); +kfree_rcu (old_opt, rcu); }else {/* only the cipso option was present on the socket so we can * remove the entire option struct */
@@ -2057,7 +2064,7 @@ static int cipso_v4_delopt(struct ip_options_rcu __rcu **opt_ptr)* Removes the CIPSO option from a socket, if present. * */ -void cipso_v4_sock_delattr (struct sock *sk) +int cipso_v4_sock_delattr (struct sock *sk) {struct inet_sock *sk_inet;int hdr_delta;
@@ -2070,6 +2077,7 @@ void cipso_v4_sock_delattr(struct sock *sk) sk_conn->icsk_ext_hdr_len -= hdr_delta; sk_conn->icsk_sync_mss (sk, sk_conn->icsk_pmtu_cookie); } +return (hdr_delta <0 ) ? hdr_delta :0 ; }/**
@@ -2080,9 +2088,11 @@ void cipso_v4_sock_delattr(struct sock *sk)* Removes the CIPSO option from a request socket, if present. * */ -void cipso_v4_req_delattr (struct request_sock *req) +int cipso_v4_req_delattr (struct request_sock *req) { -cipso_v4_delopt (&inet_rsk (req)->ireq_opt); +int hdr_delta =cipso_v4_delopt (&inet_rsk (req)->ireq_opt); + +return (hdr_delta <0 ) ? hdr_delta :0 ; }/**
net/netlabel/netlabel_kapi.c +10 -14
@@ -1045,18 +1045,18 @@ int netlbl_sock_setattr(struct sock *sk,* ensuring that @sk is locked. * */ -void netlbl_sock_delattr (struct sock *sk) +int netlbl_sock_delattr (struct sock *sk) {switch (sk->sk_family) {case AF_INET : -cipso_v4_sock_delattr (sk); -break ; +return cipso_v4_sock_delattr (sk);#if IS_ENABLED (CONFIG_IPV6 )case AF_INET6 :calipso_sock_delattr (sk);break ;#endif /* IPv6 */ } +return 0 ; }/**
@@ -1156,8 +1156,7 @@ int netlbl_conn_setattr(struct sock *sk,case NETLBL_NLTYPE_UNLABELED :/* just delete the protocols we support for right now * but we could remove other protocols if needed */ -netlbl_sock_delattr (sk); - ret_val =0 ; + ret_val =netlbl_sock_delattr (sk);break ;default : ret_val = -ENOENT ;
@@ -1185,8 +1184,7 @@ int netlbl_conn_setattr(struct sock *sk,case NETLBL_NLTYPE_UNLABELED :/* just delete the protocols we support for right now * but we could remove other protocols if needed */ -netlbl_sock_delattr (sk); - ret_val =0 ; + ret_val =netlbl_sock_delattr (sk);break ;default : ret_val = -ENOENT ;
@@ -1234,8 +1232,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->cipso, secattr);break ;case NETLBL_NLTYPE_UNLABELED : -netlbl_req_delattr (req); - ret_val =0 ; + ret_val =netlbl_req_delattr (req);break ;default : ret_val = -ENOENT ;
@@ -1255,8 +1252,7 @@ int netlbl_req_setattr(struct request_sock *req, entry->calipso, secattr);break ;case NETLBL_NLTYPE_UNLABELED : -netlbl_req_delattr (req); - ret_val =0 ; + ret_val =netlbl_req_delattr (req);break ;default : ret_val = -ENOENT ;
@@ -1280,18 +1276,18 @@ int netlbl_req_setattr(struct request_sock *req,* Remove all the NetLabel labeling from @req. * */ -void netlbl_req_delattr (struct request_sock *req) +int netlbl_req_delattr (struct request_sock *req) {switch (req->rsk_ops->family) {case AF_INET : -cipso_v4_req_delattr (req); -break ; +return cipso_v4_req_delattr (req);#if IS_ENABLED (CONFIG_IPV6 )case AF_INET6 :calipso_req_delattr (req);break ;#endif /* IPv6 */ } +return 0 ; }/**
security/selinux/netlabel.c +3 -2
@@ -557,9 +557,10 @@ static int selinux_netlbl_socket_connect_helper(struct sock *sk,* is set to AF_UNSPEC, if that is what is happening we want to reset * the socket */ if (addr->sa_family ==AF_UNSPEC ) { -netlbl_sock_delattr (sk); + rc =netlbl_sock_delattr (sk); +if (rc) +return rc; sksec->nlbl_state =NLBL_REQSKB ; - rc =0 ;return rc; } secattr =selinux_netlbl_sock_genattr (sk);
security/smack/smack_lsm.c +9 -5
@@ -2665,22 +2665,26 @@ static int smack_netlbl_add(struct sock *sk)* * Remove the outbound smack value from a socket */ -static void smack_netlbl_delete (struct sock *sk) +static int smack_netlbl_delete (struct sock *sk) {struct socket_smack *ssp =smack_sock (sk); +int rc;/* * Take the label off the socket if one is set. */ if (ssp->smk_state !=SMK_NETLBL_LABELED ) -return ; +return 0 ;local_bh_disable ();bh_lock_sock_nested (sk); -netlbl_sock_delattr (sk); + rc =netlbl_sock_delattr (sk);bh_unlock_sock (sk);local_bh_enable (); +if (rc) +return rc; ssp->smk_state =SMK_NETLBL_UNLABELED ; +return 0 ; }/**
@@ -2720,7 +2724,7 @@ static int smk_ipv4_check(struct sock *sk, struct sockaddr_in *sap)* Clear the socket netlabel if it's set. */ if (!rc) -smack_netlbl_delete (sk); + rc =smack_netlbl_delete (sk); }rcu_read_unlock ();
@@ -4564,7 +4568,7 @@ static int smack_inet_conn_request(const struct sock *sk, struct sk_buff *skb,if (hskp ==NULL ) rc =netlbl_req_setattr (req, &ssp->smk_out->smk_netlabel);else -netlbl_req_delattr (req); + rc =netlbl_req_delattr (req);return rc; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 66/1756 Revert "x86/mm/pat: Use pr_warn() for early W^X warnings"
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
This reverts commit 091c44b2d3c3cdc943f0a1fdfe63f210cb1da0c4.
--- arch/x86/mm/pat/set_memory.c | 15 --------------- 1 file changed, 15 deletions(-)
arch/x86/mm/pat/set_memory.c +0 -15
@@ -647,21 +647,6 @@ static inline pgprot_t verify_rwx(pgprot_t old, pgprot_t new, unsigned long starreturn new; end = start + npg *PAGE_SIZE -1 ; - -/* -* If the kernel text is still RWX, gently complain, this could be a -* false positive. -* Once debug_checkwx() becomes mandatory for CONFIG_STRICT_KERNEL_RWX, -* the warning can be removed completely. -*/ -if (!kernel_set_to_readonly) { -pr_warn_once ("CPA detected W^X violation: %016llx -> %016llx range: 0x%016lx - 0x%016lx PFN %lx\n" , - (unsigned long long )pgprot_val (old), - (unsigned long long )pgprot_val (new), - start, end, pfn); -return new; - } - WARN_ONCE(1, "CPA detected W^X violation: %016llx -> %016llx range: 0x%016lx - 0x%016lx PFN %lx\n", (unsigned long long)pgprot_val(old), (unsigned long long)pgprot_val(new),
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 67/1756 Revert "x86/mm/pat: Fix effective RW computation in lookup_address_in_pgd_attr()"
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
This reverts commit 11d1ba991c0754b2c3c1e31aa63b0818afc6e4f7.
--- arch/x86/mm/pat/set_memory.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
arch/x86/mm/pat/set_memory.c +4 -4
@@ -682,7 +682,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address, *level =PG_LEVEL_512G ; *nx |=pgd_flags (*pgd) & _PAGE_NX; - *rw &= !!(pgd_flags (*pgd) & _PAGE_RW); + *rw &=pgd_flags (*pgd) & _PAGE_RW; p4d =p4d_offset (pgd, address);if (p4d_none (*p4d))
@@ -693,7 +693,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address, *level =PG_LEVEL_1G ; *nx |=p4d_flags (*p4d) & _PAGE_NX; - *rw &= !!(p4d_flags (*p4d) & _PAGE_RW); + *rw &=p4d_flags (*p4d) & _PAGE_RW; pud =pud_offset (p4d, address);if (pud_none (*pud))
@@ -704,7 +704,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address, *level =PG_LEVEL_2M ; *nx |=pud_flags (*pud) & _PAGE_NX; - *rw &= !!(pud_flags (*pud) & _PAGE_RW); + *rw &=pud_flags (*pud) & _PAGE_RW; pmd =pmd_offset (pud, address);if (pmd_none (*pmd))
@@ -715,7 +715,7 @@ pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address, *level =PG_LEVEL_4K ; *nx |=pmd_flags (*pmd) & _PAGE_NX; - *rw &= !!(pmd_flags (*pmd) & _PAGE_RW); + *rw &=pmd_flags (*pmd) & _PAGE_RW;return pte_offset_kernel (pmd, address); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 68/1756 mm/vma: avoid spurious write locks when mm->mm_lock_seq overflows
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lorenzo Stoakes (ARM) <[email protected]>
[ Upstream commit 7135a05838e85845e1bbf6caa6596a7e3b791a40 ]
So far the assumption has been that mm->mm_lock_seq overflow is benign, resulting only in readers spuriously falling back to the mmap lock, however it turns out that this was an unsafe assumption.
If a VMA can be spuriously considered write locked that means read lock exclusion does not take place, and thus a VMA can end up write-locked with concurrent readers.
Since overflow only occurs every 2^31 write lock/unlock cycles, resolve the issue by resetting every VMA's vma->vm_lock_seq each time such an overflow occurs.
This is done in vma_end_write_all(), which is called when the mmap write lock is released, i.e. in mmap_write_unlock() and mmap_write_downgrade().
Care must be taken, as resetting the sequence count at overflow means changing the seqcount of VMAs which are already attached and observable.
The mm's seqcount is guaranteed to be odd when a write lock is held, and thus any write locked VMA will have an odd seqcount assigned.
Therefore resetting to an even value prevents spurious write locks, since these can only occur with the mmap write lock held, at which point the mmap seqcount will be odd.
However, vma_start_read() also checks vma->vm_lock_seq == mm->mm_lock_seq, bailing if so (indicating a write lock).
This would cause any even reset value chosen to prevent VMA read locks from being taken - avoid this by also checking whether the VMA seqcount is odd before bailing on the read lock.
So far, vma->vm_lock_seq has defaulted to UINT_MAX, but this has been unnecessary since commit e5e7fb278e59 ("mm: convert mm_lock_seq to a proper seqcount"), since this is assigned when the VMA is still detached, and cannot be observed.
Therefore perform both reset and initialisation of vma->vm_lock_seq by simply setting vma->vm_lock_seq to zero.
The reset, performed in __mm_reset_vma_seqcounts(), only needs to WRITE_ONCE() the value.
However the read of vma->vm_lock_seq in vma_start_read() needs to have acquire semantics to pair with the smp_wmb() in do_raw_write_seqcount_end() so a reader reading a reset value also observes VMA modifications made under the write lock.
Since all VMA write locks were just released and the mmap write lock is still held, there are no concurrent VMA writers.
Concurrent VMA readers are unaffected. New VMA readers observe either zero, never a write lock, or the prior seqcount, behaving as before the reset.
Since this only occurs every 2^31 write lock/unlock cycles, the time taken to update all VMAs is considered to be acceptable.
Also update comments to reflect the change.
User facing effects are - dangerous races that could cause memory corruption or NULL pointer derefences (especially on page table traversal) are avoided.
--- include/linux/mm.h | 46 ++++++++++++++++++++++++++++++++------- include/linux/mm_types.h | 13 +++++++---- include/linux/mmap_lock.h | 16 ++++++++++++++ kernel/fork.c | 2 +- mm/mmap_lock.c | 39 +++++++++++++++++++++++++++++++++ 5 files changed, 103 insertions(+), 13 deletions(-)
include/linux/mm.h +38 -8
@@ -684,6 +684,22 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}#endif /* CONFIG_NUMA_BALANCING */ #ifdef CONFIG_PER_VMA_LOCK +/* Do the VMA, mm seqcounts indicate the VMA is write locked? */ +static inline bool vma_seqcount_is_write_locked (unsigned int vma_seq, +unsigned int mm_seq) +{ +/* VMA and mm sequence numbers must match for a write lock. */ +if (vma_seq != mm_seq) +return false; + +/* +* The VMA seqcount is always odd if locked. An even value can only be +* the zero assigned on allocation or stored by +* __mm_reset_vma_seqcounts(), never a write lock. +*/ +return vma_seq &1 ; +} +/* * Try to read-lock a vma. The function is allowed to occasionally yield false * locked result to avoid performance overhead, in which case we fall back to
@@ -691,6 +707,9 @@ static inline void vma_numab_state_free(struct vm_area_struct *vma) {}*/ static inline bool vma_start_read (struct vm_area_struct *vma) { +unsigned int vma_seq; +unsigned int mm_seq; +/* * Check before locking. A race might cause false locked result. * We can use READ_ONCE() for the mm_lock_seq here, and don't need
@@ -698,24 +717,35 @@ static inline bool vma_start_read(struct vm_area_struct *vma)* we don't rely on for anything - the mm_lock_seq read against which we * need ordering is below. */ -if (READ_ONCE (vma->vm_lock_seq) ==READ_ONCE (vma->vm_mm->mm_lock_seq.sequence)) + vma_seq =READ_ONCE (vma->vm_lock_seq); + mm_seq =READ_ONCE (vma->vm_mm->mm_lock_seq.sequence); +if (vma_seqcount_is_write_locked (vma_seq, mm_seq))return false;if (unlikely (down_read_trylock (&vma->vm_lock->lock) ==0 ))return false;/* -* Overflow might produce false locked result. -* False unlocked result is impossible because we modify and check +* False unlocked result is impossible because a write lock sets * vma->vm_lock_seq under vma->vm_lock protection and mm->mm_lock_seq * modification invalidates all existing locks. * -* We must use ACQUIRE semantics for the mm_lock_seq so that if we are -* racing with vma_end_write_all(), we only start reading from the VMA -* after it has been unlocked. -* This pairs with RELEASE semantics in vma_end_write_all(). +* ACQUIRE semantics are required for both reads. +* +* __mm_reset_vma_seqcounts() might reset vma->vm_lock_seq to zero +* after an overflow. A reader observing that zero must also observe +* the VMA modifications made under the write lock which just ended, so +* the ACQUIRE pairs with the smp_wmb() in do_raw_write_seqcount_end() +* that precedes the reset stores. +* +* The ACQUIRE semantics for the mm_lock_seq read is required so that, +* if we are racing with vma_end_write_all(), we only start reading from +* the VMA after it has been unlocked. This pairs with the RELEASE +* semantics in vma_end_write_all(). */ -if (unlikely (vma->vm_lock_seq ==raw_read_seqcount (&vma->vm_mm->mm_lock_seq))) { + vma_seq =smp_load_acquire (&vma->vm_lock_seq); + mm_seq =raw_read_seqcount (&vma->vm_mm->mm_lock_seq); +if (unlikely (vma_seqcount_is_write_locked (vma_seq, mm_seq))) {up_read (&vma->vm_lock->lock);return false; }
include/linux/mm_types.h +9 -4
@@ -750,15 +750,20 @@ struct vm_area_struct {* Can only be written (using WRITE_ONCE()) while holding both: * - mmap_lock (in write mode) * - vm_lock->lock (in write mode) +* The one exception is __mm_reset_vma_seqcounts(), which stores zero +* (an even value, which can never indicate a write lock) under the +* mmap write lock alone once the mm seqcount has wrapped, so a reader +* holding only vm_lock->lock may observe the value change from odd to +* zero. * Can be read reliably while holding one of: * - mmap_lock (in read or write mode) -* - vm_lock->lock (in read or write mode) +* - vm_lock->lock (in write mode) * Can be read unreliably (using READ_ONCE()) for pessimistic bailout * while holding nothing (except RCU to keep the VMA struct allocated). * -* This sequence counter is explicitly allowed to overflow; sequence -* counter reuse can only lead to occasional unnecessary use of the -* slowpath. +* Assigned the (odd) mm seqcount on write lock and not updated on +* unlock, so a stale value would alias the mm seqcount again 2^31 write +* lock/unlock cycles later. The reset described above prevents this. */ unsigned int vm_lock_seq;/* Unstable RCU readers are allowed to read this. */
include/linux/mmap_lock.h +16 -0
@@ -127,6 +127,10 @@ static inline int __must_check mmap_write_lock_killable(struct mm_struct *mm)return ret; } +#ifdef CONFIG_PER_VMA_LOCK +void __mm_reset_vma_seqcounts (struct mm_struct *mm); +#endif +/* * Drop all currently-held per-VMA locks. * This is called from the mmap_lock implementation directly before releasing
@@ -139,6 +143,18 @@ static inline void vma_end_write_all(struct mm_struct *mm) {mmap_assert_write_locked (mm);mm_lock_seqcount_end (mm); + +#ifdef CONFIG_PER_VMA_LOCK +/* +* VMA seqcounts are not updated on unlock, so once the mm seqcount has +* wrapped, any VMA still carrying a sequence number from before the +* wrap would satisfy __is_vma_write_locked() when that number comes +* round again, and readers would not be excluded. Reset every VMA's +* seqcount so that no stale value survives the wrap. +*/ +if (unlikely (!mm->mm_lock_seq.sequence)) +__mm_reset_vma_seqcounts (mm); +#endif }static inline void mmap_write_unlock (struct mm_struct *mm)
kernel/fork.c +1 -1
@@ -450,7 +450,7 @@ static bool vma_lock_alloc(struct vm_area_struct *vma)return false;init_rwsem (&vma->vm_lock->lock); - vma->vm_lock_seq =UINT_MAX ; + vma->vm_lock_seq =0 ;return true; }
mm/mmap_lock.c +39 -0
@@ -109,3 +109,42 @@ void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write) }EXPORT_SYMBOL (__mmap_lock_do_trace_released);#endif /* CONFIG_TRACING */ + +#ifdef CONFIG_PER_VMA_LOCK +/* +* Called with mmap write lock held after mm->mm_lock_seq just overflowed (and +* therefore zero), with all VMA write locks now released. +* +* The stores below follow the smp_wmb() in do_raw_write_seqcount_end(), so +* a reader that observes a reset value also observes this cycle's VMA +* modifications (ordered by the ACQUIRE on vma->vm_lock_seq in +* vma_start_read()). +*/ +void __mm_reset_vma_seqcounts (struct mm_struct *mm) +{ +struct vm_area_struct *vma; +VMA_ITERATOR (vmi, mm,0 ); + +mmap_assert_write_locked (mm); +VM_WARN_ON_ONCE (mm->mm_lock_seq.sequence); + +/* +* Failing to reset means stale vma->vm_lock_seq values could result in +* those VMAs becoming spuriously write locked when mm->mm_lock_seq +* happens to match their values. +* +* This is problematic, as it causes the VMA write lock to not exclude +* readers, which can result in concurrent readers while a VMA write +* lock is held. +* +* Avoid this by resetting to an even value (indicates no write lock +* held). +* +* Readers will either observe zero (not write locked) or the previous +* value, so this is safe. +*/ +for_each_vma (vmi, vma) +WRITE_ONCE (vma->vm_lock_seq,0 ); +} +EXPORT_SYMBOL (__mm_reset_vma_seqcounts); +#endif /* CONFIG_PER_VMA_LOCK */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 69/1756 scsi: target: Move I/O path stats to per CPU
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Christie <[email protected]>
[ Upstream commit 9cf2317b795d6cde0fccb8744b5a080a9586020e ]
The atomic use in the main I/O path is causing perf issues when using higher performance backend devices and multiple queues. This moves the stats to per CPU. Combined with the next patch that moves the non_ordered/delayed_cmd_count to per CPU, IOPS by up to 33% for 8K IOS when using 4 or more queues.
Stable-dep-of: 6a6e7d7230cd ("scsi: target: Fix demo-mode dynamic ACL dev-entry UAF vs LUN teardown")
--- drivers/target/target_core_device.c | 69 +++++++++++++++++++++-------- drivers/target/target_core_stat.c | 69 ++++++++++++++++++++++++----- include/target/target_core_base.h | 20 ++++++--- 3 files changed, 121 insertions(+), 37 deletions(-)
drivers/target/target_core_device.c +50 -19
@@ -55,14 +55,14 @@ transport_lookup_cmd_lun(struct se_cmd *se_cmd)rcu_read_lock (); deve =target_nacl_find_deve (nacl, se_cmd->orig_fe_lun);if (deve) { -atomic_long_inc (&deve->total_cmds); +this_cpu_inc (deve->stats->total_cmds);if (se_cmd->data_direction ==DMA_TO_DEVICE ) -atomic_long_add (se_cmd->data_length, - &deve->write_bytes); +this_cpu_add (deve->stats->write_bytes, + se_cmd->data_length);else if (se_cmd->data_direction ==DMA_FROM_DEVICE ) -atomic_long_add (se_cmd->data_length, - &deve->read_bytes); +this_cpu_add (deve->stats->read_bytes, + se_cmd->data_length);if ((se_cmd->data_direction ==DMA_TO_DEVICE ) && deve->lun_access_ro) {
@@ -126,14 +126,14 @@ transport_lookup_cmd_lun(struct se_cmd *se_cmd)* target_core_fabric_configfs.c:target_fabric_port_release */ se_cmd->se_dev =rcu_dereference_raw (se_lun->lun_se_dev); -atomic_long_inc (&se_cmd->se_dev->num_cmds); +this_cpu_inc (se_cmd->se_dev->stats->total_cmds);if (se_cmd->data_direction ==DMA_TO_DEVICE ) -atomic_long_add (se_cmd->data_length, - &se_cmd->se_dev->write_bytes); +this_cpu_add (se_cmd->se_dev->stats->write_bytes, + se_cmd->data_length);else if (se_cmd->data_direction ==DMA_FROM_DEVICE ) -atomic_long_add (se_cmd->data_length, - &se_cmd->se_dev->read_bytes); +this_cpu_add (se_cmd->se_dev->stats->read_bytes, + se_cmd->data_length);return ret; }
@@ -322,6 +322,7 @@ int core_enable_device_list_for_node( struct se_portal_group *tpg) {struct se_dev_entry *orig, *new; +int ret =0 ; new =kzalloc (sizeof (*new),GFP_KERNEL );if (!new) {
@@ -329,6 +330,12 @@ int core_enable_device_list_for_node(return -ENOMEM ; } + new->stats = alloc_percpu(struct se_dev_entry_io_stats); +if (!new->stats) { + ret = -ENOMEM ; + goto free_deve; + } +spin_lock_init (&new->ua_lock);INIT_LIST_HEAD (&new->ua_list);INIT_LIST_HEAD (&new->lun_link);
@@ -351,8 +358,8 @@ int core_enable_device_list_for_node(" for dynamic -> explicit NodeACL conversion:" " %s\n", nacl->initiatorname);mutex_unlock (&nacl->lun_entry_mutex); -kfree (new); -return -EINVAL ; + ret = -EINVAL ; + goto free_stats; }if (orig->se_lun_acl !=NULL ) { pr_warn_ratelimited("Detected existing explicit"
@@ -360,8 +367,8 @@ int core_enable_device_list_for_node(" mapped_lun: %llu, failing\n" , nacl->initiatorname, mapped_lun);mutex_unlock (&nacl->lun_entry_mutex); -kfree (new); -return -EINVAL ; + ret = -EINVAL ; + goto free_stats; } new->se_lun = lun;
@@ -394,6 +401,20 @@ int core_enable_device_list_for_node(target_luns_data_has_changed (nacl, new, true);return 0 ; + +free_stats: +free_percpu (new->stats); +free_deve: +kfree (new); +return ret; +} + +static void target_free_dev_entry (struct rcu_head *head) +{ + struct se_dev_entry *deve = container_of(head, struct se_dev_entry, + rcu_head); +free_percpu (deve->stats); +kfree (deve); } void core_disable_device_list_for_node(
@@ -443,7 +464,7 @@ void core_disable_device_list_for_node(kref_put (&orig->pr_kref, target_pr_kref_release);wait_for_completion (&orig->pr_comp); -kfree_rcu (orig, rcu_head); +call_rcu (&orig->rcu_head, target_free_dev_entry);core_scsi3_free_pr_reg_from_nacl (dev, nacl);target_luns_data_has_changed (nacl,NULL , false);
@@ -689,11 +710,13 @@ struct se_device *target_alloc_device(struct se_hba *hba, const char *name)if (!dev)return NULL ; + dev->stats = alloc_percpu(struct se_dev_io_stats); +if (!dev->stats) + goto free_device; + dev->queues =kcalloc (nr_cpu_ids,sizeof (*dev->queues),GFP_KERNEL ); -if (!dev->queues) { - hba->backend->ops->free_device (dev); -return NULL ; - } +if (!dev->queues) + goto free_stats; dev->queue_cnt = nr_cpu_ids;for (i =0 ; i < dev->queue_cnt; i++) {
@@ -707,6 +730,7 @@ struct se_device *target_alloc_device(struct se_hba *hba, const char *name)INIT_WORK (&q->sq.work, target_queued_submit_work); } + dev->se_hba = hba; dev->transport = hba->backend->ops; dev->transport_flags = dev->transport->transport_flags_default;
@@ -791,6 +815,12 @@ struct se_device *target_alloc_device(struct se_hba *hba, const char *name) sizeof(dev->t10_wwn.revision));return dev; + +free_stats: +free_percpu (dev->stats); +free_device: + hba->backend->ops->free_device (dev); +return NULL ; }/*
@@ -1001,6 +1031,7 @@ void target_free_device(struct se_device *dev) dev->transport->free_prot (dev);kfree (dev->queues); +free_percpu (dev->stats); dev->transport->free_device (dev); }
drivers/target/target_core_stat.c +57 -12
138 lines not on this page · raw message
include/target/target_core_base.h +14 -6
@@ -669,15 +669,19 @@ struct se_lun_acl {struct se_ml_stat_grps ml_stat_grps; }; +struct se_dev_entry_io_stats { +u32 total_cmds; +u32 read_bytes; +u32 write_bytes; +}; +struct se_dev_entry {u64 mapped_lun;u64 pr_res_key;u64 creation_time;bool lun_access_ro;u32 attach_count; -atomic_long_t total_cmds; -atomic_long_t read_bytes; -atomic_long_t write_bytes; +struct se_dev_entry_io_stats __percpu *stats;/* Used for PR SPEC_I_PT=1 and REGISTER_AND_MOVE */ struct kref pr_kref;struct completion pr_comp;
@@ -800,6 +804,12 @@ struct se_device_queue {struct se_cmd_queue sq; }; +struct se_dev_io_stats { +u32 total_cmds; +u32 read_bytes; +u32 write_bytes; +}; +struct se_device {/* Used for SAM Task Attribute ordering */ u32 dev_cur_ordered_id;
@@ -821,9 +831,7 @@ struct se_device {atomic_long_t num_resets;atomic_long_t aborts_complete;atomic_long_t aborts_no_task; -atomic_long_t num_cmds; -atomic_long_t read_bytes; -atomic_long_t write_bytes; +struct se_dev_io_stats __percpu *stats;/* Active commands on this virtual SE device */ atomic_t non_ordered;bool ordered_sync_in_progress;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 70/1756 scsi: target: Fix demo-mode dynamic ACL dev-entry UAF vs LUN teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yu Zhang <[email protected]>
[ Upstream commit 6a6e7d7230cd4e0a6c003bae5b85bf37a1e77b94 ]
A demo-mode (generate_node_acls=1) login that allocates a dynamic NodeACL populates that ACL's per-LUN dev entries in core_tpg_add_node_to_devs() *before* the ACL is linked onto tpg->acl_node_list by target_add_node_acl():
core_tpg_check_initiator_node_acl():
...
core_tpg_add_node_to_devs(acl, tpg, NULL); /* builds deves */
target_add_node_acl(acl); /* only now listed */
The LUN teardown sweep, core_clear_lun_from_tpg(), enumerates only tpg->acl_node_list, so a dev entry whose ACL is still in the window above is invisible to the sweep and is never disabled. It is left on the se_lun->lun_deve_list after core_tpg_remove_lun() frees the se_lun; when the same unpacked_lun is later re-added and the se_lun is reallocated at the same address, the stale dev entry is rediscovered by target_nacl_find_deve() and core_enable_device_list_for_node() corrupts lun_deve_list:
BUG: KASAN: slab-use-after-free ... core_enable_device_list_for_node+0x5ce/0x880 core_tpg_add_node_to_devs+0x169/0x190 core_dev_add_lun+0x146/0x190 target_fabric_port_link+0xe9/0x1b0 configfs_symlink+0x381/0xae0 __x64_sys_symlink+0x55/0x80
The demo-mode login path that drives the ACL/dev-entry creation is reachable by an unauthenticated initiator; the colliding LUN add/remove is a local configfs operation.
Commit 49cb77e297dc ("target: Avoid mappedlun symlink creation during lun shutdown") introduced se_lun->lun_shutdown and guarded the *explicit* ACL MappedLUN path (target_fabric_mappedlun_link()), but the demo-mode automatic path, core_tpg_add_node_to_devs() -> core_enable_device_list_for_node(), was never given the equivalent guard, and the publish-after-populate ordering in core_tpg_check_initiator_node_acl() was left unchanged.
Fix it in three cooperating parts:
1) Publish the dynamic NodeACL onto acl_node_list *before* creating its dev entries, so the teardown sweep can observe them.
2) Refuse to attach a dev entry to an se_lun that is shutting down, checked under nacl->lun_entry_mutex -- the same lock the sweep takes -- so once the sweep has passed an ACL any later enable for that LUN observes lun_shutdown and skips it.
3) In core_enable_device_list_for_node(), insert the new dev entry onto lun->lun_deve_list while still holding nacl->lun_entry_mutex, in both the replace and the new-entry branch. Previously the entry was added to nacl->lun_entry_hlist under the mutex but to lun->lun_deve_list only after dropping it; with the ACL now published early, the sweep could take the mutex in that gap, find the entry on the hlist, core_disable_device_list_for_node() it (list_del() on the not-yet- linked lun_link succeeds and the entry is freed), and then the enable would list_add_tail() the freed entry back onto lun_deve_list. Linking both lists under the mutex makes enable and the sweep mutually exclusive, closing that window.
core_tpg_add_node_to_devs() already ignores the return value of core_enable_device_list_for_node(), so a shutting-down LUN is simply skipped.
--- drivers/target/target_core_device.c | 18 +++++++++++++++--- drivers/target/target_core_tpg.c | 10 +++++++++- 2 files changed, 24 insertions(+), 4 deletions(-)
drivers/target/target_core_device.c +15 -3
@@ -349,6 +349,19 @@ int core_enable_device_list_for_node( new->attach_count++;mutex_lock (&nacl->lun_entry_mutex); +/* +* Do not attach a new dev entry to an se_lun that is being torn down. +* lun_shutdown is set by core_tpg_remove_lun() before its +* core_clear_lun_from_tpg() sweep; checking it here under the same +* nacl->lun_entry_mutex the sweep takes guarantees that once the sweep +* has passed this ACL no dev entry can be left dangling on the +* se_lun->lun_deve_list that is about to be freed. +*/ +if (lun->lun_shutdown) { +mutex_unlock (&nacl->lun_entry_mutex); + ret = -ENODEV ; + goto free_stats; + } orig =target_nacl_find_deve (nacl, mapped_lun);if (orig && orig->se_lun) {struct se_lun *orig_lun = orig->se_lun;
@@ -375,12 +388,12 @@ int core_enable_device_list_for_node( new->se_lun_acl = lun_acl;hlist_del_rcu (&orig->link);hlist_add_head_rcu (&new->link, &nacl->lun_entry_hlist); -mutex_unlock (&nacl->lun_entry_mutex);spin_lock (&lun->lun_deve_lock);list_del (&orig->lun_link);list_add_tail (&new->lun_link, &lun->lun_deve_list);spin_unlock (&lun->lun_deve_lock); +mutex_unlock (&nacl->lun_entry_mutex);kref_put (&orig->pr_kref, target_pr_kref_release);wait_for_completion (&orig->pr_comp);
@@ -393,11 +406,10 @@ int core_enable_device_list_for_node( new->se_lun = lun; new->se_lun_acl = lun_acl;hlist_add_head_rcu (&new->link, &nacl->lun_entry_hlist); -mutex_unlock (&nacl->lun_entry_mutex); -spin_lock (&lun->lun_deve_lock);list_add_tail (&new->lun_link, &lun->lun_deve_list);spin_unlock (&lun->lun_deve_lock); +mutex_unlock (&nacl->lun_entry_mutex);target_luns_data_has_changed (nacl, new, true);return 0 ;
drivers/target/target_core_tpg.c +9 -1
@@ -266,6 +266,15 @@ struct se_node_acl *core_tpg_check_initiator_node_acl(kref_get (&acl->acl_kref); acl->dynamic_node_acl =1 ; +/* +* Publish the dynamic NodeACL on tpg->acl_node_list before creating +* its demo-mode MappedLUN dev entries below, so that a concurrent LUN +* teardown sweep (core_clear_lun_from_tpg(), which walks acl_node_list) +* can observe and disable those dev entries. Otherwise a dev entry can +* be left on an se_lun->lun_deve_list that is about to be freed. +*/ +target_add_node_acl (acl); +/* * Here we only create demo-mode MappedLUNs from the active * TPG LUNs if the fabric is not explicitly asking for
@@ -275,7 +284,6 @@ struct se_node_acl *core_tpg_check_initiator_node_acl( (tpg->se_tpg_tfo->tpg_check_demo_mode_login_only(tpg) != 1))core_tpg_add_node_to_devs (acl, tpg,NULL ); -target_add_node_acl (acl);return acl; }EXPORT_SYMBOL (core_tpg_check_initiator_node_acl);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 71/1756 scsi: target: Fix LUN/device R/W and total command stats
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Christie <[email protected]>
[ Upstream commit 95aa2041c654161d1b5c1eca5379d67d91ef1cf2 ]
In commit 9cf2317b795d ("scsi: target: Move I/O path stats to per CPU") I saw we sometimes use %u and also misread the spec. As a result I thought all the stats were supposed to be 32-bit only. However, for the majority of cases we support currently, the spec specifies u64 bit stats. This patch converts the stats changed in the commit above to u64.
--- drivers/target/target_core_stat.c | 24 ++++++++++++------------ include/target/target_core_base.h | 12 ++++++------ 2 files changed, 18 insertions(+), 18 deletions(-)
drivers/target/target_core_stat.c +12 -12
@@ -282,7 +282,7 @@ static ssize_t target_stat_lu_num_cmds_show(struct config_item *item,struct se_device *dev =to_stat_lu_dev (item);struct se_dev_io_stats *stats;unsigned int cpu; -u32 cmds =0 ; +u64 cmds =0 ;for_each_possible_cpu (cpu) { stats =per_cpu_ptr (dev->stats, cpu);
@@ -290,7 +290,7 @@ static ssize_t target_stat_lu_num_cmds_show(struct config_item *item, }/* scsiLuNumCommands */ -return snprintf (page,PAGE_SIZE ,"%u\n" , cmds); +return snprintf (page,PAGE_SIZE ,"%llu\n" , cmds); } static ssize_t target_stat_lu_read_mbytes_show(struct config_item *item,
@@ -299,7 +299,7 @@ static ssize_t target_stat_lu_read_mbytes_show(struct config_item *item,struct se_device *dev =to_stat_lu_dev (item);struct se_dev_io_stats *stats;unsigned int cpu; -u32 bytes =0 ; +u64 bytes =0 ;for_each_possible_cpu (cpu) { stats =per_cpu_ptr (dev->stats, cpu);
@@ -307,7 +307,7 @@ static ssize_t target_stat_lu_read_mbytes_show(struct config_item *item, }/* scsiLuReadMegaBytes */ -return snprintf (page,PAGE_SIZE ,"%u\n" , bytes >>20 ); +return snprintf (page,PAGE_SIZE ,"%llu\n" , bytes >>20 ); } static ssize_t target_stat_lu_write_mbytes_show(struct config_item *item,
@@ -316,7 +316,7 @@ static ssize_t target_stat_lu_write_mbytes_show(struct config_item *item,struct se_device *dev =to_stat_lu_dev (item);struct se_dev_io_stats *stats;unsigned int cpu; -u32 bytes =0 ; +u64 bytes =0 ;for_each_possible_cpu (cpu) { stats =per_cpu_ptr (dev->stats, cpu);
@@ -324,7 +324,7 @@ static ssize_t target_stat_lu_write_mbytes_show(struct config_item *item, }/* scsiLuWrittenMegaBytes */ -return snprintf (page,PAGE_SIZE ,"%u\n" , bytes >>20 ); +return snprintf (page,PAGE_SIZE ,"%llu\n" , bytes >>20 ); }static ssize_t target_stat_lu_resets_show (struct config_item *item,char *page)
@@ -1044,7 +1044,7 @@ static ssize_t target_stat_auth_num_cmds_show(struct config_item *item,struct se_dev_entry *deve;unsigned int cpu;ssize_t ret; -u32 cmds =0 ; +u64 cmds =0 ;rcu_read_lock (); deve =target_nacl_find_deve (nacl, lacl->mapped_lun);
@@ -1059,7 +1059,7 @@ static ssize_t target_stat_auth_num_cmds_show(struct config_item *item, }/* scsiAuthIntrOutCommands */ - ret =snprintf (page,PAGE_SIZE ,"%u\n" , cmds); + ret =snprintf (page,PAGE_SIZE ,"%llu\n" , cmds);rcu_read_unlock ();return ret; }
@@ -1073,7 +1073,7 @@ static ssize_t target_stat_auth_read_mbytes_show(struct config_item *item,struct se_dev_entry *deve;unsigned int cpu;ssize_t ret; -u32 bytes =0 ; +u64 bytes =0 ;rcu_read_lock (); deve =target_nacl_find_deve (nacl, lacl->mapped_lun);
@@ -1088,7 +1088,7 @@ static ssize_t target_stat_auth_read_mbytes_show(struct config_item *item, }/* scsiAuthIntrReadMegaBytes */ - ret =snprintf (page,PAGE_SIZE ,"%u\n" , bytes >>20 ); + ret =snprintf (page,PAGE_SIZE ,"%llu\n" , bytes >>20 );rcu_read_unlock ();return ret; }
@@ -1102,7 +1102,7 @@ static ssize_t target_stat_auth_write_mbytes_show(struct config_item *item,struct se_dev_entry *deve;unsigned int cpu;ssize_t ret; -u32 bytes =0 ; +u64 bytes =0 ;rcu_read_lock (); deve =target_nacl_find_deve (nacl, lacl->mapped_lun);
@@ -1117,7 +1117,7 @@ static ssize_t target_stat_auth_write_mbytes_show(struct config_item *item, }/* scsiAuthIntrWrittenMegaBytes */ - ret =snprintf (page,PAGE_SIZE ,"%u\n" , bytes >>20 ); + ret =snprintf (page,PAGE_SIZE ,"%llu\n" , bytes >>20 );rcu_read_unlock ();return ret; }
include/target/target_core_base.h +6 -6
@@ -670,9 +670,9 @@ struct se_lun_acl { };struct se_dev_entry_io_stats { -u32 total_cmds; -u32 read_bytes; -u32 write_bytes; +u64 total_cmds; +u64 read_bytes; +u64 write_bytes; };struct se_dev_entry {
@@ -805,9 +805,9 @@ struct se_device_queue { };struct se_dev_io_stats { -u32 total_cmds; -u32 read_bytes; -u32 write_bytes; +u64 total_cmds; +u64 read_bytes; +u64 write_bytes; };struct se_device {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 72/1756 KVM: arm64: vgic-its: Dont map an LPI from more than one event
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fuad Tabba <[email protected]>
[ Upstream commit de81b28f0b83b22163d7d9a9b708d7aa912e0ef7 ]
KVM keeps one vgic_irq per LPI. A MAPTI of an LPI whose vgic_irq already exists reuses it for the new ITE and leaves its target vCPU as it was. Mapping one LPI from two events is UNPREDICTABLE (IHI 0069H.b, 5.2.10), but nothing stops a guest from doing it. If the first MAPTI names a collection the guest never maps and the second a mapped one, the LPI translates through the second event with a NULL target vCPU.
When the VMM routes an assigned device's MSI to that event on a host with GICv4 enabled, kvm_vgic_v4_set_forwarding() takes the vPE from the NULL target vCPU and the host oopses:
Unable to handle kernel paging request at virtual address 0000000000001980 [...] Call trace: its_build_vmapti_cmd (drivers/irqchip/irq-gic-v3-its.c:943) (P) its_irq_set_vcpu_affinity (drivers/irqchip/irq-gic-v3-its.c:1380) irq_set_vcpu_affinity (kernel/irq/manage.c:670) its_map_vlpi (drivers/irqchip/irq-gic-v4.c:326) kvm_vgic_v4_set_forwarding (arch/arm64/kvm/vgic/vgic-v4.c:485) kvm_arch_irq_bypass_add_producer (arch/arm64/kvm/arm.c:2977) irq_bypass_register_consumer (virt/lib/irqbypass.c:44) kvm_irqfd (arch/arm64/kvm/../../../virt/kvm/eventfd.c:496) kvm_vm_ioctl (arch/arm64/kvm/../../../virt/kvm/kvm_main.c:5270)
Track in each vgic_irq whether an ITE maps it. Drop a MAPTI of an LPI that is already mapped, as a failed MAPTI already is. Restoring the ITS tables keeps the first ITE it reads for each LPI and drops any later one, so a guest saved with a double mapping still restores. Key the check on the mapping, not on the vgic_irq. A vgic_irq outlives its ITE while anything holds a reference to it, such as the vCPU it was last queued on. A later MAPTI of such an LPI succeeds as before, and now retargets it to its collection.
--- arch/arm64/kvm/vgic/vgic-its.c | 37 +++++++++++++++++++++++++++++----- include/kvm/arm_vgic.h | 1 + 2 files changed, 33 insertions(+), 5 deletions(-)
arch/arm64/kvm/vgic/vgic-its.c +32 -5
@@ -786,12 +786,18 @@ int vgic_its_inject_msi(struct kvm *kvm, struct kvm_msi *msi)/* Requires the its_lock to be held. */ static void its_free_ite (struct kvm *kvm,struct its_ite *ite) { +struct vgic_irq *irq = ite->irq;list_del (&ite->ite_list);/* This put matches the get in vgic_add_lpi. */ -if (ite->irq) { -if (ite->irq->hw) -WARN_ON (its_unmap_vlpi (ite->irq->host_irq)); +if (irq) { + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { +if (irq->hw) +WARN_ON (its_unmap_vlpi (ite->irq->host_irq)); + + irq->hw = false; + irq->mapped = false; + }vgic_put_irq (kvm, ite->irq); }
@@ -799,6 +805,23 @@ static void its_free_ite(struct kvm *kvm, struct its_ite *ite)kfree (ite); } +/* Mapping one LPI from two events is UNPREDICTABLE: the first ITE keeps it. */ +static bool vgic_its_map_lpi (struct kvm *kvm,struct its_ite *ite, +struct vgic_irq *irq,struct kvm_vcpu *vcpu) +{ + scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) { +if (!irq->mapped) { + irq->mapped = true; + irq->target_vcpu = vcpu; + ite->irq = irq; +return true; + } + } + +vgic_put_irq (kvm, irq); +return false; +} +static u64 its_cmd_mask_field (u64 *its_cmd,int word,int shift,int size) {return (le64_to_cpu (its_cmd[word]) >> shift) & (BIT_ULL (size) -1 );
@@ -1108,13 +1131,14 @@ static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its, vcpu =collection_to_vcpu (kvm, collection); irq =vgic_add_lpi (kvm, lpi_nr, vcpu); +if (!IS_ERR (irq) && !vgic_its_map_lpi (kvm, ite, irq, vcpu)) + irq =ERR_PTR (-EEXIST );if (IS_ERR (irq)) {if (new_coll)vgic_its_free_collection (its, coll_id);its_free_ite (kvm, ite);return PTR_ERR (irq); } - ite->irq = irq;return 0 ; }
@@ -2223,7 +2247,10 @@ static int vgic_its_restore_ite(struct vgic_its *its, u32 event_id,its_free_ite (kvm, ite);return PTR_ERR (irq); } - ite->irq = irq; + +/* Drop an ITE whose LPI another ITE maps, as MAPTI does. */ +if (!vgic_its_map_lpi (kvm, ite, irq, vcpu)) +its_free_ite (kvm, ite);return offset; }
include/kvm/arm_vgic.h +1 -0
@@ -139,6 +139,7 @@ struct vgic_irq {bool active;/* not used for LPIs */ bool enabled;bool hw;/* Tied to HW IRQ */ +bool mapped;/* LPIs: mapped by an ITE */ struct kref refcount;/* Used for LPIs */ u32 hwintid;/* HW INTID number */ unsigned int host_irq;/* linux irq corresponding to hwintid */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 73/1756 l2tp: snapshot sequencing state when building transmit headers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chengfeng Ye <[email protected]>
[ Upstream commit d06ae66516e1aaf023808912af6292aef09d46c3 ]
Updates to send_seq from netlink, PPP setsockopt and receive-side negotiation race with packet transmission. The header length is updated separately, while transmit reads both fields repeatedly without synchronization.
For example, transmit can push a ten-byte L2TPv2 header, then a concurrent writer clears send_seq before the header builder reads it. The builder writes only six bytes, leaving four bytes of uninitialized skb headroom in the outgoing packet. The reverse mismatch overwrites the beginning of the payload. A later hdr_len read can also make the UDP length disagree with the skb length.
KCSAN reported:
BUG: KCSAN: data-race in l2tp_session_set_header_len / l2tp_xmit_skb
write to 0xffff888100d0944a of 2 bytes by task 116 on cpu 1:
l2tp_session_set_header_len+0x81/0xc0 l2tp_nl_cmd_session_modify+0x122/0x2c0 genl_family_rcv_msg_doit+0x170/0x1d0
read to 0xffff888100d0944a of 2 bytes by task 115 on cpu 0:
l2tp_xmit_skb+0x9c/0xc80 pppol2tp_sendmsg+0x21c/0x2a0 __sys_sendto+0x28c/0x2a0
The bug can lead to leak kernel base address for KASLR bypass, the corresponding reproducer can be provided per request.
Initialize hdr_len to the maximum header size and leave it unchanged when sequencing is toggled. Snapshot send_seq once per packet and use that snapshot for the actual header length and header construction, including the sequence flag. Use the same length for headroom, the header push and the UDP length. PPP callers can safely reserve the maximum size; L2TPv3 header sizes do not depend on sequencing.
Make send_seq a separate bool so READ_ONCE() and WRITE_ONCE() can be used without sharing a bitfield storage unit with other configuration flags. Preserve the netlink attribute's existing low-bit truncation.
--- net/l2tp/l2tp_core.c | 51 +++++++++++++++++++---------------------- net/l2tp/l2tp_core.h | 6 ++--- net/l2tp/l2tp_debugfs.c | 4 ++-- net/l2tp/l2tp_netlink.c | 11 ++++----- net/l2tp/l2tp_ppp.c | 8 +++---- 5 files changed, 35 insertions(+), 45 deletions(-)
net/l2tp/l2tp_core.c +24 -27
@@ -924,11 +924,9 @@ void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,* check if we sre sending sequence numbers and if not, * configure it so. */ -if (!session->lns_mode && !session->send_seq) { +if (!session->lns_mode && !READ_ONCE (session->send_seq)) {trace_session_seqnum_lns_enable (session); - session->send_seq =1 ; -l2tp_session_set_header_len (session, tunnel->version, - tunnel->encap); +WRITE_ONCE (session->send_seq, true); } }else {/* No sequence numbers.
@@ -946,12 +944,10 @@ void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,* If we're the LNS and we're sending sequence numbers, the * LAC is broken. Discard the frame. */ -if (!session->lns_mode && session->send_seq) { +if (!session->lns_mode &&READ_ONCE (session->send_seq)) {trace_session_seqnum_lns_disable (session); - session->send_seq =0 ; -l2tp_session_set_header_len (session, tunnel->version, - tunnel->encap); - }else if (session->send_seq) { +WRITE_ONCE (session->send_seq, false); + }else if (READ_ONCE (session->send_seq)) {pr_debug_ratelimited ("%s: recv data has no seq numbers when required. Discarding.\n" , session->name);atomic_long_inc (&session->stats.rx_seq_discards);
@@ -1147,7 +1143,8 @@ static void l2tp_udp_encap_err_recv(struct sock *sk, struct sk_buff *skb, int er/* Build an L2TP header for the session into the buffer provided. */ -static int l2tp_build_l2tpv2_header (struct l2tp_session *session,void *buf) +static int l2tp_build_l2tpv2_header (struct l2tp_session *session,void *buf, +bool send_seq) {struct l2tp_tunnel *tunnel = session->tunnel;__be16 *bufp = buf;
@@ -1156,14 +1153,14 @@ static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)u32 tunnel_id = tunnel->peer_tunnel_id;u32 session_id = session->peer_session_id; -if (session->send_seq) +if (send_seq) flags |=L2TP_HDRFLAG_S ;/* Setup L2TP header. */ *bufp++ =htons (flags); *bufp++ =htons (tunnel_id); *bufp++ =htons (session_id); -if (session->send_seq) { +if (send_seq) { *bufp++ =htons (session->ns); *bufp++ =0 ; session->ns++;
@@ -1174,7 +1171,8 @@ static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)return bufp - optr; } -static int l2tp_build_l2tpv3_header (struct l2tp_session *session,void *buf) +static int l2tp_build_l2tpv3_header (struct l2tp_session *session,void *buf, +bool send_seq) {struct l2tp_tunnel *tunnel = session->tunnel;char *bufp = buf;
@@ -1200,7 +1198,7 @@ static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)if (session->l2specific_type ==L2TP_L2SPECTYPE_DEFAULT ) {u32 l2h =0 ; -if (session->send_seq) { +if (send_seq) { l2h =0x40000000 | session->ns; session->ns++; session->ns &=0xffffff ;
@@ -1234,19 +1232,24 @@ static int l2tp_xmit_queue(struct l2tp_tunnel *tunnel, struct sk_buff *skb, strustatic int l2tp_xmit_core (struct l2tp_session *session,struct sk_buff *skb,unsigned int *len) {struct l2tp_tunnel *tunnel = session->tunnel; +bool send_seq =READ_ONCE (session->send_seq);unsigned int data_len = skb->len;struct sock *sk = tunnel->sock; +u16 hdr_len = session->hdr_len;int headroom, uhlen, udp_len;int ret =NET_XMIT_SUCCESS ;struct inet_sock *inet;struct udphdr *uh; +if (tunnel->version ==L2TP_HDR_VER_2 && !send_seq) + hdr_len -=4 ; +/* Check that there's enough headroom in the skb to insert IP, * UDP and L2TP headers. If not enough, expand it to * make room. Adjust truesize. */ uhlen = (tunnel->encap ==L2TP_ENCAPTYPE_UDP ) ?sizeof (*uh) :0 ; - headroom =NET_SKB_PAD +sizeof (struct iphdr ) + uhlen + session->hdr_len; + headroom =NET_SKB_PAD +sizeof (struct iphdr ) + uhlen + hdr_len;if (skb_cow_head (skb, headroom)) {kfree_skb (skb);return NET_XMIT_DROP ;
@@ -1254,9 +1257,9 @@ static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb, uns/* Setup L2TP header */ if (tunnel->version ==L2TP_HDR_VER_2 ) -l2tp_build_l2tpv2_header (session,__skb_push (skb, session->hdr_len)); +l2tp_build_l2tpv2_header (session,__skb_push (skb, hdr_len), send_seq);else -l2tp_build_l2tpv3_header (session,__skb_push (skb, session->hdr_len)); +l2tp_build_l2tpv3_header (session,__skb_push (skb, hdr_len), send_seq);/* Reset skb netfilter state */ memset (&(IPCB (skb)->opt),0 ,sizeof (IPCB (skb)->opt));
@@ -1299,7 +1302,7 @@ static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb, uns uh =udp_hdr (skb); uh->source = inet->inet_sport; uh->dest = inet->inet_dport; - udp_len = uhlen + session->hdr_len + data_len; + udp_len = uhlen + hdr_len + data_len;if (udp_len >U16_MAX ) {kfree_skb (skb); ret =NET_XMIT_DROP ;
@@ -1768,16 +1771,11 @@ static void l2tp_session_del_work(struct work_struct *work)l2tp_session_put (session); } -/* We come here whenever a session's send_seq, cookie_len or -* l2specific_type parameters are set. -*/ -void l2tp_session_set_header_len (struct l2tp_session *session,int version, -enum l2tp_encap_type encap) +static void l2tp_session_set_header_len (struct l2tp_session *session,int version, +enum l2tp_encap_type encap) {if (version ==L2TP_HDR_VER_2 ) { - session->hdr_len =6 ; -if (session->send_seq) - session->hdr_len +=4 ; + session->hdr_len =10 ; }else { session->hdr_len =4 + session->cookie_len; session->hdr_len +=l2tp_get_l2specific_len (session);
@@ -1785,7 +1783,6 @@ void l2tp_session_set_header_len(struct l2tp_session *session, int version, session->hdr_len +=4 ; } } -EXPORT_SYMBOL_GPL (l2tp_session_set_header_len);struct l2tp_session *l2tp_session_create (int priv_size,struct l2tp_tunnel *tunnel,u32 session_id,u32 peer_session_id,struct l2tp_session_cfg *cfg)
net/l2tp/l2tp_core.h +2 -4
@@ -76,7 +76,7 @@ struct l2tp_session {u8 peer_cookie[8 ];int peer_cookie_len;u16 l2specific_type; -u16 hdr_len; +u16 hdr_len;/* maximum L2TP header length */ u32 nr;/* session NR state (receive) */ u32 ns;/* session NR state (send) */ struct sk_buff_head reorder_q;/* receive reorder queue */
@@ -94,8 +94,8 @@ struct l2tp_session {char name[L2TP_SESSION_NAME_MAX ];/* for logging */ char ifname[IFNAMSIZ ]; +bool send_seq;/* send packets with sequence numbers? */ unsigned int recv_seq:1; /* expect receive packets with sequence numbers? */ - unsigned int send_seq:1; /* send packets with sequence numbers? */ unsigned int lns_mode:1; /* behave as LNS?* LAC enables sequence numbers under LNS control. */
@@ -257,8 +257,6 @@ void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,int l2tp_udp_encap_recv (struct sock *sk,struct sk_buff *skb);/* Transmit path helpers for sending packets over the tunnel socket. */ -void l2tp_session_set_header_len (struct l2tp_session *session,int version, -enum l2tp_encap_type encap);int l2tp_xmit_skb (struct l2tp_session *session,struct sk_buff *skb);/* Pseudowire management.
net/l2tp/l2tp_debugfs.c +2 -2
@@ -182,12 +182,12 @@ static void l2tp_dfs_seq_session_show(struct seq_file *m, void *v) session->pwtype ==L2TP_PWTYPE_ETH ?"ETH" : session->pwtype ==L2TP_PWTYPE_PPP ?"PPP" : ""); -if (session->send_seq || session->recv_seq) +if (READ_ONCE (session->send_seq) || session->recv_seq)seq_printf (m," nr %u, ns %u\n" , session->nr, session->ns);seq_printf (m," refcnt %d\n" ,refcount_read (&session->ref_count));seq_printf (m," config 0/0/%c/%c/-/%s %08x %u\n" , session->recv_seq ?'R' :'-' , - session->send_seq ?'S' :'-' , +READ_ONCE (session->send_seq) ?'S' :'-' , session->lns_mode ?"LNS" :"LAC" ,0 ,jiffies_to_msecs (session->reorder_timeout));
net/l2tp/l2tp_netlink.c +4 -7
@@ -697,12 +697,9 @@ static int l2tp_nl_cmd_session_modify(struct sk_buff *skb, struct genl_info *infif (info->attrs[L2TP_ATTR_RECV_SEQ ]) session->recv_seq =nla_get_u8 (info->attrs[L2TP_ATTR_RECV_SEQ ]); -if (info->attrs[L2TP_ATTR_SEND_SEQ ]) { -struct l2tp_tunnel *tunnel = session->tunnel; - - session->send_seq =nla_get_u8 (info->attrs[L2TP_ATTR_SEND_SEQ ]); -l2tp_session_set_header_len (session, tunnel->version, tunnel->encap); - } +if (info->attrs[L2TP_ATTR_SEND_SEQ ]) +WRITE_ONCE (session->send_seq, +nla_get_u8 (info->attrs[L2TP_ATTR_SEND_SEQ ]) &1 );if (info->attrs[L2TP_ATTR_LNS_MODE ]) session->lns_mode =nla_get_u8 (info->attrs[L2TP_ATTR_LNS_MODE ]);
@@ -745,7 +742,7 @@ static int l2tp_nl_session_send(struct sk_buff *skb, u32 portid, u32 seq, int fl (session->peer_cookie_len &&nla_put (skb,L2TP_ATTR_PEER_COOKIE , session->peer_cookie_len, session->peer_cookie)) ||nla_put_u8 (skb,L2TP_ATTR_RECV_SEQ , session->recv_seq) || -nla_put_u8 (skb,L2TP_ATTR_SEND_SEQ , session->send_seq) || +nla_put_u8 (skb,L2TP_ATTR_SEND_SEQ ,READ_ONCE (session->send_seq)) ||nla_put_u8 (skb,L2TP_ATTR_LNS_MODE , session->lns_mode) || (l2tp_tunnel_uses_xfrm (tunnel) && nla_put_u8(skb, L2TP_ATTR_USING_IPSEC, 1)) ||
net/l2tp/l2tp_ppp.c +3 -5
@@ -1193,15 +1193,13 @@ static int pppol2tp_session_setsockopt(struct sock *sk, err = -EINVAL ;break ; } - session->send_seq = !!val; +WRITE_ONCE (session->send_seq, !!val); {struct pppox_sock *po =pppox_sk (sk); po->chan.hdrlen = val ?PPPOL2TP_L2TP_HDR_SIZE_SEQ :PPPOL2TP_L2TP_HDR_SIZE_NOSEQ ; } -l2tp_session_set_header_len (session, session->tunnel->version, - session->tunnel->encap);break ;case PPPOL2TP_SO_LNSMODE :
@@ -1311,7 +1309,7 @@ static int pppol2tp_session_getsockopt(struct sock *sk,break ;case PPPOL2TP_SO_SENDSEQ : - *val = session->send_seq; + *val =READ_ONCE (session->send_seq);break ;case PPPOL2TP_SO_LNSMODE :
@@ -1557,7 +1555,7 @@ static void pppol2tp_seq_session_show(struct seq_file *m, void *v) state, user_data_ok);seq_printf (m," 0/0/%c/%c/%s %08x %u\n" , session->recv_seq ?'R' :'-' , - session->send_seq ?'S' :'-' , +READ_ONCE (session->send_seq) ?'S' :'-' , session->lns_mode ?"LNS" :"LAC" ,0 ,jiffies_to_msecs (session->reorder_timeout));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 74/1756 mm/hugetlb: fix mremap deadlock when PMD sharing is possible
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Zhe <[email protected]>
[ Upstream commit 92daa8652f88c8cfc05f4899a8408a04b02f211e ]
move_hugetlb_page_tables() holds the mapping's i_mmap_rwsem for write while moving hugetlb PTEs. This prevents races with truncation and protects huge_pmd_unshare(), but the move loop must not call helpers that can acquire the same rwsem for read.
huge_pte_alloc() can do that when the destination can use PMD
sharing: it may call huge_pmd_share(), which takes i_mmap_rwsem for read while searching for a shareable PMD table. Calling it while the move path already holds i_mmap_rwsem for write can deadlock.
Avoid that path for PMD-sized hugetlb mappings that can use PMD sharing. Instead of allocating or sharing the destination page table while moving, zap the source range and let the destination fault path populate or share the PMD lazily.
Reuse the hugetlb unmap logic for the source-side zap by splitting the core loop out of __unmap_hugepage_range(). The wrapper keeps the existing tlb_start_vma(), tlb_end_vma() and huge_pmd_unshare_flush() behavior, while move_hugetlb_page_tables() can reuse the unmap loop with its existing mmu_gather.
--- mm/hugetlb.c | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-)
mm/hugetlb.c +37 -10
@@ -92,6 +92,10 @@ static int __huge_pmd_unshare(struct mmu_gather *tlb, bool check_locks);static void hugetlb_unshare_pmds (struct vm_area_struct *vma,unsigned long start,unsigned long end,bool take_locks); +static void hugetlb_unmap_range (struct mmu_gather *tlb, +struct vm_area_struct *vma,unsigned long start, +unsigned long end,struct page *ref_page, +zap_flags_t zap_flags);static struct resv_map *vma_resv_map (struct vm_area_struct *vma);static void hugetlb_free_folio (struct folio *folio)
@@ -5540,6 +5544,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,for (; old_addr < old_end; old_addr += sz, new_addr += sz) {const unsigned long offset_to_last_entry = (old_addr | last_addr_mask) - old_addr; +const unsigned long offset_to_last_dst_entry = + (new_addr | last_addr_mask) - new_addr; src_pte =hugetlb_walk (vma, old_addr, sz);if (!src_pte) {
@@ -5556,6 +5562,24 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,continue ; } +/* +* Avoid entering the destination PMD sharing path while holding +* i_mmap_rwsem for write. Leave destination page table +* population to the fault path, which can share the PMD lazily. +*/ +if (sz ==PMD_SIZE &&want_pmd_share (new_vma, new_addr)) { +const unsigned long unmap_size = +min (old_end - old_addr, + offset_to_last_dst_entry + sz); + +hugetlb_unmap_range (&tlb, vma, old_addr, + old_addr + unmap_size,NULL , +ZAP_FLAG_DROP_MARKER ); + old_addr += unmap_size - sz; + new_addr += unmap_size - sz; +continue ; + } + dst_pte =huge_pte_alloc (mm, new_vma, new_addr, sz);if (!dst_pte)break ;
@@ -5575,9 +5599,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,return len + old_addr - old_end; } -void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, -unsigned long start,unsigned long end, -struct page *ref_page,zap_flags_t zap_flags) +static void hugetlb_unmap_range (struct mmu_gather *tlb, +struct vm_area_struct *vma,unsigned long start, +unsigned long end,struct page *ref_page, +zap_flags_t zap_flags) {struct mm_struct *mm = vma->vm_mm;unsigned long address;
@@ -5595,13 +5620,6 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,BUG_ON (start & ~huge_page_mask (h));BUG_ON (end & ~huge_page_mask (h)); -/* -* This is a hugetlb vma, all the pte entries should point -* to huge page. -*/ -tlb_change_page_size (tlb, sz); -tlb_start_vma (tlb, vma); - last_addr_mask =hugetlb_mask_last_page (h); address = start;for (; address < end; address += sz) {
@@ -5728,6 +5746,15 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,if (ref_page)break ; } +} + +void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, +unsigned long start,unsigned long end, +struct page *ref_page,zap_flags_t zap_flags) +{ +tlb_change_page_size (tlb,huge_page_size (hstate_vma (vma))); +tlb_start_vma (tlb, vma); +hugetlb_unmap_range (tlb, vma, start, end, ref_page, zap_flags);tlb_end_vma (tlb, vma);huge_pmd_unshare_flush (tlb, vma);
Signature · 1 line
2.53.0
Re: [PATCH 6.12 0074/1756] mm/hugetlb: fix mremap deadlock when PMD sharing is possible
Hi Greg/Sasha,
Quoted 8 lines · Greg Kroah-Hartman
6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Zhe <[email protected]>
[ Upstream commit
92daa8652f88c8cfc05f4899a8408a04b02f211e]
....
Quoted 7 lines
mm/hugetlb.c +3
-0@@ -5556,6 +5562,24 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,continue ; } +/* +* Avoid entering the destination PMD sharing path while holding +* i_mmap_rwsem for write. Leave destination page table
mm/hugetlb.c unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma, · line 5577
Quoted 10 lines
mm/hugetlb.c +10
-0+* population to the fault path, which can share the PMD lazily. +*/ +if (sz ==PMD_SIZE &&want_pmd_share (new_vma, new_addr)) { +const unsigned long unmap_size = +min (old_end - old_addr, + offset_to_last_dst_entry + sz); + +hugetlb_unmap_range (&tlb, vma, old_addr, + old_addr + unmap_size,NULL , +ZAP_FLAG_DROP_MARKER );
I have run and AI-assisted review of 6.12.y commit and found a missing restriction compared with upstream 92daa8652f88.
include/linux/userfaultfd_k.h, 6.12.y -> upstream:
static inline bool uffd_disable_huge_pmd_share(struct vm_area_struct *vma) {
- return vma->vm_flags & (VM_UFFD_WP | VM_UFFD_MINOR);
+ return vma->vm_userfaultfd_ctx.ctx;
}The 6.12.y helper permits PMD sharing for missing-only UFFD registrations. Upstream disables sharing for all registrations.
This matters because the new path in mm/hugetlb.c does:
hugetlb_unmap_range(&tlb, vma, old_addr,
old_addr + unmap_size, NULL, ZAP_FLAG_DROP_MARKER);
With an unshared source table and a sharing-eligible destination, a missing-only UFFD mapping can reach this zap and lose its poison marker instead of preserving it across mremap.
I think this is a needed prerequisite: 809cbe72ace8 ("mm/hugetlb: disable PMD sharing for UFFD missing mode").
We don;t have that in 6.12.y, so should we drop it ?
thanks,
Harshit
Quoted 52 lines
mm/hugetlb.c +18
-10+ old_addr += unmap_size - sz; + new_addr += unmap_size - sz; +continue ; + } + dst_pte =huge_pte_alloc (mm, new_vma, new_addr, sz);if (!dst_pte)break ;@@ -5575,9 +5599,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,return len + old_addr - old_end; } -void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, -unsigned long start,unsigned long end, -struct page *ref_page,zap_flags_t zap_flags) +static void hugetlb_unmap_range (struct mmu_gather *tlb, +struct vm_area_struct *vma,unsigned long start, +unsigned long end,struct page *ref_page, +zap_flags_t zap_flags) {struct mm_struct *mm = vma->vm_mm;unsigned long address;@@ -5595,13 +5620,6 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,BUG_ON (start & ~huge_page_mask (h));BUG_ON (end & ~huge_page_mask (h)); -/* -* This is a hugetlb vma, all the pte entries should point -* to huge page. -*/ -tlb_change_page_size (tlb, sz); -tlb_start_vma (tlb, vma); - last_addr_mask =hugetlb_mask_last_page (h); address = start;for (; address < end; address += sz) {@@ -5728,6 +5746,15 @@ void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,if (ref_page)break ; } +} + +void __unmap_hugepage_range (struct mmu_gather *tlb,struct vm_area_struct *vma, +unsigned long start,unsigned long end, +struct page *ref_page,zap_flags_t zap_flags) +{ +tlb_change_page_size (tlb,huge_page_size (hstate_vma (vma))); +tlb_start_vma (tlb, vma); +hugetlb_unmap_range (tlb, vma, start, end, ref_page, zap_flags);tlb_end_vma (tlb, vma);huge_pmd_unshare_flush (tlb, vma);
Re: [PATCH 6.12 0074/1756] mm/hugetlb: fix mremap deadlock when PMD sharing is possible
Quoted 4 lines
I think this is a needed prerequisite:
809cbe72ace8("mm/hugetlb:
disable PMD sharing for UFFD missing mode").We don;t have that in 6.12.y, so should we drop it ?
Queued the missing prerequisite for 7.3, 6.18, 6.12 and 6.6, thanks.
Signature · 2 lines
Thanks, Sasha
Greg Kroah-Hartman
maintainerPATCH 75/1756 mm: fix outdated incorrect code comments for handle_mm_fault()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jinliang Zheng <[email protected]>
[ Upstream commit 8e6173ccf7b87c1f855e1ad3d94fd50c51d1f46b ]
Stable-dep-of: f681d4580d5c ("mm: fix address wraparound when scanning large folio PTEs")
--- mm/memory.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/memory.c +2 -1
@@ -6071,7 +6071,8 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma, }/* -* By the time we get here, we already hold the mm semaphore +* By the time we get here, we already hold either the VMA lock or the +* mmap_lock (FAULT_FLAG_VMA_LOCK tells you which). * * The mmap_lock may have been released depending on flags and our * return value. See filemap_fault() and __folio_lock_or_retry().
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 76/1756 mm/memory: update stale locking comments for fault handlers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Aditya Sharma <[email protected]>
[ Upstream commit 214f9ab72ce6e16120c20ad670389656f059e685 ]
Update the comments for wp_page_copy(), do_wp_page(), do_swap_page(), do_anonymous_page(), __do_fault(), do_fault(), handle_pte_fault(), __handle_mm_fault(), and handle_mm_fault() to concisely clarify that they can be entered holding either the mmap_lock or the VMA lock, and that the lock may be released upon returning VM_FAULT_RETRY.
Additionally, make the following corrections:
- In do_anonymous_page(), correct the outdated claim that the function is entered with the PTE "mapped but not yet locked". Since handle_pte_fault() unmaps the empty PTE before routing to do_pte_missing(), the comment now correctly states it is entered with the PTE unmapped and unlocked.
- In __do_fault(), update the stale reference from __lock_page_retry() to __folio_lock_or_retry().
Stable-dep-of: f681d4580d5c ("mm: fix address wraparound when scanning large folio PTEs")
--- mm/memory.c | 55 ++++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 26 deletions(-)
mm/memory.c +29 -26
@@ -3322,8 +3322,8 @@ vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)* Handle the case of a page which we actually need to copy to a new page, * either due to COW or unsharing. * -* Called with mmap_lock locked and the old page referenced, but -* without the ptl held. +* Called with either the VMA lock or the mmap_lock held (see FAULT_FLAG_VMA_LOCK) +* and the old page referenced, but without the ptl held. * * High level logic flow: *
@@ -3657,9 +3657,9 @@ static bool wp_can_reuse_anon_folio(struct folio *folio,* though the page will change only once the write actually happens. This * avoids a few races, and potentially makes it more efficient. * -* We enter with non-exclusive mmap_lock (to exclude vma changes, -* but allow concurrent faults), with pte both mapped and locked. -* We return with mmap_lock still held, but pte unmapped and unlocked. +* We enter with either the VMA lock or the mmap_lock held (see +* FAULT_FLAG_VMA_LOCK) and pte both mapped and locked. We return with +* the same lock still held, but pte unmapped and unlocked. */ static vm_fault_t do_wp_page(struct vm_fault *vmf) __releases(vmf->ptl)
@@ -4199,12 +4199,12 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)static DECLARE_WAIT_QUEUE_HEAD (swapcache_wq);/* -* We enter with non-exclusive mmap_lock (to exclude vma changes, -* but allow concurrent faults), and pte mapped but not yet locked. +* We enter with either the VMA lock or the mmap_lock held (see +* FAULT_FLAG_VMA_LOCK), and pte mapped but not yet locked. * We return with pte unmapped and unlocked. * -* We return with the mmap_lock locked or unlocked in the same cases -* as does filemap_fault(). +* When returning, the lock may have been released in the same cases +* as done by filemap_fault(). */ vm_fault_t do_swap_page (struct vm_fault *vmf) {
@@ -4737,9 +4737,10 @@ static struct folio *alloc_anon_folio(struct vm_fault *vmf) }/* -* We enter with non-exclusive mmap_lock (to exclude vma changes, -* but allow concurrent faults), and pte mapped but not yet locked. -* We return with mmap_lock still held, but pte unmapped and unlocked. +* We enter with either the VMA lock or the mmap_lock held (see +* FAULT_FLAG_VMA_LOCK), and pte unmapped and unlocked. +* We return with the lock still held, but pte unmapped and unlocked. +* If VM_FAULT_RETRY is returned, the lock may have been released. */ static vm_fault_t do_anonymous_page (struct vm_fault *vmf) {
@@ -4857,9 +4858,10 @@ static vm_fault_t do_anonymous_page(struct vm_fault *vmf) }/* -* The mmap_lock must have been held on entry, and may have been -* released depending on flags and vma->vm_ops->fault() return value. -* See filemap_fault() and __lock_page_retry(). +* Either the VMA lock or the mmap_lock must have been held on entry +* (see FAULT_FLAG_VMA_LOCK) and may have been released depending on +* flags and vma->vm_ops->fault() return value. +* See filemap_fault() and __folio_lock_or_retry(). */ static vm_fault_t __do_fault (struct vm_fault *vmf) {
@@ -5423,11 +5425,11 @@ static vm_fault_t do_shared_fault(struct vm_fault *vmf) }/* -* We enter with non-exclusive mmap_lock (to exclude vma changes, -* but allow concurrent faults). -* The mmap_lock may have been released depending on flags and our +* We enter with either the VMA lock or the mmap_lock held (see +* FAULT_FLAG_VMA_LOCK). +* The lock may have been released depending on flags and our * return value. See filemap_fault() and __folio_lock_or_retry(). -* If mmap_lock is released, vma may become invalid (for example +* If the lock is released, vma may become invalid (for example * by other thread calling munmap()). */ static vm_fault_t do_fault (struct vm_fault *vmf)
@@ -5755,10 +5757,11 @@ static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)* with external mmu caches can use to update those (ie the Sparc or * PowerPC hashed page tables that act as extended TLBs). * -* We enter with non-exclusive mmap_lock (to exclude vma changes, but allow -* concurrent faults). +* On entry, we hold either the VMA lock or the mmap_lock +* (see FAULT_FLAG_VMA_LOCK). * -* The mmap_lock may have been released depending on flags and our return value. +* The mmap_lock or VMA lock may have been released depending on flags +* and our return value. * See filemap_fault() and __folio_lock_or_retry(). */ static vm_fault_t handle_pte_fault (struct vm_fault *vmf)
@@ -5841,8 +5844,8 @@ static vm_fault_t handle_pte_fault(struct vm_fault *vmf)/* * On entry, we hold either the VMA lock or the mmap_lock -* (FAULT_FLAG_VMA_LOCK tells you which). If VM_FAULT_RETRY is set in -* the result, the mmap_lock is not held on exit. See filemap_fault() +* (see FAULT_FLAG_VMA_LOCK). If VM_FAULT_RETRY is set in +* the result, the lock is not held on exit. See filemap_fault() * and __folio_lock_or_retry(). */ static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
@@ -6072,9 +6075,9 @@ static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma,/* * By the time we get here, we already hold either the VMA lock or the -* mmap_lock (FAULT_FLAG_VMA_LOCK tells you which). +* mmap_lock (see FAULT_FLAG_VMA_LOCK). * -* The mmap_lock may have been released depending on flags and our +* The lock may have been released depending on flags and our * return value. See filemap_fault() and __folio_lock_or_retry(). */ vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 77/1756 mm: fix address wraparound when scanning large folio PTEs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f681d4580d5c3c749f623cda722a21aefd3147b3 ]
numa_rebuild_large_mapping() and do_swap_page() can be tricked into generating an address wraparound, crashing the kernel. All that's required is to map a tail page of a large folio close enough to the start/end of the address space to e.g., make
unsigned long addr_start = addr - (nr << PAGE_SHIFT);
to wrap around.
Let's fix it by providing a better helper, folio_scan_range(), that takes care of staying within VMA and page table boundaries while handling possible wraparounds.
There are some nasty details, like not being able to use pmd_addr_end() in this context. Add some helpful comments for these cases.
--- mm/memory.c | 50 ++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 14 deletions(-)
mm/memory.c +36 -14
@@ -4198,6 +4198,34 @@ static struct folio *alloc_swap_folio(struct vm_fault *vmf)static DECLARE_WAIT_QUEUE_HEAD (swapcache_wq); +/* +* Get the address range in which a folio might be mapped, assuming its pages +* are mapped consecutively and the folio page at the given idx is mapped at +* the given address. +*/ +static void folio_pte_range (const struct folio *folio, +const struct vm_area_struct *vma,unsigned long addr, +unsigned long idx,unsigned long *start,unsigned long *end) +{ +/* Stay within the page table and VMA boundaries. */ +const unsigned long pmd_start = addr &PMD_MASK ; +const unsigned long pmd_end = pmd_start +PMD_SIZE ; +const unsigned long lower =max (pmd_start, vma->vm_start); +/* +* We cannot use pmd_addr_end(), as it does not clamp reliably. To +* avoid wraparounds, compute using the inclusive end. +*/ +const unsigned long upper =min (pmd_end -1 , vma->vm_end -1 ) +1 ; +const unsigned long offset = idx <<PAGE_SHIFT ; + +/* +* Avoid start/end addresses wrapping by not adding/subtracting more +* than the lower/upper limits would allow. +*/ + *start = addr -min (addr - lower, offset); + *end = addr +min (upper - addr,folio_size (folio) - offset); +} +/* * We enter with either the VMA lock or the mmap_lock held (see * FAULT_FLAG_VMA_LOCK), and pte mapped but not yet locked.
@@ -4445,16 +4473,15 @@ vm_fault_t do_swap_page(struct vm_fault *vmf) address = vmf->address; ptep = vmf->pte;if (folio_test_large (folio) &&folio_test_swapcache (folio)) { -int nr =folio_nr_pages (folio); -unsigned long idx =folio_page_idx (folio, page); -unsigned long folio_start = address - idx *PAGE_SIZE ; -unsigned long folio_end = folio_start + nr *PAGE_SIZE ; +const int nr =folio_nr_pages (folio); +const unsigned long idx =folio_page_idx (folio, page); +unsigned long folio_start, folio_end;pte_t *folio_ptep;pte_t folio_pte; -if (unlikely (folio_start <max (address &PMD_MASK , vma->vm_start))) - goto check_folio; -if (unlikely (folio_end >pmd_addr_end (address, vma->vm_end))) +folio_pte_range (folio, vma, address, idx, &folio_start, + &folio_end); +if (unlikely ((folio_end - folio_start) >>PAGE_SHIFT != nr)) goto check_folio; folio_ptep = vmf->pte - idx;
@@ -5542,16 +5569,11 @@ static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_stru struct folio *folio, pte_t fault_pte, bool ignore_writable, bool pte_write_upgrade) { - int nr = pte_pfn(fault_pte) - folio_pfn(folio); + const unsigned long idx = pte_pfn(fault_pte) - folio_pfn(folio);unsigned long start, end, addr = vmf->address; -unsigned long addr_start = addr - (nr <<PAGE_SHIFT ); -unsigned long pt_start =ALIGN_DOWN (addr,PMD_SIZE );pte_t *start_ptep; -/* Stay within the VMA and within the page table. */ - start =max3 (addr_start, pt_start, vma->vm_start); - end =min3 (addr_start +folio_size (folio), pt_start +PMD_SIZE , - vma->vm_end); +folio_pte_range (folio, vma, addr, idx, &start, &end); start_ptep = vmf->pte - ((addr - start) >>PAGE_SHIFT );/* Restore all PTEs' mapping of the large folio */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 78/1756 mm/huge_memory: fix truncate racing with PMD zapping
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chris Mason <[email protected]>
[ Upstream commit e6a07d29b0a60f3a4cfe77fe34eeb4b3fb38d6c4 ]
zap_huge_pmd_folio() removes the rmap before calling folio_mark_dirty(). If this was the last mapping, truncation can skip unmapping the folio and proceed without waiting for the PMD lock, racing with dirtying.
ifs_set_range_dirty() can oops if MADV_DONTNEED races with ftruncate() on XFS, when we get the folio set dirty after it was found to not be mapped anymore.
Move folio_mark_dirty() and folio_mark_accessed() before rmap removal, matching the PTE zap path. This keeps the folio mapped while updating its state, so truncation must wait for the page table lock.
Fix generated by an LLM and sent by Chris Mason in private.
--- mm/huge_memory.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
mm/huge_memory.c +9 -2
@@ -2128,8 +2128,6 @@ int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,struct page *page =pmd_page (orig_pmd); folio =page_folio (page); -folio_remove_rmap_pmd (folio, page, vma); -WARN_ON_ONCE (folio_mapcount (folio) <0 );VM_BUG_ON_PAGE (!PageHead (page), page); }else if (thp_migration_supported ()) {swp_entry_t entry;
@@ -2154,6 +2152,15 @@ int zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,folio_mark_dirty (folio); } +/* +* Only present folios are rmappable. Remove the rmap after +* transferring young+dirty to the folio. +*/ +if (flush_needed) { +folio_remove_rmap_pmd (folio, &folio->page, vma); +WARN_ON_ONCE (folio_mapcount (folio) <0 ); + } +spin_unlock (ptl);if (flush_needed)tlb_remove_page_size (tlb, &folio->page,HPAGE_PMD_SIZE );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 79/1756 fbdev: kyro: Use devm_ioremap() for mmio registers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giovanni Di Santi <[email protected]>
[ Upstream commit e0bf12a43243e6afc5a03fc55c58ec48aba48088 ]
Replace the manual ioremap() call for the MMIO registers with the device-managed devm_ioremap() variant.
This simplifies the driver's resource management by ensuring the memory is automatically unmapped when the driver detaches from the device.
Stable-dep-of: d3bc005a6294 ("fbdev: kyro: Release WC setup on registration failure")
--- drivers/video/fbdev/kyro/fbdev.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/video/fbdev/kyro/fbdev.c +3 -5
@@ -718,13 +718,14 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent) kyro_fix.mmio_len =pci_resource_len (pdev,1 ); currentpar->regbase = deviceInfo.pSTGReg = -ioremap (kyro_fix.mmio_start, kyro_fix.mmio_len); +devm_ioremap (&pdev->dev, kyro_fix.mmio_start, + kyro_fix.mmio_len);if (!currentpar->regbase) goto out_free_fb; info->screen_base =pci_ioremap_wc_bar (pdev,0 );if (!info->screen_base) - goto out_unmap_regs; + goto out_free_fb;if (!nomtrr) currentpar->wc_cookie = arch_phys_wc_add(kyro_fix.smem_start,
@@ -772,8 +773,6 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent) out_unmap:iounmap (info->screen_base); -out_unmap_regs: -iounmap (currentpar->regbase); out_free_fb:framebuffer_release (info);
@@ -796,7 +795,6 @@ static void kyrofb_remove(struct pci_dev *pdev) deviceInfo.ulOverlayOffset =0 ;iounmap (info->screen_base); -iounmap (par->regbase);arch_phys_wc_del (par->wc_cookie);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 80/1756 fbdev: kyro: Use devm_ioremap_wc() for screen mem
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giovanni Di Santi <[email protected]>
[ Upstream commit 32dfb6112ea3ca143636832cd34234f2be4830bb ]
Replace the manual pci_ioremap_wc() call for mapping screen memory with the device-managed devm_ioremap_wc() variant.
This simplifies the driver's resource management by ensuring the memory is automatically unmapped when the driver detaches from the device.
Stable-dep-of: d3bc005a6294 ("fbdev: kyro: Release WC setup on registration failure")
--- drivers/video/fbdev/kyro/fbdev.c | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-)
drivers/video/fbdev/kyro/fbdev.c +3 -6
@@ -723,7 +723,8 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)if (!currentpar->regbase) goto out_free_fb; - info->screen_base =pci_ioremap_wc_bar (pdev,0 ); + info->screen_base =devm_ioremap_wc (&pdev->dev, kyro_fix.smem_start, + kyro_fix.smem_len);if (!info->screen_base) goto out_free_fb;
@@ -760,7 +761,7 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)fb_memset_io (info->screen_base,0 , size);if (register_framebuffer (info) <0 ) - goto out_unmap; + goto out_free_fb; fb_info(info, "%s frame buffer device, at %dx%d@%d using %ldk/%ldk of VRAM\n", info->fix.id,
@@ -771,8 +772,6 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)return 0 ; -out_unmap: -iounmap (info->screen_base); out_free_fb:framebuffer_release (info);
@@ -794,8 +793,6 @@ static void kyrofb_remove(struct pci_dev *pdev) deviceInfo.ulNextFreeVidMem =0 ; deviceInfo.ulOverlayOffset =0 ; -iounmap (info->screen_base); -arch_phys_wc_del (par->wc_cookie);unregister_framebuffer (info);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 81/1756 fbdev: kyro: Release WC setup on registration failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
[ Upstream commit d3bc005a62945aec57059201092b12b7c955e5a7 ]
If register_framebuffer() fails, kyrofb_probe() frees the framebuffer without releasing its write-combining range. Release the range before freeing the framebuffer. Earlier failures still skip this cleanup.
The missing cleanup already exists in the initial Git import, before the conversion from mtrr_add() to arch_phys_wc_add().
This issue was identified during our ongoing static-analysis research while reviewing kernel code.
--- drivers/video/fbdev/kyro/fbdev.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/video/fbdev/kyro/fbdev.c +3 -1
@@ -761,7 +761,7 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)fb_memset_io (info->screen_base,0 , size);if (register_framebuffer (info) <0 ) - goto out_free_fb; + goto out_free_wc; fb_info(info, "%s frame buffer device, at %dx%d@%d using %ldk/%ldk of VRAM\n", info->fix.id,
@@ -772,6 +772,8 @@ static int kyrofb_probe(struct pci_dev *pdev, const struct pci_device_id *ent)return 0 ; +out_free_wc: +arch_phys_wc_del (currentpar->wc_cookie); out_free_fb:framebuffer_release (info);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 82/1756 hwmon: (coretemp) Fix 32-bit jiffies wraparound in show_temp()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 9a6aa085c94c7f2817c4d50a7264e6fb51286f40 ]
show_temp() rate-limits MSR reads by storing tdata->last_updated as an unsigned long and comparing it against jiffies using time_after(jiffies, tdata->last_updated + HZ).
time_after() relies on signed long subtraction, which only produces the expected result while the two timestamps are within LONG_MAX jiffies of each other. On 32-bit kernels, if tempX_input is not read for more than LONG_MAX jiffies (~24.85 days at HZ=1000), the signed difference flips sign and time_after() evaluates to false. Because tdata->last_updated is only refreshed when time_after() succeeds, subsequent reads remain blocked from refreshing for another ~24.85 days until jiffies wraps past tdata->last_updated + HZ again, returning either a stale cached temperature or -ENODATA if the sensor had never been read since initialization.
Store tdata->last_updated as a u64 and use get_jiffies_64() with time_after64(), which does not wrap in any practical uptime.
--- drivers/hwmon/coretemp.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-)
drivers/hwmon/coretemp.c +5 -8
@@ -77,7 +77,7 @@ struct temp_data {int temp;bool temp_valid;int tjmax; -unsigned long last_updated; +u64 last_updated;unsigned int cpu;int index;u32 cpu_core_id;
@@ -407,7 +407,7 @@ static ssize_t show_temp(struct device *dev, tjmax =get_tjmax (tdata, dev);/* Check whether the time interval has elapsed */ -if (time_after (jiffies, tdata->last_updated +HZ )) { +if (time_after64 (get_jiffies_64 (), tdata->last_updated +HZ )) {rdmsr_on_cpu (tdata->cpu, tdata->status_reg, &eax, &edx);/* * Bit 31 indicates whether the reading is valid. Some CPUs
@@ -416,7 +416,7 @@ static ssize_t show_temp(struct device *dev,*/ tdata->temp_valid = (eax >>31 ) &1 ; tdata->temp = tjmax - ((eax >>16 ) &0xff ) *1000 ; - tdata->last_updated = jiffies; + tdata->last_updated =get_jiffies_64 (); } valid = tdata->temp_valid;
@@ -528,11 +528,8 @@ init_temp_data(struct platform_data *pdata, unsigned int cpu, int pkg_flag) tdata->cpu = cpu; tdata->cpu_core_id =topology_core_id (cpu); tdata->attr_size =MAX_CORE_ATTRS ; -/* -* A zero timestamp does not look stale on 32-bit, where jiffies -* starts just short of wrapping. Backdate it instead. -*/ - tdata->last_updated = jiffies -HZ -1 ; +/* Backdate to force a refresh on the first read */ + tdata->last_updated =get_jiffies_64 () -HZ -1 ;mutex_init (&tdata->update_lock);return tdata; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 83/1756 hwmon: (tmp108) Add helper function tmp108_common_probe() to prepare I3C support
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Frank Li <[email protected]>
[ Upstream commit 700f3250198d51093884254220a96777a922dd47 ]
Add help function tmp108_common_probe() to pave road to support i3c for P3T1085(NXP) chip.
Use dev_err_probe() to simplify the code.
Message-ID: <[email protected]>
Stable-dep-of: 7cd60538073e ("hwmon: (tmp108) Fix initial conversion delay and wait until ready")
--- drivers/hwmon/tmp108.c | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-)
drivers/hwmon/tmp108.c +21 -18
@@ -323,33 +323,19 @@ static const struct regmap_config tmp108_regmap_config = { .use_single_write = true, }; -static int tmp108_probe (struct i2c_client *client) +static int tmp108_common_probe (struct device *dev,struct regmap *regmap,char *name) { -struct device *dev = &client->dev;struct device *hwmon_dev;struct tmp108 *tmp108; -int err;u32 config; - -if (!i2c_check_functionality (client->adapter, -I2C_FUNC_SMBUS_WORD_DATA )) { -dev_err (dev, -"adapter doesn't support SMBus word transactions\n" ); -return -ENODEV ; - } +int err; tmp108 =devm_kzalloc (dev,sizeof (*tmp108),GFP_KERNEL );if (!tmp108)return -ENOMEM ;dev_set_drvdata (dev, tmp108); - - tmp108->regmap =devm_regmap_init_i2c (client, &tmp108_regmap_config); -if (IS_ERR (tmp108->regmap)) { - err =PTR_ERR (tmp108->regmap); -dev_err (dev,"regmap init failed: %d" , err); -return err; - } + tmp108->regmap = regmap; err =regmap_read (tmp108->regmap,TMP108_REG_CONF , &config);if (err <0 ) {
@@ -383,13 +369,30 @@ static int tmp108_probe(struct i2c_client *client)return err; } - hwmon_dev =devm_hwmon_device_register_with_info (dev, client->name, + hwmon_dev =devm_hwmon_device_register_with_info (dev, name, tmp108, &tmp108_chip_info,NULL );return PTR_ERR_OR_ZERO (hwmon_dev); } +static int tmp108_probe (struct i2c_client *client) +{ +struct device *dev = &client->dev; +struct regmap *regmap; + +if (!i2c_check_functionality (client->adapter, +I2C_FUNC_SMBUS_WORD_DATA )) +return dev_err_probe (dev, -ENODEV , +"adapter doesn't support SMBus word transactions\n" ); + + regmap =devm_regmap_init_i2c (client, &tmp108_regmap_config); +if (IS_ERR (regmap)) +return dev_err_probe (dev,PTR_ERR (regmap),"regmap init failed" ); + +return tmp108_common_probe (dev, regmap, client->name); +} +static int tmp108_suspend (struct device *dev) {struct tmp108 *tmp108 =dev_get_drvdata (dev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 84/1756 hwmon: (tmp108) Fix initial conversion delay and wait until ready
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guenter Roeck <[email protected]>
[ Upstream commit 7cd60538073e465310c94b2a2f0ea8d2f03768ef ]
In tmp108_common_probe(), the driver only adds the 30 ms conversion delay (TMP108_CONVERSION_TIME_MS) to ready_time if the sensor was previously in TMP108_MODE_SHUTDOWN. However, the TMP108 hardware defaults to continuous conversion mode (TMP108_MODE_CONTINUOUS) upon power-on reset, including immediately after enabling the vcc supply regulator during probe, while the temperature register retains its power-on reset value of 0x0000 (0°C) until the first conversion completes. Because the initial mode is not shutdown, the delay is bypassed and early reads via thermal zone registration or sysfs before the first conversion finishes return an uninitialized 0°C reading.
In addition, returning -EAGAIN from tmp108_read() while waiting for a conversion to complete after probe or resume can trigger an unnecessary tight retry loop in callers or fail initial reads.
Unconditionally set ready_time to TMP108_CONVERSION_TIME_MS ahead in tmp108_common_probe(), track ready_time as ktime_t, and wait for the remaining conversion time in tmp108_read() using usleep_range() instead of returning -EAGAIN.
--- drivers/hwmon/tmp108.c | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-)
drivers/hwmon/tmp108.c +11 -15
@@ -14,7 +14,7 @@#include <linux/of.h> #include <linux/i2c.h> #include <linux/init.h> -#include <linux/jiffies.h> +#include <linux/ktime.h> #include <linux/regmap.h> #include <linux/slab.h>
@@ -73,7 +73,7 @@struct tmp108 {struct regmap *regmap;u16 orig_config; -u64 ready_time; +ktime_t ready_time; };/* convert 12-bit TMP108 register value to milliCelsius */
@@ -94,6 +94,7 @@ static int tmp108_read(struct device *dev, enum hwmon_sensor_types type,struct tmp108 *tmp108 =dev_get_drvdata (dev);unsigned int regval;int err, hyst; +s64 delay;if (type == hwmon_chip) {if (attr == hwmon_chip_update_interval) {
@@ -123,12 +124,10 @@ static int tmp108_read(struct device *dev, enum hwmon_sensor_types type,switch (attr) {case hwmon_temp_input: -/* Is it too early to return a conversion ? */ -if (time_before64 (get_jiffies_64 (), tmp108->ready_time)) { -dev_dbg (dev,"%s: Conversion not ready yet..\n" , - __func__); -return -EAGAIN ; - } +/* Wait if it is too early to return a conversion */ + delay =ktime_us_delta (tmp108->ready_time,ktime_get ()); +if (delay >0 ) +usleep_range (delay, delay +1000 ); err =regmap_read (tmp108->regmap,TMP108_REG_TEMP , ®val);if (err <0 )return err;
@@ -357,11 +356,8 @@ static int tmp108_common_probe(struct device *dev, struct regmap *regmap, char *return err; } - tmp108->ready_time =get_jiffies_64 (); -if ((tmp108->orig_config &TMP108_CONF_MODE_MASK ) == -TMP108_MODE_SHUTDOWN ) - tmp108->ready_time += -msecs_to_jiffies (TMP108_CONVERSION_TIME_MS ); + tmp108->ready_time =ktime_add_ms (ktime_get (), +TMP108_CONVERSION_TIME_MS ); err =devm_add_action_or_reset (dev, tmp108_restore_config, tmp108);if (err) {
@@ -408,8 +404,8 @@ static int tmp108_resume(struct device *dev) err =regmap_update_bits (tmp108->regmap,TMP108_REG_CONF ,TMP108_CONF_MODE_MASK ,TMP108_MODE_CONTINUOUS ); - tmp108->ready_time =get_jiffies_64 () + -msecs_to_jiffies (TMP108_CONVERSION_TIME_MS ); + tmp108->ready_time =ktime_add_ms (ktime_get (), +TMP108_CONVERSION_TIME_MS );return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 85/1756 drm/amdgpu: dont walk the CS chunks when allocating them failed
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit ade92d50aad6799a5a9d7e73cd1604fd0576e656 ]
amdgpu_cs_pass1() sets p->nchunks before allocating p->chunks, and the allocation failure path skips resetting it. amdgpu_cs_parser_fini() then frees the kdata of nchunks chunks from a NULL array. On navi48 with the chunk array allocation failed through failslab:
Oops: general protection fault, probably for non-canonical address 0xdffffc0000000001: 0000 [#1] SMP KASAN NOPTI KASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f] RIP: 0010:amdgpu_cs_parser_fini+0x35d/0x710 [amdgpu] amdgpu_cs_ioctl+0xcae/0x7a20 [amdgpu] drm_ioctl_kernel+0x180/0x320 [drm]
Set nchunks once the array exists.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_cs.c +3 -2
@@ -215,13 +215,14 @@ static int amdgpu_cs_pass1(struct amdgpu_cs_parser *p,if (IS_ERR (chunk_array))return PTR_ERR (chunk_array); - p->nchunks = cs->in.num_chunks; - p->chunks =kvmalloc_array (p->nchunks,sizeof (struct amdgpu_cs_chunk ), +/* parser_fini() walks nchunks chunks, set it once they exist */ + p->chunks =kvmalloc_array (cs->in.num_chunks,sizeof (struct amdgpu_cs_chunk ),GFP_KERNEL );if (!p->chunks) { ret = -ENOMEM ; goto free_chunk; } + p->nchunks = cs->in.num_chunks;for (i =0 ; i < p->nchunks; i++) {struct drm_amdgpu_cs_chunk __user *chunk_ptr =NULL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 86/1756 nvme: tuning pr code by using defined structs and macros
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guixin Liu <[email protected]>
[ Upstream commit 029cc98dec2eadb5d0978b5fea9ae6c427f2a020 ]
All the modifications are simply to make the code more readable, and this patch does not include any functional changes.
Stable-dep-of: a9d431124fb2 ("nvme: unregister when pr_register() is given a zero new key")
--- drivers/nvme/host/pr.c | 122 +++++++++++++++++++++++++---------------- 1 file changed, 75 insertions(+), 47 deletions(-)
drivers/nvme/host/pr.c +75 -47
@@ -92,109 +92,137 @@ static int nvme_status_to_pr_err(int status) } } -static int nvme_send_pr_command (struct block_device *bdev, -struct nvme_command *c,void *data,unsigned int data_len) +static int __nvme_send_pr_command (struct block_device *bdev,u32 cdw10, +u32 cdw11,u8 op,void *data,unsigned int data_len) { -if (nvme_disk_is_ns_head (bdev->bd_disk)) -return nvme_send_ns_head_pr_command (bdev, c, data, data_len); +struct nvme_command c = {0 }; -return nvme_send_ns_pr_command (bdev->bd_disk->private_data, c, data, - data_len); + c.common.opcode = op; + c.common.cdw10 =cpu_to_le32 (cdw10); + c.common.cdw11 =cpu_to_le32 (cdw11); + +if (nvme_disk_is_ns_head (bdev->bd_disk)) +return nvme_send_ns_head_pr_command (bdev, &c, data, data_len); +return nvme_send_ns_pr_command (bdev->bd_disk->private_data, &c, + data, data_len); } -static int nvme_pr_command (struct block_device *bdev,u32 cdw10, -u64 key,u64 sa_key,u8 op) +static int nvme_send_pr_command (struct block_device *bdev,u32 cdw10,u32 cdw11, +u8 op,void *data,unsigned int data_len) { -struct nvme_command c = { }; -u8 data[16 ] = {0 , };int ret; -put_unaligned_le64 (key, &data[0 ]); -put_unaligned_le64 (sa_key, &data[8 ]); - - c.common.opcode = op; - c.common.cdw10 =cpu_to_le32 (cdw10); - - ret =nvme_send_pr_command (bdev, &c, data,sizeof (data)); -if (ret <0 ) -return ret; - -return nvme_status_to_pr_err (ret); + ret =__nvme_send_pr_command (bdev, cdw10, cdw11, op, data, data_len); +return ret <0 ? ret :nvme_status_to_pr_err (ret); } -static int nvme_pr_register (struct block_device *bdev,u64 old, -u64 new,unsigned flags) +static int nvme_pr_register (struct block_device *bdev,u64 old_key,u64 new_key, +unsigned int flags) { +struct nvmet_pr_register_data data = {0 };u32 cdw10;if (flags & ~PR_FL_IGNORE_KEY )return -EOPNOTSUPP ; - cdw10 = old ?2 :0 ; - cdw10 |= (flags &PR_FL_IGNORE_KEY ) ?1 <<3 :0 ; - cdw10 |= (1 <<30 ) | (1 <<31 );/* PTPL=1 */ -return nvme_pr_command (bdev, cdw10, old, new, nvme_cmd_resv_register); + data.crkey =cpu_to_le64 (old_key); + data.nrkey =cpu_to_le64 (new_key); + + cdw10 = old_key ?NVME_PR_REGISTER_ACT_REPLACE : +NVME_PR_REGISTER_ACT_REG ; + cdw10 |= (flags &PR_FL_IGNORE_KEY ) ?NVME_PR_IGNORE_KEY :0 ; + cdw10 |=NVME_PR_CPTPL_PERSIST ; + +return nvme_send_pr_command (bdev, cdw10,0 , nvme_cmd_resv_register, + &data,sizeof (data)); }static int nvme_pr_reserve (struct block_device *bdev,u64 key,enum pr_type type,unsigned flags) { +struct nvmet_pr_acquire_data data = {0 };u32 cdw10;if (flags & ~PR_FL_IGNORE_KEY )return -EOPNOTSUPP ; - cdw10 =nvme_pr_type_from_blk (type) <<8 ; - cdw10 |= ((flags &PR_FL_IGNORE_KEY ) ?1 <<3 :0 ); -return nvme_pr_command (bdev, cdw10, key,0 , nvme_cmd_resv_acquire); + data.crkey =cpu_to_le64 (key); + + cdw10 =NVME_PR_ACQUIRE_ACT_ACQUIRE ; + cdw10 |=nvme_pr_type_from_blk (type) <<8 ; + cdw10 |= (flags &PR_FL_IGNORE_KEY ) ?NVME_PR_IGNORE_KEY :0 ; + +return nvme_send_pr_command (bdev, cdw10,0 , nvme_cmd_resv_acquire, + &data,sizeof (data)); }static int nvme_pr_preempt (struct block_device *bdev,u64 old,u64 new,enum pr_type type,bool abort) { -u32 cdw10 =nvme_pr_type_from_blk (type) <<8 | (abort ?2 :1 ); +struct nvmet_pr_acquire_data data = {0 }; +u32 cdw10; + + data.crkey =cpu_to_le64 (old); + data.prkey =cpu_to_le64 (new); -return nvme_pr_command (bdev, cdw10, old, new, nvme_cmd_resv_acquire); + cdw10 = abort ?NVME_PR_ACQUIRE_ACT_PREEMPT_AND_ABORT : +NVME_PR_ACQUIRE_ACT_PREEMPT ; + cdw10 |=nvme_pr_type_from_blk (type) <<8 ; + +return nvme_send_pr_command (bdev, cdw10,0 , nvme_cmd_resv_acquire, + &data,sizeof (data)); }static int nvme_pr_clear (struct block_device *bdev,u64 key) { -u32 cdw10 =1 | (key ?0 :1 <<3 ); +struct nvmet_pr_release_data data = {0 }; +u32 cdw10; + + data.crkey =cpu_to_le64 (key); -return nvme_pr_command (bdev, cdw10, key,0 , nvme_cmd_resv_release); + cdw10 =NVME_PR_RELEASE_ACT_CLEAR ; + cdw10 |= key ?0 :NVME_PR_IGNORE_KEY ; + +return nvme_send_pr_command (bdev, cdw10,0 , nvme_cmd_resv_release, + &data,sizeof (data)); }static int nvme_pr_release (struct block_device *bdev,u64 key,enum pr_type type) { -u32 cdw10 =nvme_pr_type_from_blk (type) <<8 | (key ?0 :1 <<3 ); +struct nvmet_pr_release_data data = {0 }; +u32 cdw10; + + data.crkey =cpu_to_le64 (key); -return nvme_pr_command (bdev, cdw10, key,0 , nvme_cmd_resv_release); + cdw10 =NVME_PR_RELEASE_ACT_RELEASE ; + cdw10 |=nvme_pr_type_from_blk (type) <<8 ; + cdw10 |= key ?0 :NVME_PR_IGNORE_KEY ; + +return nvme_send_pr_command (bdev, cdw10,0 , nvme_cmd_resv_release, + &data,sizeof (data)); }static int nvme_pr_resv_report (struct block_device *bdev,void *data,u32 data_len,bool *eds) { -struct nvme_command c = { }; +u32 cdw10, cdw11;int ret; - c.common.opcode = nvme_cmd_resv_report; - c.common.cdw10 =cpu_to_le32 (nvme_bytes_to_numd (data_len)); - c.common.cdw11 =cpu_to_le32 (NVME_EXTENDED_DATA_STRUCT ); + cdw10 =nvme_bytes_to_numd (data_len); + cdw11 =NVME_EXTENDED_DATA_STRUCT ; *eds = true; retry: - ret =nvme_send_pr_command (bdev, &c, data, data_len); + ret =__nvme_send_pr_command (bdev, cdw10, cdw11, nvme_cmd_resv_report, + data, data_len);if (ret ==NVME_SC_HOST_ID_INCONSIST && - c.common.cdw11 ==cpu_to_le32 (NVME_EXTENDED_DATA_STRUCT )) { - c.common.cdw11 =0 ; + cdw11 ==NVME_EXTENDED_DATA_STRUCT ) { + cdw11 =0 ; *eds = false; goto retry; } -if (ret <0 ) -return ret; - -return nvme_status_to_pr_err (ret); +return ret <0 ? ret :nvme_status_to_pr_err (ret); } static int nvme_pr_read_keys(struct block_device *bdev,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 87/1756 nvme: unregister when pr_register() is given a zero new key
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit a9d431124fb2e58215daf0299d6fcf47bbc2d6b1 ]
The block layer PR API defines a zero new_key in pr_register() as unregistering old_key. nvme_pr_register() sends Replace Reservation Key with a zero NRKEY instead. The host stays registered with key 0, and its next registration with another key fails with Reservation Conflict.
The pNFS SCSI layout client unregisters this way at umount. A later mount cannot register and sends all I/O through the metadata server.
Send Unregister Reservation Key when new_key is zero.
--- drivers/nvme/host/pr.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/nvme/host/pr.c +6 -2
@@ -128,8 +128,12 @@ static int nvme_pr_register(struct block_device *bdev, u64 old_key, u64 new_key, data.crkey =cpu_to_le64 (old_key); data.nrkey =cpu_to_le64 (new_key); - cdw10 = old_key ?NVME_PR_REGISTER_ACT_REPLACE : -NVME_PR_REGISTER_ACT_REG ; +if (!new_key) + cdw10 =NVME_PR_REGISTER_ACT_UNREG ; +else if (old_key) + cdw10 =NVME_PR_REGISTER_ACT_REPLACE ; +else + cdw10 =NVME_PR_REGISTER_ACT_REG ; cdw10 |= (flags &PR_FL_IGNORE_KEY ) ?NVME_PR_IGNORE_KEY :0 ; cdw10 |=NVME_PR_CPTPL_PERSIST ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 88/1756 mm/vma: dont leak the charge for stack growth
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit b1ee87802111156e27557e82acc31fa7dfc76e2a ]
acct_stack_growth() charges stack expansion even without VM_ACCOUNT. This can happen for read-only or MAP_NORESERVE mappings created with MAP_GROWSDOWN. Unmapping these VMAs does not release the charge, leaking Committed_AS.
Only check and charge growth for VM_ACCOUNT VMAs, matching mremap(). Unaccounted growth skips the overcommit check while remaining subject to the other stack-growth limits.
--- mm/mmap.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
mm/mmap.c +2 -1
@@ -1040,7 +1040,8 @@ static int acct_stack_growth(struct vm_area_struct *vma,* Overcommit.. This must be the final test, as it will * update security statistics. */ -if (security_vm_enough_memory_mm (mm, grow)) +if ((vma->vm_flags &VM_ACCOUNT ) && +security_vm_enough_memory_mm (mm, grow))return -ENOMEM ;return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 89/1756 drm/i915/psr: Clear selective fetch area when duplicating plane state
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit cbe565475988d3b22dc36f13c14d9f0eec1685cd ]
We are currently not clearing selective fetch area when duplicating plane state. This is causing problem when plane is re-used for another purpose. Fix this by clearing selective fetch area when duplicating plane state.
Now as the state is cleared we need to ensure we have consistent selective fetch area in plane state on full update. Earlier this was relying on selective fetch area being copied from old state on state duplicate. Now this isn't true anymore as we are clearing it. Tackle this by setting full plane area as selective fetch area for each plane on full update. Rename the label as skip_su_area_calc as the loop setting the plane selective fetch area is not skipped anymore.
Move also psr2_sel_fetch_pipe_state_supported check after psr2_su_area initialization. The loop is run on full update as well now and it needs initialized psr2_su_area. Clip_area_update is only touching rect height and x1/x2 are left untouched.
Don't set the area at all for planes not intersecting with the selective update area. It is already zero sized after plane state duplicate.
--- .../gpu/drm/i915/display/intel_atomic_plane.c | 1 + drivers/gpu/drm/i915/display/intel_psr.c | 24 +++++++++---------- 2 files changed, 12 insertions(+), 13 deletions(-)
drivers/gpu/drm/i915/display/intel_atomic_plane.c +1 -0
@@ -115,6 +115,7 @@ intel_plane_duplicate_state(struct drm_plane *plane) intel_state->ggtt_vma =NULL ; intel_state->dpt_vma =NULL ; intel_state->flags =0 ; + intel_state->psr2_sel_fetch_area =DRM_RECT_INIT (0 ,0 ,0 ,0 );/* add reference to fb */ if (intel_state->hw.fb)
drivers/gpu/drm/i915/display/intel_psr.c +11 -13
@@ -2579,16 +2579,16 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,if (!crtc_state->enable_psr2_sel_fetch)return 0 ; -if (!psr2_sel_fetch_pipe_state_supported (crtc_state)) { - full_update = true; - goto skip_sel_fetch_set_loop; - } - crtc_state->psr2_su_area.x1 =0 ; crtc_state->psr2_su_area.y1 =-1 ; crtc_state->psr2_su_area.x2 =drm_rect_width (&display_area); crtc_state->psr2_su_area.y2 =-1 ; +if (!psr2_sel_fetch_pipe_state_supported (crtc_state)) { + full_update = true; + goto skip_su_area_calc; + } +/* * Calculate minimal selective fetch area of each plane and calculate * the pipe damaged area.
@@ -2672,7 +2672,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, }if (full_update) - goto skip_sel_fetch_set_loop; + goto skip_su_area_calc;intel_psr_apply_su_area_workarounds (crtc_state);
@@ -2708,6 +2708,11 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,break ; }while (su_area_changed); +skip_su_area_calc: +if (full_update) +clip_area_update (&crtc_state->psr2_su_area, &display_area, + &display_area); +/* * Now that we have the pipe damaged area check if it intersect with * every plane, if it does set the plane selective fetch area.
@@ -2724,8 +2729,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, inter = crtc_state->psr2_su_area; sel_fetch_area = &new_plane_state->psr2_sel_fetch_area;if (!drm_rect_intersect (&inter, &new_plane_state->uapi.dst)) { - sel_fetch_area->y1 =-1 ; - sel_fetch_area->y2 =-1 ;/* * if plane sel fetch was previously enabled -> * disable it
@@ -2765,11 +2768,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, } } -skip_sel_fetch_set_loop: -if (full_update) -clip_area_update (&crtc_state->psr2_su_area, &display_area, - &display_area); -psr2_man_trk_ctl_calc (crtc_state, full_update); crtc_state->pipe_srcsz_early_tpt =psr2_pipe_srcsz_early_tpt_calc (crtc_state, full_update);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 90/1756 mm/hugetlb: dont clear the resv_map of a VMA whose lock is held
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit d42032c0fe3ca007986c1229128775af0340fbec ]
Since commit bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs") the lock of a private hugetlb VMA that owns a reservation is the rw_sema of its resv_map. The hugetlb_vma_*lock*() helpers find it through vma->vm_private_data, anew for every lock and every unlock.
At the end of mremap() the old VMA has to let go of the resv_map, which now belongs to the new VMA: clear_vma_resv_huge_pages() stores NULL into vm_private_data. mremap() holds mmap_lock for writing and has write locked the VMA, which keeps away everybody who comes through the mm. It does not keep away those who find the VMA through the file. For hole punch and truncation hugetlb_vmdelete_list() does
hugetlb_vma_trylock_write(vma); locks resv_map->rw_sema unmap_hugepage_range(vma, ...); vm_private_data = NULL hugetlb_vma_unlock_write(vma); no resv_map: does nothing
and the rw_sema stays write locked for ever:
WARNING: lock held when returning to user space! mremap_punch/116 is leaving the kernel with locks still held! locks held by mremap_punch/116: 1, last CPU#1:
#0: (&resv_map->rw_sema){+.+.}-{4:4}, at:
hugetlb_vmdelete_list+0x46/0x160
The next fault in the new VMA sleeps in hugetlb_vma_lock_read(), uninterruptibly, and it holds its entry of hugetlb_fault_mutex_table[]. That table is global, so a fault of any other process on a page that hashes to the same entry sleeps uninterruptibly as well.
All those who take the lock of a private VMA without taking the mmap/vma lock are affected: rmap walks. So hold i_mmap_rwsem around the clearing of the resv_map.
No change of behaviour, other than that mremap() of a hugetlb VMA takes i_mmap_rwsem once more.
Original fix generated by an LLM and sent in private by Josef.
--- mm/mremap.c | 7 +++++++ 1 file changed, 7 insertions(+)
mm/mremap.c +7 -0
@@ -812,7 +812,14 @@ static unsigned long move_vma(struct vm_area_struct *vma, }if (is_vm_hugetlb_page (vma)) { +/* +* Rmap walks might still find this VMA and take the lock +* inside the reservation map for __vma_private_lock(). Don't clear +* the reservation map while that is possible. +*/ +i_mmap_lock_write (vma->vm_file->f_mapping);clear_vma_resv_huge_pages (vma); +i_mmap_unlock_write (vma->vm_file->f_mapping); }/* Conceal VM_ACCOUNT so old reservation is not undone */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 91/1756 mm/madvise: preserve VMA_SOFTDIRTY_BIT when changing anonymous names
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 652f15be3c11415725694ccea317c51e35c0b582 ]
When changing the anonymous VMA name, madvise_update_vma() calls vma_modify_name() to possibly merge with adjacent VMAs. We don't call vma_modify_flags() and consequently don't obtain the new VMA flags.
Later in the function we update the VMA flags to the stale new_vma_flags we obtained before. This can result in us losing the VMA_SOFTDIRTY_BIT flag set on a VMA we just merged with.
There is no need to update the VMA flags at all, so just exit early. This skips calling khugepaged_enter_vma(), but since the flags didn't change this is fine.
--- mm/madvise.c | 4 ++++ 1 file changed, 4 insertions(+)
mm/madvise.c +4 -0
@@ -140,6 +140,7 @@ static int madvise_update_vma(struct vm_area_struct *vma, struct anon_vma_name *anon_name) {struct mm_struct *mm = vma->vm_mm; +bool set_new_anon_name = new_flags == vma->vm_flags;int error;VMA_ITERATOR (vmi, mm, start);
@@ -157,6 +158,9 @@ static int madvise_update_vma(struct vm_area_struct *vma,/* vm_flags is protected by the mmap_lock held in write mode. */ vma_start_write (vma); +if (set_new_anon_name) +return replace_anon_vma_name (vma, anon_name); +vm_flags_reset (vma, new_flags);/* * If the vma become good for khugepaged to scan,
Signature · 1 line
2.53.0
Re: [PATCH 6.12 0091/1756] mm/madvise: preserve VMA_SOFTDIRTY_BIT when changing anonymous names
Hi Sasha,
Quoted 59 lines · Greg Kroah-Hartman
6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit
652f15be3c11415725694ccea317c51e35c0b582]When changing the anonymous VMA name,
madvise_update_vma()callsvma_modify_name()to possibly merge with adjacent VMAs. We don't callvma_modify_flags()and consequently don't obtain the new VMA flags.Later in the function we update the VMA flags to the stale
new_vma_flagswe obtained before. This can result in us losing theVMA_SOFTDIRTY_BITflag set on a VMA we just merged with.There is no need to update the VMA flags at all, so just exit early. This skips calling
khugepaged_enter_vma(), but since the flags didn't change this is fine.[[email protected]: minor edit of commit message, rebased]Fixes 9a10064f5625 ("mm: add a field to store names for private anonymous memory")Signed-off-by David Hildenbrand (Arm) <[email protected]>Signed-off-by Lorenzo Stoakes (ARM) <[email protected]>Signed-off-by Andrew Morton <[email protected]>Reviewed-by Lorenzo Stoakes (ARM) <[email protected]>Reviewed-by Pedro Falcato <[email protected]>Tested-by Gregory Price (Meta) <[email protected]>Cc Liam R. Howlett <[email protected]>Cc Vlastimil Babka <[email protected]>Cc Mike Rapoport <[email protected]>Cc Suren Baghdasaryan <[email protected]>Cc Michal Hocko <[email protected]>Cc Jann Horn <[email protected]>Cc Davidlohr Bueso <[email protected]>Cc SJ Park <[email protected]>Cc Kees Cook <[email protected]>Cc Colin Cross <[email protected]>Cc <[email protected]>[ sashal: inferred name-only changes from pre-merge flag equality instead of using a separate name-change indicator ]Signed-off-by Sasha Levin <[email protected]>--- mm/madvise.c | 4 ++++ 1 file changed, 4 insertions(+)mm/madvise.c +1
-0@@ -140,6 +140,7 @@ static int madvise_update_vma(struct vm_area_struct *vma, struct anon_vma_name *anon_name) {struct mm_struct *mm = vma->vm_mm; +bool set_new_anon_name = new_flags == vma->vm_flags;int error;VMA_ITERATOR (vmi, mm, start);
mm/madvise.c static int madvise_update_vma(struct vm_area_struct *vma, · line 163
Quoted 6 lines
mm/madvise.c +3
-0@@ -157,6 +158,9 @@ static int madvise_update_vma(struct vm_area_struct *vma,/* vm_flags is protected by the mmap_lock held in write mode. */ vma_start_write (vma); +if (set_new_anon_name) +return replace_anon_vma_name (vma, anon_name); +
I ran an AI-assisted backport review found an issue and it looks correct to me
Renaming a dirty anonymous VMA into a clean neighbor can now lose VM_SOFTDIRTY.
mm/vma.c:
6.12.y 6a44160fd54e:
res = merge_left ? prev : next;
khugepaged_enter_vma(res, vmg->flags);
vmg->state = VMA_MERGE_SUCCESS;
return res;Original upstream 652f15be3c11:
vma_set_flags_mask(vmg->target, sticky_flags);
khugepaged_enter_vma(vmg->target, vmg->vm_flags);
vmg->state = VMA_MERGE_SUCCESS;
return vmg->target;mm/madvise.c:
6.12.y 6a44160fd54e:
vma_start_write(vma);
if (set_new_anon_name)
return replace_anon_vma_name(vma, anon_name);
vm_flags_reset(vma, new_flags);The destination permits merges that differ only in VM_SOFTDIRTY but returns the surviving neighbor without combining that bit. The new early return skips vm_flags_reset(), which previously preserved a dirty renamed range in this direction. Upstream first accumulates sticky flags on the surviving VMA. The change fixes the opposite loss direction while introducing this one; the consequence is incorrect caller-visible change metadata.
Upstream supplies sticky propagation through 64212ba02e66 ("mm:
implement sticky VMA flags") and 6707915e030a ("mm: propagate VM_SOFTDIRTY on merge").
Should we drop this patch until we have these backports ?
thanks,
Harshit
Quoted 3 lines
mm/madvise.c +0
-0vm_flags_reset (vma, new_flags);/* * If the vma become good for khugepaged to scan,
Sasha Levin
maintainerRe: [PATCH 6.12 0091/1756] mm/madvise: preserve VMA_SOFTDIRTY_BIT when changing anonymous names
Quoted 5 lines
Upstream supplies sticky propagation through
64212ba02e66("mm:
implement sticky VMA flags") and6707915e030a("mm: propagateVM_SOFTDIRTYon merge").Should we drop this patch until we have these backports ?
Dropped from 6.12, 6.6 and 6.1, since the sticky-flag merge propagation is missing there. 7.3 and 6.18 keep it. Thanks!
Signature · 2 lines
Thanks, Sasha
Greg Kroah-Hartman
maintainerPATCH 92/1756 mm/mremap: use pudp_huge_get_and_clear() when moving huge PUDs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit b4417d08034a7b4a3083e0e2d95429d4542524f2 ]
move_huge_pud() reads the old PUD and clears it in separate operations. Hardware accessed or dirty updates between those operations can be lost when the saved entry is installed at the new address.
The raw pud_clear() also bypasses page_table_check_pud_clear(), while set_pud_at() accounts for the destination mapping. This leaves the checker counts unbalanced for mappings tracked by page table checking.
To fix it, simply use pudp_huge_get_and_clear().
--- mm/mremap.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
mm/mremap.c +1 -2
@@ -400,8 +400,7 @@ static bool move_huge_pud(struct vm_area_struct *vma, unsigned long old_addr,spin_lock_nested (new_ptl,SINGLE_DEPTH_NESTING );/* Clear the pud */ - pud = *old_pud; -pud_clear (old_pud); + pud =pudp_huge_get_and_clear (mm, old_addr, old_pud);VM_BUG_ON (!pud_none (*new_pud));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 93/1756 vhost-scsi: Reduce mem use by moving upages to per queue
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Christie <[email protected]>
[ Upstream commit 4c1f3a7d74277903b290dd989cbd2ea8627fc925 ]
Each worker thread can process 1 command at a time so there's no need to allocate a upages array per cmd. This patch moves it to per queue. Even a small device with 128 cmds and 1 queue this brings mem use for the array from
2 MB = 8 bytes per page pointer * 2048 pointers * 128 cmds
to
16K = 8 bytes per pointer * 2048 * 1 queue
Message-Id: <[email protected]>
Stable-dep-of: 01c3a5fa6d64 ("vhost-scsi: zero misaligned I/O bounce pages")
--- drivers/vhost/scsi.c | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-)
drivers/vhost/scsi.c +10 -14
@@ -83,7 +83,6 @@ struct vhost_scsi_cmd {/* Pointer to the SGL formatted memory from virtio-scsi */ struct scatterlist *tvc_sgl;struct scatterlist *tvc_prot_sgl; -struct page **tvc_upages;/* Pointer to response header iovec */ struct iovec *tvc_resp_iov;/* Pointer to vhost_scsi for our device */
@@ -187,6 +186,7 @@ struct vhost_scsi_virtqueue {struct vhost_scsi_cmd *scsi_cmds;struct sbitmap scsi_tags;int max_cmds; +struct page **upages;struct vhost_work completion_work;struct llist_head completion_list;
@@ -624,7 +624,6 @@ vhost_scsi_get_cmd(struct vhost_virtqueue *vq, struct vhost_scsi_tpg *tpg,struct vhost_scsi_nexus *tv_nexus;struct scatterlist *sg, *prot_sg;struct iovec *tvc_resp_iov; -struct page **pages;int tag; tv_nexus = tpg->tpg_nexus;
@@ -642,12 +641,10 @@ vhost_scsi_get_cmd(struct vhost_virtqueue *vq, struct vhost_scsi_tpg *tpg, cmd = &svq->scsi_cmds[tag]; sg = cmd->tvc_sgl; prot_sg = cmd->tvc_prot_sgl; - pages = cmd->tvc_upages; tvc_resp_iov = cmd->tvc_resp_iov;memset (cmd,0 ,sizeof (*cmd)); cmd->tvc_sgl = sg; cmd->tvc_prot_sgl = prot_sg; - cmd->tvc_upages = pages; cmd->tvc_se_cmd.map_tag = tag; cmd->tvc_tag = scsi_tag; cmd->tvc_lun = lun;
@@ -674,7 +671,9 @@ vhost_scsi_map_to_sgl(struct vhost_scsi_cmd *cmd, struct scatterlist *sgl, bool is_prot) { -struct page **pages = cmd->tvc_upages; +struct vhost_scsi_virtqueue *svq =container_of (cmd->tvc_vq, + struct vhost_scsi_virtqueue, vq); +struct page **pages = svq->upages;struct scatterlist *sg = sgl;ssize_t bytes, mapped_bytes;size_t offset, mapped_offset;
@@ -1659,11 +1658,11 @@ static void vhost_scsi_destroy_vq_cmds(struct vhost_virtqueue *vq)kfree (tv_cmd->tvc_sgl);kfree (tv_cmd->tvc_prot_sgl); -kfree (tv_cmd->tvc_upages);kfree (tv_cmd->tvc_resp_iov); }sbitmap_free (&svq->scsi_tags); +kfree (svq->upages);kfree (svq->scsi_cmds); svq->scsi_cmds =NULL ; }
@@ -1689,6 +1688,11 @@ static int vhost_scsi_setup_vq_cmds(struct vhost_virtqueue *vq, int max_cmds)return -ENOMEM ; } + svq->upages =kcalloc (VHOST_SCSI_PREALLOC_UPAGES ,sizeof (struct page *), +GFP_KERNEL ); +if (!svq->upages) + goto out; +for (i =0 ; i < max_cmds; i++) { tv_cmd = &svq->scsi_cmds[i];
@@ -1700,14 +1704,6 @@ static int vhost_scsi_setup_vq_cmds(struct vhost_virtqueue *vq, int max_cmds) goto out; } - tv_cmd->tvc_upages =kcalloc (VHOST_SCSI_PREALLOC_UPAGES , -sizeof (struct page *), -GFP_KERNEL ); -if (!tv_cmd->tvc_upages) { -pr_err ("Unable to allocate tv_cmd->tvc_upages\n" ); - goto out; - } - tv_cmd->tvc_resp_iov =kcalloc (UIO_MAXIOV ,sizeof (struct iovec ),GFP_KERNEL );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 94/1756 vhost-scsi: zero misaligned I/O bounce pages
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shubham Antil <[email protected]>
[ Upstream commit 01c3a5fa6d641c93c7cef4fb25c5f12938316e18 ]
The misaligned I/O fallback copies the full bounce scatterlist to the request buffer during completion. If a data-in command transfers less than requested, part of a newly allocated bounce page can remain unwritten.
Allocate bounce pages with __GFP_ZERO so all bytes copied during completion have a defined value. This path is already the slow fallback for misaligned I/O, so the added initialization cost is acceptable.
Found during an LLM-assisted source audit and validated with a QEMU/KVM vhost-scsi target using misaligned data-in commands.
Message-ID: <[email protected]>
--- drivers/vhost/scsi.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
drivers/vhost/scsi.c +6 -1
@@ -771,7 +771,12 @@ vhost_scsi_copy_iov_to_sgl(struct vhost_scsi_cmd *cmd, struct iov_iter *iter, }for (i =0 ; i < sg_count; i++) { - page =alloc_page (GFP_KERNEL ); +/* +* Completion copies the full bounce buffer, including bytes the +* target did not write. This is already the slow fallback for +* misaligned I/O, so zeroing is acceptable here. +*/ + page =alloc_page (GFP_KERNEL | __GFP_ZERO);if (!page) { i--; ret = -ENOMEM ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 95/1756 quota: initialize dquot cache before mounting rootfs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: YouYou Yu <[email protected]>
[ Upstream commit e21a6f39aa6d0336ffbf5f34e5fa20ff8de36773 ]
On some systems, a tmpfs backed rootfs is extensively used throughout system's lifecycle. tmpfs quotas are needed to limit per user rootfs usage. However, booting with CONFIG_TMPFS_QUOTA=y, an initramfs, no root= and "initramfs_options=usrquota" panics at boot:
BUG: kernel NULL pointer dereference, address: 0000000000000000 RIP: 0010:dqget+0x1ac/0x490 Call Trace: __dquot_initialize dquot_initialize shmem_get_inode shmem_fill_super ... mnt_init vfs_caches_init start_kernel
The rootfs is mounted from mnt_init(), but the dquot hash table and cache are only set up later by dquot_init(), an fs_initcall. Creating the root inode of a quota enabled rootfs thus dereferences the NULL dquot_hash in dqget().
Rename dquot_init() to dquot_cache_init() and call it from vfs_caches_init() before mnt_init(). The slab, percpu and early workqueue code it relies on is available there, and the workqueue rescuer and shrinker debugfs entries are set up later by their own subsystems. Keep the sysctl registration in an fs_initcall, as done for the dcache, inode and mount sysctls. This only moves existing allocations earlier in boot.
--- fs/dcache.c | 2 ++ fs/quota/dquot.c | 10 ++++++---- include/linux/quotaops.h | 5 +++++ 3 files changed, 13 insertions(+), 4 deletions(-)
fs/dcache.c +2 -0
@@ -32,6 +32,7 @@#include <linux/bit_spinlock.h> #include <linux/rculist_bl.h> #include <linux/list_lru.h> +#include <linux/quotaops.h> #include "internal.h" #include "mount.h"
@@ -3204,6 +3205,7 @@ void __init vfs_caches_init(void)inode_init ();files_init ();files_maxfiles_init (); +dquot_cache_init ();mnt_init ();bdev_cache_init ();chrdev_init ();
fs/quota/dquot.c +6 -4
@@ -3020,7 +3020,7 @@ static struct ctl_table fs_dqstats_table[] = {#endif }; -static int __init dquot_init (void ) +void __init dquot_cache_init (void ) {int i, ret;unsigned long nr_hash, order;
@@ -3028,8 +3028,6 @@ static int __init dquot_init(void)printk (KERN_NOTICE "VFS: Disk quotas %s\n" , __DQUOT_VERSION__); -register_sysctl_init ("fs/quota" , fs_dqstats_table); - dquot_cachep = kmem_cache_create("dquot", sizeof(struct dquot), sizeof(unsigned long) * 4, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
@@ -3071,7 +3069,11 @@ static int __init dquot_init(void) WQ_UNBOUND | WQ_MEM_RECLAIM, WQ_MAX_ACTIVE);if (!quota_unbound_wq)panic ("Cannot create quota_unbound_wq\n" ); +} +static int __init init_fs_dquot_sysctls (void ) +{ +register_sysctl_init ("fs/quota" , fs_dqstats_table);return 0 ; } -fs_initcall (dquot_init); +fs_initcall (init_fs_dquot_sysctls);
include/linux/quotaops.h +5 -0
@@ -40,6 +40,7 @@ void __quota_error(struct super_block *sb, const char *func,/* * declaration of quota_function calls in kernel. */ +void dquot_cache_init (void );int dquot_initialize (struct inode *inode);bool dquot_initialize_needed (struct inode *inode);void dquot_drop (struct inode *inode);
@@ -206,6 +207,10 @@ static inline int sb_has_quota_active(struct super_block *sb, int type)return 0 ; } +static inline void dquot_cache_init (void ) +{ +} +static inline int dquot_initialize (struct inode *inode) {return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 96/1756 ksmbd: let the owner read and change the DACL when no ACE names it
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Bridges <[email protected]>
[ Upstream commit ffc855fe16afe02b22305111aa68cd8d07360941 ]
smb_check_perm_dacl() refuses the owner when neither its DACL lookup nor the POSIX ACL fallback matches. The owner then cannot read or replace the DACL over SMB. MS-DTYP 2.5.3.2 grants the owner READ_CONTROL and WRITE_DAC unless an OWNER RIGHTS ACE applies.
An empty DACL allows the owner's explicit requests for these rights but refuses MAXIMUM_ALLOWED. smb2_open() uses that check for the maximal access reply (MS-SMB2 3.3.5.9.5), so even a READ_CONTROL open fails when it asks for that reply.
Grant the owner's implicit rights on both paths, for explicit requests and MAXIMUM_ALLOWED, unless an OWNER RIGHTS ACE applies.
--- fs/smb/server/smbacl.c | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-)
fs/smb/server/smbacl.c +33 -4
@@ -27,6 +27,9 @@ static const struct smb_sid creator_owner = {/* security id for everyone/world system group */ static const struct smb_sid creator_group = {1 ,1 , {0 ,0 ,0 ,0 ,0 ,3 }, {cpu_to_le32 (1 )} }; +/* security id for owner rights */ +static const struct smb_sid sid_owner_rights = { +1 ,1 , {0 ,0 ,0 ,0 ,0 ,3 }, {cpu_to_le32 (4 )} };/* security id for everyone/world system group */ static const struct smb_sid sid_everyone = {
@@ -1466,6 +1469,7 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,int i, found =0 ;unsigned int access_bits =0 , denied =0 ;struct smb_ace *others_ace =NULL ; +bool or_ace = false;struct posix_acl_entry *pa_entry;unsigned int sid_type =SIDOWNER ;unsigned short ace_size;
@@ -1498,6 +1502,8 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, is_owner = uid ==from_kuid (&init_user_ns,vfsuid_into_kuid (vfsuid));if (!pdacl->num_aces) { +unsigned int allowed =0 ; +/* * An empty (present, zero-ACE) DACL grants no access to * anyone except the object owner's implicit READ_CONTROL
@@ -1506,9 +1512,14 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,* not let trailing bytes after a zero-ACE DACL become an * implicit grant. */ -if (!is_owner || - (*pdaccess & ~(FILE_READ_CONTROL_LE |FILE_WRITE_DAC_LE ))) +if (is_owner) + allowed =READ_CONTROL |WRITE_DAC ; +if (*pdaccess &FILE_MAXIMAL_ACCESS_LE ) + requested |= allowed; +if (!allowed || requested & ~allowed) rc = -EACCES ; +else + *pdaccess =cpu_to_le32 (requested); goto err_out; }
@@ -1585,6 +1596,9 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path, found =1 ;break ; } +if (!compare_sids (&sid_owner_rights, &ace->sid) && + !(ace->flags &INHERIT_ONLY_ACE )) + or_ace = true;if (!compare_sids (&sid_everyone, &ace->sid) || !compare_sids (&sid_authusers, &ace->sid)) others_ace = ace;
@@ -1629,8 +1643,23 @@ int smb_check_perm_dacl(struct ksmbd_conn *conn, const struct path *path,if (others_ace) { ace = others_ace; }else { -ksmbd_debug (SMB ,"Can't find corresponding sid\n" ); - rc = -EACCES ; +unsigned int allowed =0 ; + +/* +* No ACE names the owner, who may still read and +* change the DACL unless OWNER RIGHTS applies +* (MS-DTYP 2.5.3.2). +*/ +if (is_owner && !or_ace) + allowed =READ_CONTROL |WRITE_DAC ; +if (*pdaccess &FILE_MAXIMAL_ACCESS_LE ) + requested |= allowed; +if (!allowed || requested & ~allowed) { +ksmbd_debug (SMB ,"Can't find corresponding sid\n" ); + rc = -EACCES ; + goto err_out; + } + *pdaccess =cpu_to_le32 (requested); goto err_out; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 97/1756 mm/userfaultfd: compare exact registration modes before skipping
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Gregory Price <[email protected]>
[ Upstream commit 05f64f211a25f7d9771d4fde109aad97174a1cf3 ]
Changing registration from MISSING|WP to WP returns success but leaves MISSING enabled. The no-op check sees that WP is already set and skips the update, so later accesses to missing pages still wait for userspace.
Skip the update only when the current and requested UFFD modes match exactly.
--- mm/userfaultfd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
mm/userfaultfd.c +1 -1
@@ -1979,7 +1979,7 @@ int userfaultfd_register_range(struct userfaultfd_ctx *ctx,* userfaultfd and with the right tracking mode too. */ if (vma->vm_userfaultfd_ctx.ctx == ctx && - (vma->vm_flags & vm_flags) == vm_flags) + (vma->vm_flags & __VM_UFFD_FLAGS) == vm_flags) goto skip;if (vma->vm_start > start)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 98/1756 apparmor: fix query_data() output overlapping the lookup key
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cen Zhang (Microsoft) <[email protected]>
[ Upstream commit d30844001360a403a511cf24fc75ecaa6a7a7544 ]
In query_data(), buf and query point into the same multi_transaction
buffer: buf at the start, query a few bytes in, and the lookup key right after the label string that query points to. Reusing the buffer is by design and is safe as long as the query is fully parsed before buf is written to, but the key is not: it is dereferenced on every iteration of label_for_each_confined(), after output has already been written. So when the label has more than one profile with a data table, the data of the first matching profile is written to buf while the key is still needed, and overwrites it if the data is large enough. The later lookups then run on a corrupted key. Besides, if the data has no NUL byte from the key's position to the end of the allocation, strhash() -> strlen() -> jhash() reads past the 4096-byte slab object, triggering an out-of-bound read:
BUG: KASAN: slab-out-of-bounds in jhash+0x595/0x5e0 Read of size 1 at addr ff1100001159d000 by task exploit/155 CPU: 0 UID: 1000 PID: 155 Comm: exploit Not tainted 7.3.0-rc7 #1 Call Trace: jhash+0x595/0x5e0 aa_write_access+0x880/0x1400 vfs_write+0x26f/0xd20 ksys_write+0x115/0x210
Writing to the .access file is unprivileged (0666), but triggering this requires loaded profiles that carry a data table, which needs CAP_MAC_ADMIN and is not the case on default distribution policies.
Fix by copying the key with kstrdup() before writing any output to buf, so the key stays valid across all loop iterations regardless of what gets written to the overlapping buffer.
--- security/apparmor/apparmorfs.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-)
security/apparmor/apparmorfs.c +12 -3
@@ -744,7 +744,7 @@ static void profile_query_cb(struct aa_profile *profile, struct aa_perms *perms,static ssize_t query_data (char *buf,size_t buf_len,char *query,size_t query_len) { -char *out; +char *out, *keydup;const char *key;struct label_it i;struct aa_label *label, *curr;
@@ -765,11 +765,18 @@ static ssize_t query_data(char *buf, size_t buf_len,if (buf_len <sizeof (bytes) +sizeof (blocks))return -EINVAL ;/* not enough space */ +/* buf overlaps query, keep a copy of the key for the later lookups */ + keydup =kstrdup (key,GFP_KERNEL ); +if (!keydup) +return -ENOMEM ; + curr =begin_current_label_crit_section (); label =aa_label_parse (curr, query,GFP_KERNEL , false, false);end_current_label_crit_section (curr); -if (IS_ERR (label)) +if (IS_ERR (label)) { +kfree (keydup);return PTR_ERR (label); + }/* We are going to leave space for two numbers. The first is the total * number of bytes we are writing after the first number. This is so
@@ -787,13 +794,14 @@ static ssize_t query_data(char *buf, size_t buf_len,if (!profile->data)continue ; - data =rhashtable_lookup_fast (profile->data, &key, + data =rhashtable_lookup_fast (profile->data, &keydup, profile->data->p);if (data) {if (out +sizeof (outle32) + data->size > buf + buf_len) {aa_put_label (label); +kfree (keydup);return -EINVAL ;/* not enough space */ } outle32 =__cpu_to_le32 (data->size);
@@ -805,6 +813,7 @@ static ssize_t query_data(char *buf, size_t buf_len, } }aa_put_label (label); +kfree (keydup); outle32 =__cpu_to_le32 (out - buf -sizeof (bytes));memcpy (buf, &outle32,sizeof (outle32));
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 99/1756 virtio_blk: use synchronous quiesce in virtblk_freeze_priv()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Zhang <[email protected]>
[ Upstream commit 6c6dec7883f8eb10b326bc9d109a4990c885d949 ]
blk_mq_run_work_fn() can call blk_mq_sched_dispatch_requests() through blk_mq_run_dispatch_ops(). The dispatcher checks QUEUE_FLAG_QUIESCED while the flag is clear. It can then be preempted before it gets a request. At that time, it has no queue usage reference, so blk_mq_freeze_queue() does not wait for it.
virtblk_freeze_priv() then calls blk_mq_quiesce_queue_nowait() and blk_mq_unfreeze_queue(). A new request can enter the queue. The old dispatcher can run again, use its old flag check, get the new request, and call virtio_queue_rq(). At the same time, virtblk_freeze_priv() can reset the device, delete the virtqueues, and free vblk->vqs. The old dispatcher can then use a deleted virtqueue or a NULL vblk->vqs, and the kernel can crash.
Fix this by using blk_mq_quiesce_queue(), which waits for dispatch code that was already running. Keep the existing freeze and unfreeze order. The queue remains quiesced until virtblk_restore_priv() calls blk_mq_unquiesce_queue().
--- drivers/block/virtio_blk.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/virtio_blk.c +1 -1
@@ -1590,7 +1590,7 @@ static int virtblk_freeze(struct virtio_device *vdev)/* Ensure no requests in virtqueues before deleting vqs. */ blk_mq_freeze_queue (q); -blk_mq_quiesce_queue_nowait (q); +blk_mq_quiesce_queue (q);blk_mq_unfreeze_queue (q);/* Ensure we don't receive any more interrupts */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 100/1756 mm/filemap: read mapping->a_ops->free_folio under i_lock
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Josef Bacik <[email protected]>
[ Upstream commit dc24e273244e9d712257d5a6c20a32c7f5ca84e6 ]
memory_failure() -> ... -> filemap_remove_folio() can read mapping->a_ops after the inode has been freed. Once the folio is deleted from the pagecache it no longer pins the mapping, so after i_lock is dropped e.g., a concurrent final iput() can evict and free the inode before filemap_free_folio() looks up mapping->a_ops->free_folio.
Most callers hold a reference on the inode, but not all.
Documentation/filesystems/vfs.rst explicitly states that ->free_folio() must not assume the original address_space mapping still exists.
Fix it by loading ->free_folio while i_lock is still held, similar to what folio_unmap_invalidate() does.
Inline filemap_free_folio() into its remaining caller such that delete_from_page_cache_batch() also just loads the callback before dropping the i_lock.
The bug was found by code inspection and has not been reproduced.
Fix generated by an LLM and sent by Josef Bacik in private.
--- mm/filemap.c | 31 ++++++++++++++----------------- mm/internal.h | 1 - mm/truncate.c | 7 ++++++- 3 files changed, 20 insertions(+), 19 deletions(-)
mm/filemap.c +14 -17
@@ -224,20 +224,6 @@ void __filemap_remove_folio(struct folio *folio, void *shadow)page_cache_delete (mapping, folio, shadow); } -void filemap_free_folio (struct address_space *mapping,struct folio *folio) -{ -void (*free_folio)(struct folio *); -int refs =1 ; - - free_folio = mapping->a_ops->free_folio; -if (free_folio) -free_folio (folio); - -if (folio_test_large (folio)) - refs =folio_nr_pages (folio); -folio_put_refs (folio, refs); -} -/** * filemap_remove_folio - Remove folio from page cache. * @folio: The folio.
@@ -249,6 +235,7 @@ void filemap_free_folio(struct address_space *mapping, struct folio *folio)void filemap_remove_folio (struct folio *folio) {struct address_space *mapping = folio->mapping; +void (*free_folio)(struct folio *folio);BUG_ON (!folio_test_locked (folio));spin_lock (&mapping->host->i_lock);
@@ -257,9 +244,12 @@ void filemap_remove_folio(struct folio *folio)xa_unlock_irq (&mapping->i_pages);if (mapping_shrinkable (mapping))inode_add_lru (mapping->host); + free_folio = mapping->a_ops->free_folio;spin_unlock (&mapping->host->i_lock); -filemap_free_folio (mapping, folio); +if (free_folio) +free_folio (folio); +folio_put_refs (folio,folio_nr_pages (folio)); }/*
@@ -319,6 +309,7 @@ static void page_cache_delete_batch(struct address_space *mapping,void delete_from_page_cache_batch (struct address_space *mapping,struct folio_batch *fbatch) { +void (*free_folio)(struct folio *folio);int i;if (!folio_batch_count (fbatch))
@@ -336,10 +327,16 @@ void delete_from_page_cache_batch(struct address_space *mapping,xa_unlock_irq (&mapping->i_pages);if (mapping_shrinkable (mapping))inode_add_lru (mapping->host); + free_folio = mapping->a_ops->free_folio;spin_unlock (&mapping->host->i_lock); -for (i =0 ; i <folio_batch_count (fbatch); i++) -filemap_free_folio (mapping, fbatch->folios[i]); +for (i =0 ; i <folio_batch_count (fbatch); i++) { +struct folio *folio = fbatch->folios[i]; + +if (free_folio) +free_folio (folio); +folio_put_refs (folio,folio_nr_pages (folio)); + } }int filemap_check_errors (struct address_space *mapping)
mm/internal.h +0 -1
@@ -402,7 +402,6 @@ unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start, pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices);unsigned find_get_entries (struct address_space *mapping,pgoff_t *start,pgoff_t end,struct folio_batch *fbatch,pgoff_t *indices); -void filemap_free_folio (struct address_space *mapping,struct folio *folio);int truncate_inode_folio (struct address_space *mapping,struct folio *folio);bool truncate_inode_partial_folio (struct folio *folio,loff_t start,loff_t end);
mm/truncate.c +6 -1
@@ -574,6 +574,8 @@ EXPORT_SYMBOL(invalidate_mapping_pages);static int invalidate_complete_folio2 (struct address_space *mapping,struct folio *folio) { +void (*free_folio)(struct folio *folio); +if (folio->mapping != mapping)return 0 ;
@@ -590,9 +592,12 @@ static int invalidate_complete_folio2(struct address_space *mapping,xa_unlock_irq (&mapping->i_pages);if (mapping_shrinkable (mapping))inode_add_lru (mapping->host); + free_folio = mapping->a_ops->free_folio;spin_unlock (&mapping->host->i_lock); -filemap_free_folio (mapping, folio); +if (free_folio) +free_folio (folio); +folio_put_refs (folio,folio_nr_pages (folio));return 1 ; failed:xa_unlock_irq (&mapping->i_pages);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 101/1756 mm/rmap: handle device-exclusive entries in folio_referenced_one()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit f3c493d2f42b5f44a5c134d8d7ea7f960caf5e2c ]
page_vma_mapped_walk() can return non-present device-exclusive entries, but folio_referenced_one() passes them to PTE young-bit accessors that require present PTEs.
We must neither call clear_flush_young_ptes_notify() nor folio_pte_batch() with non-present entries. For example, clearing the young bit on non-present PTEs can corrupt the entry: on arm64 PTE_AF overlaps the swap type, so clearing it turns a device-exclusive entry into an ordinary swap entry.
folio_pte_batch() will VM_WARN_ON_FOLIO.
Apply the same approach as the previous fixes to e.g., damon_ptep_mkold():
treat these entries as old from the CPU's perspective and obtain their young state through the MMU notifier.
Skip PTE batching and MGLRU look-around for non-present entries, and don't modify non-present PTEs.
--- mm/rmap.c | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-)
mm/rmap.c +17 -3
@@ -850,6 +850,7 @@ static bool folio_referenced_one(struct folio *folio,DEFINE_FOLIO_VMA_WALK (pvmw, folio, vma, address,0 );int referenced =0 ;unsigned long start = address, ptes =0 ; +pte_t pteval;while (page_vma_mapped_walk (&pvmw)) { address = pvmw.address;
@@ -892,12 +893,25 @@ static bool folio_referenced_one(struct folio *folio,return false; } -if (lru_gen_enabled () && pvmw.pte) { +if (pvmw.pte) + pteval =ptep_get (pvmw.pte); + +if (lru_gen_enabled () && pvmw.pte &&pte_present (pteval)) {if (lru_gen_look_around (&pvmw)) referenced++; }else if (pvmw.pte) { -if (ptep_clear_flush_young_notify (vma, address, - pvmw.pte)) +bool young = false; + +/* +* PFN swap PTEs, such as device-exclusive ones, that +* actually map pages are "old" from a CPU perspective. +* The MMU notifier takes care of any device aspects. +*/ +if (pte_present (pteval)) + young =ptep_clear_flush_young (vma, address, pvmw.pte); + young |=mmu_notifier_clear_flush_young (vma->vm_mm, address, + address +PAGE_SIZE ); +if (young) referenced++; }else if (IS_ENABLED (CONFIG_TRANSPARENT_HUGEPAGE )) { if (pmdp_clear_flush_young_notify(vma, address,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 102/1756 fork: take mmap_lock before copying mm_struct
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit ef694e2d210111cc08c52fd25da9ab130170bfa3 ]
dup_mm() copies the parent's mm_struct before dup_mmap() takes the mmap_lock. A concurrent brk() can leave the child with a stale mm->brk and newer heap mappings, causing later brk() requests to fail.
Other operations (e.g., PR_SET_MM) on the parent's mm_struct can similarly cause inconsistencies.
As a simple and robust fix, grab the parent's mmap_lock earlier. This way we don't need to update individual mm fields in dup_mmap() and keep missing ones. Stop updating the 4 existing members (total_vm, data_vm, exec_vm, stack_vm), as that is now no longer required.
Keep releasing the parent's mmap_lock in dup_mmap(), before userfaultfd completion, to avoid moving the userfaultfd handling into the caller. This should get cleaned up later.
Move uprobe_start_dup_mmap() to preserve the lock ordering.
--- kernel/fork.c | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-)
kernel/fork.c +16 -14
@@ -641,8 +641,7 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,LIST_HEAD (uf);VMA_ITERATOR (vmi, mm,0 ); -if (mmap_write_lock_killable (oldmm)) -return -EINTR ; +mmap_assert_write_locked (oldmm);flush_cache_dup_mm (oldmm);uprobe_dup_mmap (oldmm, mm);/*
@@ -653,11 +652,6 @@ static __latent_entropy int dup_mmap(struct mm_struct *mm,/* No ordering required: file already has been exposed. */ dup_mm_exe_file (mm, oldmm); - mm->total_vm = oldmm->total_vm; - mm->data_vm = oldmm->data_vm; - mm->exec_vm = oldmm->exec_vm; - mm->stack_vm = oldmm->stack_vm; -/* Use __mt_dup() to efficiently build an identical maple tree. */ retval =__mt_dup (&oldmm->mm_mt, &mm->mm_mt,GFP_KERNEL );if (unlikely (retval))
@@ -824,7 +818,7 @@ static inline void mm_free_pgd(struct mm_struct *mm)#else static int dup_mmap (struct mm_struct *mm,struct mm_struct *oldmm) { -mmap_write_lock (oldmm); +mmap_assert_write_locked (oldmm);dup_mm_exe_file (mm, oldmm);mmap_write_unlock (oldmm);return 0 ;
@@ -1705,12 +1699,19 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,if (!mm) goto fail_nomem; +uprobe_start_dup_mmap (); +if (mmap_write_lock_killable (oldmm)) { +free_mm (mm); + goto fail_uprobe; + } +memcpy (mm, oldmm,sizeof (*mm)); -if (!mm_init (mm, tsk, mm->user_ns)) - goto fail_nomem; +if (!mm_init (mm, tsk, mm->user_ns)) { +mmap_write_unlock (oldmm); + goto fail_uprobe; + } -uprobe_start_dup_mmap (); err =dup_mmap (mm, oldmm);if (err) goto free_pt;
@@ -1729,9 +1730,10 @@ static struct mm_struct *dup_mm(struct task_struct *tsk, mm->binfmt =NULL ;mm_init_owner (mm,NULL );mmput (mm); -if (err) -uprobe_end_dup_mmap (); - +if (!err) +return NULL ; +fail_uprobe: +uprobe_end_dup_mmap (); fail_nomem:return NULL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 103/1756 ASoC: qcom: q6apm: clear g_apm on driver removal
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ajay Kumar Nandam <[email protected]>
[ Upstream commit be2172758f2b7c801ae80b9c8d1510b31eeffdaa ]
The global g_apm pointer is set during apm_probe() but never cleared in apm_remove(). After the driver is removed the devm-managed struct q6apm is freed, leaving g_apm dangling. A subsequent call to q6apm_is_adsp_ready() dereferences the freed pointer.
Clear g_apm in apm_remove() before the component is unregistered so that q6apm_is_adsp_ready() returns false instead of triggering a use-after-free.
--- sound/soc/qcom/qdsp6/q6apm.c | 1 + 1 file changed, 1 insertion(+)
sound/soc/qcom/qdsp6/q6apm.c +1 -0
@@ -795,6 +795,7 @@ static int apm_probe(gpr_device_t *gdev)static void apm_remove (gpr_device_t *gdev) { + g_apm =NULL ;of_platform_depopulate (&gdev->dev);snd_soc_unregister_component (&gdev->dev); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 104/1756 drm/amdkfd: Map wptr BO to GART unconditionally
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lang Yu <[email protected]>
[ Upstream commit 30837a49bd0aba0f311d4056cd48753955f60d40 ]
For simulation C models that don't run CP FW where adev->mes.sched_version is not populated correctly. This causes NULL dereference in amdgpu_amdkfd_free_gtt_mem(dev->adev, (void **)&pqn->q->wptr_bo_gart) and warning on unpinned BO in amdgpu_bo_gpu_offset(q->properties.wptr_bo).
Compared with adding version check here and there, always map wptr BO to GART simplifies things.
v2: Add NULL check in amdgpu_amdkfd_free_gtt_mem.(Philip)
Stable-dep-of: da2897ee8b81 ("drm/amdkfd: use the queue's process info for the WPTR BO eviction fence")
--- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c | 3 +++ .../amd/amdkfd/kfd_process_queue_manager.c | 23 ++++++++----------- 2 files changed, 13 insertions(+), 13 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.c +3 -0
@@ -368,6 +368,9 @@ void amdgpu_amdkfd_free_gtt_mem(struct amdgpu_device *adev, void **mem_obj) {struct amdgpu_bo **bo = (struct amdgpu_bo **) mem_obj; +if (!bo || !*bo) +return ; + (void )amdgpu_bo_reserve (*bo, true);amdgpu_bo_kunmap (*bo);amdgpu_bo_unpin (*bo);
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +10 -13
@@ -278,20 +278,17 @@ static int init_user_queue(struct process_queue_manager *pqm,/* Starting with GFX11, wptr BOs must be mapped to GART for MES to determine work * on unmapped queues for usermode queue oversubscription (no aggregated doorbell) */ -if (((dev->adev->mes.sched_version &AMDGPU_MES_API_VERSION_MASK ) - >>AMDGPU_MES_API_VERSION_SHIFT ) >=2 ) { -if (dev->adev !=amdgpu_ttm_adev (q_properties->wptr_bo->tbo.bdev)) { -pr_err ("Queue memory allocated to wrong device\n" ); - retval = -EINVAL ; - goto free_gang_ctx_bo; - } +if (dev->adev !=amdgpu_ttm_adev (q_properties->wptr_bo->tbo.bdev)) { +pr_err ("Queue memory allocated to wrong device\n" ); + retval = -EINVAL ; + goto free_gang_ctx_bo; + } - retval =amdgpu_amdkfd_map_gtt_bo_to_gart (q_properties->wptr_bo, - &(*q)->wptr_bo_gart); -if (retval) { -pr_err ("Failed to map wptr bo to GART\n" ); - goto free_gang_ctx_bo; - } + retval =amdgpu_amdkfd_map_gtt_bo_to_gart (q_properties->wptr_bo, + &(*q)->wptr_bo_gart); +if (retval) { +pr_err ("Failed to map wptr bo to GART\n" ); + goto free_gang_ctx_bo; } }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 105/1756 drm/amdkfd: use the queues process info for the WPTR BO eviction fence
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jesse Zhang <[email protected]>
[ Upstream commit da2897ee8b811945fd40ecc4aaf03291c14ce61c ]
amdgpu_amdkfd_map_gtt_bo_to_gart() removes the eviction fence of bo->vm_bo->vm->process_info from the WPTR BO of a new queue. bo->vm_bo is the VM which opened the BO last, not necessarily the KFD process' VM, and a render node VM has no process info.
On navi31, an unprivileged process which exports its WPTR BO with AMDKFD_IOC_EXPORT_DMABUF and imports it on a second render node fd oopses in AMDKFD_IOC_CREATE_QUEUE:
BUG: kernel NULL pointer dereference, address: 0000000000000060 RIP: 0010:amdgpu_amdkfd_map_gtt_bo_to_gart+0x86/0x1a0 [amdgpu] init_user_queue.part.0+0x180/0x250 [amdgpu] pqm_create_queue+0x32d/0x730 [amdgpu] kfd_ioctl_create_queue+0x583/0x9f0 [amdgpu]
Pass the process info of the queue instead. With the fix, the queue is created and destroyed normally.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h | 3 ++- drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c | 8 +++++--- drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c | 3 ++- 3 files changed, 9 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd.h +2 -1
@@ -324,7 +324,8 @@ int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem, void **kptr, uint64_t *size);void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel (struct kgd_mem *mem); -int amdgpu_amdkfd_map_gtt_bo_to_gart (struct amdgpu_bo *bo,struct amdgpu_bo **bo_gart); +int amdgpu_amdkfd_map_gtt_bo_to_gart (struct amdgpu_bo *bo,struct amdgpu_bo **bo_gart, +struct amdkfd_process_info *process_info);int amdgpu_amdkfd_gpuvm_restore_process_bos (void *process_info,struct dma_fence __rcu **ef);
drivers/gpu/drm/amd/amdgpu/amdgpu_amdkfd_gpuvm.c +5 -3
@@ -2248,11 +2248,13 @@ int amdgpu_amdkfd_gpuvm_sync_memory(* amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count * @bo: Buffer object to be mapped * @bo_gart: Return bo reference +* @process_info: KFD process info of the queue the BO is for * * Before return, bo reference count is incremented. To release the reference and unpin/ * unmap the BO, call amdgpu_amdkfd_free_gtt_mem. */ -int amdgpu_amdkfd_map_gtt_bo_to_gart (struct amdgpu_bo *bo,struct amdgpu_bo **bo_gart) +int amdgpu_amdkfd_map_gtt_bo_to_gart (struct amdgpu_bo *bo,struct amdgpu_bo **bo_gart, +struct amdkfd_process_info *process_info) {int ret;
@@ -2274,8 +2276,8 @@ int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_bo *bo, struct amdgpu_bo **bo goto err_map_bo_gart_failed; } -amdgpu_amdkfd_remove_eviction_fence ( - bo, bo->vm_bo->vm->process_info->eviction_fence); +/* bo->vm_bo can be the VM of any file which opened the BO */ +amdgpu_amdkfd_remove_eviction_fence (bo, process_info->eviction_fence);amdgpu_bo_unreserve (bo);
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +2 -1
@@ -285,7 +285,8 @@ static int init_user_queue(struct process_queue_manager *pqm, } retval =amdgpu_amdkfd_map_gtt_bo_to_gart (q_properties->wptr_bo, - &(*q)->wptr_bo_gart); + &(*q)->wptr_bo_gart, + pqm->process->kgd_process_info);if (retval) {pr_err ("Failed to map wptr bo to GART\n" ); goto free_gang_ctx_bo;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 106/1756 rose: walk the neighbour list under its lock when a device goes down
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_link_device_down() walks rose_neigh_list without rose_neigh_list_lock. The list can change under it: rose_add_node() and rose_del_node() from the SIOCADDRT/SIOCDELRT ioctls, and rose_rt_device_down(), which the same NETDEV_DOWN event calls right after, all add or free neighbours under that lock. The walk can then follow a neighbour that has just been freed.
Take the lock around the walk, as rose_link_failed() does around the very same calls to rose_del_route_by_neigh() and rose_kill_by_neigh().
--- net/rose/rose_route.c | 2 ++ 1 file changed, 2 insertions(+)
net/rose/rose_route.c +2 -0
@@ -958,12 +958,14 @@ void rose_link_device_down(struct net_device *dev) {struct rose_neigh *rose_neigh; +spin_lock_bh (&rose_neigh_list_lock);for (rose_neigh = rose_neigh_list; rose_neigh !=NULL ; rose_neigh = rose_neigh->next) {if (rose_neigh->dev == dev) {rose_del_route_by_neigh (rose_neigh);rose_kill_by_neigh (rose_neigh); } } +spin_unlock_bh (&rose_neigh_list_lock); }/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 107/1756 rose: hold RTNL while a route is added or deleted
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_ax25_dev_find() says it is called with RTNL, but rose_rt_ioctl() does not take it for SIOCADDRT and SIOCDELRT. __dev_get_by_name() is then used without RTNL or RCU, and the device can go down between the IFF_UP check and rose_add_node(): the NETDEV_DOWN notifier runs rose_rt_device_down(), finds no neighbour on the device yet, and the neighbour added right after keeps a pointer to a device that may be unregistered and freed, since rose_neigh->dev holds no reference.
Commit b4ec82402149 ("rose: device refcount leak") stopped taking a reference on the device because RTNL would be held, which the ioctl never did.
Take RTNL around the lookup of the device and the change of the tables. The notifier runs under RTNL too, so a neighbour is either on the list before the device goes down, where rose_rt_device_down() removes it, or not added at all.
--- net/rose/rose_route.c | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-)
net/rose/rose_route.c +13 -6
@@ -17,6 +17,7 @@#include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> +#include <linux/rtnetlink.h> #include <net/arp.h> #include <linux/if_arp.h> #include <linux/skbuff.h>
@@ -829,23 +830,29 @@ int rose_rt_ioctl(unsigned int cmd, void __user *arg)case SIOCADDRT :if (copy_from_user (&rose_route, arg,sizeof (struct rose_route_struct )))return -EFAULT ; -if ((dev =rose_ax25_dev_find (rose_route.device)) ==NULL ) -return -EINVAL ;if (rose_dev_exists (&rose_route.address))/* Can't add routes to ourself */ return -EINVAL ;if (rose_route.mask >10 )/* Mask can't be more than 10 digits */ return -EINVAL ;if (rose_route.ndigis >AX25_MAX_DIGIS )return -EINVAL ; - err =rose_add_node (&rose_route, dev); +/* +* RTNL keeps the device up until the neighbour that uses it +* is on the list, where rose_rt_device_down() finds it. +*/ +rtnl_lock (); + dev =rose_ax25_dev_find (rose_route.device); + err = dev ?rose_add_node (&rose_route, dev) : -EINVAL ; +rtnl_unlock ();return err;case SIOCDELRT :if (copy_from_user (&rose_route, arg,sizeof (struct rose_route_struct )))return -EFAULT ; -if ((dev =rose_ax25_dev_find (rose_route.device)) ==NULL ) -return -EINVAL ; - err =rose_del_node (&rose_route, dev); +rtnl_lock (); + dev =rose_ax25_dev_find (rose_route.device); + err = dev ?rose_del_node (&rose_route, dev) : -EINVAL ; +rtnl_unlock ();return err;case SIOCRSCLRRT :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 108/1756 rose: change the loopback nodes under the neighbour list lock too
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
Since commit fe2c802ab62a ("rose: improving AX25 routing frames via ROSE network"), rose_route_frame() looks up the node list through rose_get_neigh() with route_frame set, under rose_neigh_list_lock only:
it cannot take rose_node_list_lock there. Every other writer of rose_node_list holds both locks for that reason, but rose_add_loopback_node() and rose_del_loopback_node(), run when a rose device is opened, closed or given a new address, take rose_node_list_lock alone. A frame routed at that moment can walk a node that is being freed.
Take rose_neigh_list_lock inside rose_node_list_lock in both, in the same order as rose_add_node() and rose_del_node().
--- net/rose/rose_route.c | 4 ++++ 1 file changed, 4 insertions(+)
net/rose/rose_route.c +4 -0
@@ -463,6 +463,7 @@ int rose_add_loopback_node(const rose_address *address)int err =0 ;spin_lock_bh (&rose_node_list_lock); +spin_lock_bh (&rose_neigh_list_lock); rose_node = rose_node_list;while (rose_node !=NULL ) {
@@ -495,6 +496,7 @@ int rose_add_loopback_node(const rose_address *address)rose_neigh_hold (rose_loopback_neigh); out: +spin_unlock_bh (&rose_neigh_list_lock);spin_unlock_bh (&rose_node_list_lock);return err;
@@ -508,6 +510,7 @@ void rose_del_loopback_node(const rose_address *address)struct rose_node *rose_node;spin_lock_bh (&rose_node_list_lock); +spin_lock_bh (&rose_neigh_list_lock); rose_node = rose_node_list;while (rose_node !=NULL ) {
@@ -527,6 +530,7 @@ void rose_del_loopback_node(const rose_address *address)rose_neigh_put (rose_loopback_neigh); out: +spin_unlock_bh (&rose_neigh_list_lock);spin_unlock_bh (&rose_node_list_lock); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 109/1756 rose: check the length of Restart Request and Diagnostic frames
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_route_frame() only makes sure that a frame holds the three bytes of the ROSE header before it hands the frames with LCI 0 to rose_link_rx_restart(). There, a Restart Request has its cause read from byte 3 to set dce_mode, and a Diagnostic has bytes 3 to 6 printed. A peer that sends them shorter makes the kernel read past the end of the frame, and set dce_mode, which decides from which end LCIs are given out, from whatever lies there.
Only read the restarting cause when the frame has one, and leave dce_mode as it was otherwise. Ignore a Diagnostic too short to hold its diagnostic code and the three bytes it reports, as x25 does with pskb_may_pull().
--- net/rose/rose_link.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
net/rose/rose_link.c +6 -1
@@ -185,7 +185,9 @@ void rose_link_rx_restart(struct sk_buff *skb, struct rose_neigh *neigh, unsignerose_link_restarted (neigh);rose_stop_t0timer (neigh); neigh->restarted =1 ; - neigh->dce_mode = (skb->data[3 ] ==ROSE_DTE_ORIGINATED ); +/* The restarting cause, when present, tells if the peer is a DTE */ +if (skb->len >ROSE_MIN_LEN ) + neigh->dce_mode = (skb->data[3 ] ==ROSE_DTE_ORIGINATED );rose_transmit_restart_confirmation (neigh);break ;
@@ -195,6 +197,9 @@ void rose_link_rx_restart(struct sk_buff *skb, struct rose_neigh *neigh, unsignebreak ;case ROSE_DIAGNOSTIC : +/* Diagnostic code and the first three bytes of the bad packet */ +if (skb->len <ROSE_MIN_LEN +4 ) +break ;pr_warn ("ROSE: received diagnostic #%d - %3ph\n" , skb->data[3 ], skb->data +4 );break ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 110/1756 rose: keep a socket unbound when connect() fails to autobind it
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
When connect() is called on a socket that was never bound, it clears SOCK_ZAPPED first and then looks for a rose device and for the callsign of the user. If there is no rose device, or no callsign for the user, connect() fails, but the socket is left marked as bound although it has no device, no source address and is not on rose_list.
A second connect() on that socket then skips the autobind and places the call with an all-zero source address and callsign. The socket is not on rose_list, so rose_new_lci() does not see the LCI it holds and rose_find_socket() never finds it: the Call Accepted is not delivered to it and the call can only time out.
Clear SOCK_ZAPPED only once the autobind has succeeded, right before the socket goes on rose_list, as rose_bind() does.
--- net/rose/af_rose.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
net/rose/af_rose.c +2 -2
@@ -894,8 +894,6 @@ static int rose_connect(struct socket *sock, struct sockaddr *uaddr, int addr_leif (sock_flag (sk,SOCK_ZAPPED )) {/* Must bind first - autobinding in this may or may not work */ struct net_device *dev; -sock_reset_flag (sk,SOCK_ZAPPED ); - dev =rose_dev_first ();if (!dev) { err = -ENETUNREACH ;
@@ -916,6 +914,8 @@ static int rose_connect(struct socket *sock, struct sockaddr *uaddr, int addr_le GFP_KERNEL);ax25_uid_put (user); +/* Only now is the socket bound: a failed autobind leaves it as it was */ +sock_reset_flag (sk,SOCK_ZAPPED );rose_insert_socket (sk);/* Finish the bind */ }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 111/1756 rose: refuse an empty message when the Q bit is included
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
With the ROSE_QBITINCL socket option set, rose_sendmsg() takes the Q bit from the first byte of the message and pulls that byte off. Nothing checks that there is a first byte: a send() of zero bytes reads the Q bit from beyond the data copied from the user, skb_pull() fails without a word, and an empty data frame goes out with a Q bit taken from uninitialised memory.
Refuse such a message with EINVAL before anything is allocated. x25_sendmsg() checks for that byte too, with pskb_may_pull().
--- net/rose/af_rose.c | 4 ++++ 1 file changed, 4 insertions(+)
net/rose/af_rose.c +4 -0
@@ -1286,6 +1286,10 @@ static int rose_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)if (len >65535 )return -EMSGSIZE ; +/* With the Q bit included, the first byte of the data holds it */ +if (rose->qbitincl && len <1 ) +return -EINVAL ; + size = len +AX25_BPQ_HEADER_LEN +AX25_MAX_HEADER_LEN +ROSE_MIN_LEN ;if ((skb =sock_alloc_send_skb (sk, size, msg->msg_flags &MSG_DONTWAIT , &err)) ==NULL )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 112/1756 rose: give loopback answers LCIs that calls cannot be given
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
A call to an address of the node itself goes through the loopback neighbour, and both ends of it use that neighbour. rose_loopback_timer() gives the answering end LCI 51 - i for a call on LCI i, so that each end finds the other. The 51 comes from ROSE_DEFAULT_MAXVC, but the number of circuits is the maximum_virtual_circuits sysctl, which goes up to 254, and rose_new_lci() hands out LCIs from 1 up to that value on the loopback neighbour as on any other.
With more than 50 circuits allowed, the call on LCI 51 is answered on LCI 0 and the next ones on LCIs that wrap around to huge values: the answer is never matched to its call. Below that, LCI 51 - i is never checked to be free, and only the way rose_new_lci() walks the LCIs keeps it from being one that a call already uses.
Answer on LCI 4096 - i instead, at the top of the 12-bit LCI range, as was nearly done before commit 1f731b63752d ("rose_loopback_timer sets VC number <= ROSE_DEFAULT_MAXVC"): 0xFFF - i. That commit moved the answers below 51 so that /proc/net/rose would not show an LCI above the number of circuits; it prints the LCI on three hex digits, which any LCI up to 0xFFF fits. 4096 - i is still its own inverse, so each end finds the other as before, and rose_new_lci() never gives out an LCI above 254.
--- net/rose/rose_loopback.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-)
net/rose/rose_loopback.c +6 -1
@@ -101,7 +101,12 @@ static void rose_loopback_timer(struct timer_list *unused)continue ; } dest = (rose_address *)(skb->data +ROSE_CALL_REQ_DEST_ADDR_OFF ); - lci_o =ROSE_DEFAULT_MAXVC +1 - lci_i; +/* +* The call and its answer use the same neighbour: give the +* answer the LCI at the other end of the 12-bit range, which +* rose_new_lci() never hands out, and get back from it. +*/ + lci_o =0xFFF +1 - lci_i;skb_reset_transport_header (skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 113/1756 rose: clear the other half of a through route a new call takes over
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
When a Call Request comes in on the LCI of an existing through route, for a call other than the one the route was built for, the neighbour has evidently lost that call: it gives the LCI out again. rose_route_frame() then removes the route and goes on with the new call, but says nothing to the neighbour on the other half. That end keeps its virtual circuit up with nothing behind it, and its LCI on our side is freed while it may still send on it.
Do as rose_clear_routes_by_neigh() does when a neighbour goes away:
detach the half that the new call takes over and send a Clear Request on the other half. The route stays for that half until its Clear Confirmation, which removes it, and its LCI is not given to another call meanwhile. The cause is the one given to a socket in the same case, network congestion. A route that has no other half left is removed as before.
--- net/rose/rose_route.c | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-)
net/rose/rose_route.c +36 -4
@@ -1145,8 +1145,24 @@ int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25) 120); goto out; } -/* Remove an existing unused route */ -rose_remove_route (rose_route); +/* +* Another call on the LCI of a through +* route: the neighbour no longer has the +* call it was built for. Clear the other +* half, which keeps the route until its +* Clear Confirmation, and leave the LCI +* to the new call. +*/ +if (rose_route->neigh2 !=NULL ) { +rose_neigh_put (rose_route->neigh1); + rose_route->neigh1 =NULL ; +rose_transmit_clear_request (rose_route->neigh2, + rose_route->lci2, +ROSE_NETWORK_CONGESTION , +0 ); + }else { +rose_remove_route (rose_route); + }break ; }else if (rose_route->neigh2 !=NULL ) { skb->data[0 ] &=0xF0 ;
@@ -1180,8 +1196,24 @@ int rose_route_frame(struct sk_buff *skb, ax25_cb *ax25) 120); goto out; } -/* Remove an existing unused route */ -rose_remove_route (rose_route); +/* +* Another call on the LCI of a through +* route: the neighbour no longer has the +* call it was built for. Clear the other +* half, which keeps the route until its +* Clear Confirmation, and leave the LCI +* to the new call. +*/ +if (rose_route->neigh1 !=NULL ) { +rose_neigh_put (rose_route->neigh2); + rose_route->neigh2 =NULL ; +rose_transmit_clear_request (rose_route->neigh1, + rose_route->lci1, +ROSE_NETWORK_CONGESTION , +0 ); + }else { +rose_remove_route (rose_route); + }break ; }else if (rose_route->neigh1 !=NULL ) { skb->data[0 ] &=0xF0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 114/1756 rose: disconnect sockets under their lock when a neighbour goes away
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
rose_kill_by_neigh() disconnects every socket that uses a neighbour whose link has failed, restarted or gone down, holding only rose_list_lock. rose_disconnect() stops the timers, purges the queues and changes the state of the socket, but its timers and the frames received for it work on the same socket under bh_lock_sock() only, on other CPUs, and are not kept out by rose_list_lock.
Disconnect each socket under its lock. rose_rx_call_request() and rose_kill_by_device() take the socket lock before rose_list_lock, so do as rose_kill_by_device() does: take a reference on the sockets that use the neighbour under rose_list_lock, drop it, and lock each socket in turn, checking that it still uses the neighbour. The neighbour is still taken under rose_list_lock as well: rose_release() takes it under that lock while it owns the socket, which bh_lock_sock() does not keep out.
--- net/rose/af_rose.c | 48 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 41 insertions(+), 7 deletions(-)
net/rose/af_rose.c +41 -7
@@ -162,19 +162,52 @@ static void rose_remove_socket(struct sock *sk)*/ void rose_kill_by_neigh (struct rose_neigh *neigh) { -struct sock *s; +struct sock *s, *array[16 ]; +bool rescan; +int i, cnt; +/* +* Each socket is disconnected under its lock, which its timers and +* the frames received for it hold while they work on it. That lock +* is taken before rose_list_lock elsewhere, so collect the sockets +* first, as rose_kill_by_device() does. rose_list_lock is still +* held around the change of the neighbour, which rose_release() +* takes under it while it owns the socket. A socket done with has +* no neighbour left and is not collected again. +*/ +again: + rescan = false; + cnt =0 ;spin_lock_bh (&rose_list_lock);sk_for_each (s, &rose_list) { -struct rose_sock *rose =rose_sk (s); +if (rose_sk (s)->neighbour != neigh) +continue ; +if (cnt ==ARRAY_SIZE (array)) { + rescan = true; +break ; + } +sock_hold (s); + array[cnt++] = s; + } +spin_unlock_bh (&rose_list_lock); + +for (i =0 ; i < cnt; i++) { +struct rose_sock *rose =rose_sk (array[i]); +bh_lock_sock (array[i]); +/* rose_release() takes the neighbour under rose_list_lock */ +spin_lock_bh (&rose_list_lock);if (rose->neighbour == neigh) { -rose_disconnect (s,ENETUNREACH ,ROSE_OUT_OF_ORDER ,0 ); +rose_disconnect (array[i],ENETUNREACH ,ROSE_OUT_OF_ORDER ,0 );rose_neigh_put (rose->neighbour); rose->neighbour =NULL ; } +spin_unlock_bh (&rose_list_lock); +bh_unlock_sock (array[i]); +sock_put (array[i]); } -spin_unlock_bh (&rose_list_lock); +if (rescan) + goto again; }/*
@@ -721,9 +754,10 @@ static int rose_release(struct socket *sock)* Disconnect before the socket lock is dropped: frames put on * the backlog meanwhile, a Clear Confirmation for one, then * find it in state 0 instead of dropping the neighbour -* reference a second time. rose_kill_by_neigh() does not take -* the socket lock: take the neighbour under rose_list_lock, as -* it does, so that only one of them drops the reference. +* reference a second time. rose_kill_by_neigh() can run while +* the socket is owned here: take the neighbour under +* rose_list_lock, as it does, so that only one of them drops +* the reference. */ rose_disconnect (sk,0 ,-1 ,-1 );spin_lock_bh (&rose_list_lock);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 115/1756 hdlcdrv: close the hardware driver once, and only if it was opened
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bernard Pidoux <[email protected]>
hdlcdrv_unregister() calls the hardware driver's close() when s->opened is set and then calls unregister_netdev(). Two things go wrong:
- if the interface is still up, unregister_netdev() closes it through ndo_stop, so hdlcdrv_close() calls the hardware driver's close() a second time;
- hdlcdrv_open() sets s->opened before it calls the hardware driver's open() and leaves it set when that fails, so close() is also called for a port that was never opened.
The close() methods of the baycom drivers are not written for either case. baycom_ser_fdx and baycom_ser_hdx call free_irq() and release_region() for resources they do not hold. baycom_par dereferences bc->pdev, which is NULL if the port was never opened and points to an unregistered parport device after a first close.
Set s->opened only once the hardware driver's open() has succeeded, and let unregister_netdev() do the closing.
Tested in a QEMU guest (6.12.94, KASAN and lockdep) with baycom_ser_fdx and two ports: bcsf0 at an address without a UART, whose open fails, and bcsf1 on a UART, left up. Unloading baycom_ser_fdx gave before the change:
Trying to free already-free IRQ 5
ser12_close+0xa1/0x190 [baycom_ser_fdx] cleanup_baycomserfdx+0x38/0x50 [baycom_ser_fdx] resource: Trying to free nonexistent resource <0x300-0x307> baycom_ser_fdx: close ser_fdx at iobase 0x250 irq 9 Trying to free already-free IRQ 9 resource: Trying to free nonexistent resource <0x250-0x257>
and after the change a single close of bcsf1 and no warning. The baycom_par case was not reproduced, the test kernel has no parport support.
--- drivers/net/hamradio/hdlcdrv.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/net/hamradio/hdlcdrv.c +2 -3
@@ -441,7 +441,6 @@ static int hdlcdrv_open(struct net_device *dev)/* * initialise some variables */ - s->opened =1 ; s->hdlcrx.hbuf.rd = s->hdlcrx.hbuf.wr =0 ; s->hdlcrx.in_hdlc_rx =0 ; s->hdlcrx.rx_state =0 ;
@@ -458,6 +457,7 @@ static int hdlcdrv_open(struct net_device *dev) i = s->ops->open (dev);if (i)return i; + s->opened =1 ;netif_start_queue (dev);return 0 ; }
@@ -725,8 +725,7 @@ void hdlcdrv_unregister(struct net_device *dev)BUG_ON (s->magic !=HDLCDRV_MAGIC ); -if (s->opened && s->ops->close) - s->ops->close (dev); +/* unregister_netdev() closes the device if it is still up */ unregister_netdev (dev);free_netdev (dev);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 116/1756 mm/shmem: make shmem_file() check the files inode
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit d3710111839d11339e414b1bb3fea3d05ab83f6e ]
shmem_file() only checks if file->f_mapping is a shmem mapping. This mapping can belong to another file, however, as with a Coda file backed by a tmpfs container after mmap().
So it does not guarantee that the file inode is an actual shmem inode.
Seal handling and memfd preservation use this check before accessing shmem inode state, so they can access an inode of the wrong type.
Let's make shmem_file() check the inode's file operations instead, to identify shmem inodes reliably. This will identify regular shmem inodes, including memfds and ordinary tmpfs files, independently of wrapper file operations.
Use shmem_mapping() in collapse_file() instead to not change the behavior of collapse_file(): it operates on the page cache and uses mapping->host for shmem inode operations. Focusing on the file does not seem relevant.
--- include/linux/shmem_fs.h | 15 ++++++--------- mm/khugepaged.c | 2 +- mm/shmem.c | 5 +++++ 3 files changed, 12 insertions(+), 10 deletions(-)
include/linux/shmem_fs.h +6 -9
@@ -97,8 +97,14 @@ extern unsigned long shmem_get_unmapped_area(struct file *, unsigned long addr, unsigned long len, unsigned long pgoff, unsigned long flags);extern int shmem_lock (struct file *file,int lock,struct ucounts *ucounts);#ifdef CONFIG_SHMEM +bool shmem_file (struct file *file);bool shmem_mapping (struct address_space *mapping);#else +static inline bool shmem_file (struct file *file) +{ +return false; +} +static inline bool shmem_mapping (struct address_space *mapping) {return false;
@@ -161,15 +167,6 @@ static inline struct page *shmem_read_mapping_page( mapping_gfp_mask(mapping)); } -static inline bool shmem_file (struct file *file) -{ -if (!IS_ENABLED (CONFIG_SHMEM )) -return false; -if (!file || !file->f_mapping) -return false; -return shmem_mapping (file->f_mapping); -} -/* * If fallocate(FALLOC_FL_KEEP_SIZE) has been used, there may be pages * beyond i_size's notion of EOF, which fallocate has committed to reserving:
mm/khugepaged.c +1 -1
@@ -1809,6 +1809,7 @@ static int collapse_file(struct mm_struct *mm, unsigned long addr, struct collapse_control *cc) {struct address_space *mapping = file->f_mapping; +const bool is_shmem =shmem_mapping (mapping);struct page *dst;struct folio *folio, *tmp, *new_folio;unsigned long new_pfn =-1 ;
@@ -1816,7 +1817,6 @@ static int collapse_file(struct mm_struct *mm, unsigned long addr,LIST_HEAD (pagelist);XA_STATE_ORDER (xas, &mapping->i_pages, start,HPAGE_PMD_ORDER );int nr_none =0 , result =SCAN_SUCCEED ; -bool is_shmem =shmem_file (file);bool do_readahead = false;bool readahead_done = false;
mm/shmem.c +5 -0
@@ -270,6 +270,11 @@ static const struct vm_operations_struct shmem_vm_ops;static const struct vm_operations_struct shmem_anon_vm_ops;static struct file_system_type shmem_fs_type; +bool shmem_file (struct file *file) +{ +return file &&file_inode (file)->i_fop == &shmem_file_operations; +} +bool shmem_mapping (struct address_space *mapping) {return mapping->a_ops == &shmem_aops;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 117/1756 drm/i915/display: Add enabled pipe planes into state for selective fetch
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jouni Högander <[email protected]>
[ Upstream commit 94cb1f08b197d9ae932ff98c741bd0dbc96e17e8 ]
Selective fetch support for biplanar formats relies on linking of UV and the Y planes. Planes that are not part of the atomic state are pulled in by the drm_atomic_add_affected_planes. If the UV plane is added into the state by drm_atomic_add_affected_planes in the selective fetch calculation, the linking isn't done anymore and the Y plane is left disabled.
Fix this by adding affected planes already in intel_add_affected_planes if selective fetch is enabled.
Remove redundant drm_atomic_add_affected_planes from intel_psr2_sel_fetch_update and redundant check for plane selective fetch support that is not needed as all planes are already in atomic state on first loop iterating them. Also switch to intel_atomic_get_new_plane_state for linked plane new plane state.
--- drivers/gpu/drm/i915/display/intel_display.c | 12 ++++++++++ drivers/gpu/drm/i915/display/intel_psr.c | 25 +++++++------------- 2 files changed, 20 insertions(+), 17 deletions(-)
drivers/gpu/drm/i915/display/intel_display.c +12 -0
@@ -5879,6 +5879,18 @@ static int intel_atomic_check_planes(struct intel_atomic_state *state)struct intel_crtc *crtc;int i, ret; +for_each_new_intel_crtc_in_state (state, crtc, new_crtc_state, i) { +/* +* Add affected plane here to ensure UV and Y plane linking is +* in place if UV plane is added as a part of selective update. +*/ +if (new_crtc_state->enable_psr2_sel_fetch) { + ret =intel_atomic_add_affected_planes (state, crtc); +if (ret) +return ret; + } + } + ret =icl_add_linked_planes (state);if (ret)return ret;
drivers/gpu/drm/i915/display/intel_psr.c +8 -17
@@ -2561,7 +2561,7 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state, .y2 = crtc_state->hw.adjusted_mode.crtc_vdisplay, };bool full_update = false, su_area_changed; -int i, ret; +int i;/* * Selective fetch is not always usable, for instance it is dropped
@@ -2676,19 +2676,15 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,intel_psr_apply_su_area_workarounds (crtc_state); - ret =drm_atomic_add_affected_planes (&state->base, &crtc->base); -if (ret) -return ret; - do { bool cursor_in_su_area = false; /* * Adjust su area to cover cursor fully as necessary - * (early transport). This needs to be done after - * drm_atomic_add_affected_planes to ensure visible - * cursor is added into affected planes even when - * cursor is not updated by itself. + * (early transport). A visible cursor is in the state + * even when it is not updated by itself as all planes + * of the pipe are added into the state before the plane + * checks when selective fetch is enabled. */ intel_psr2_sel_fetch_et_alignment(state, crtc, &display_area, &cursor_in_su_area);
@@ -2739,11 +2735,6 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,continue ; } -if (!psr2_sel_fetch_plane_state_supported (new_plane_state)) { - full_update = true; -break ; - } - sel_fetch_area = &new_plane_state->psr2_sel_fetch_area; sel_fetch_area->y1 = inter.y1 - new_plane_state->uapi.dst.y1; sel_fetch_area->y2 = inter.y2 - new_plane_state->uapi.dst.y1;
@@ -2757,9 +2748,9 @@ int intel_psr2_sel_fetch_update(struct intel_atomic_state *state,struct intel_plane_state *linked_new_plane_state;struct drm_rect *linked_sel_fetch_area; - linked_new_plane_state =intel_atomic_get_plane_state (state, linked); -if (IS_ERR (linked_new_plane_state)) -return PTR_ERR (linked_new_plane_state); + linked_new_plane_state =intel_atomic_get_new_plane_state (state, linked); +if (!linked_new_plane_state) +return -EINVAL ; linked_sel_fetch_area = &linked_new_plane_state->psr2_sel_fetch_area; linked_sel_fetch_area->y1 = sel_fetch_area->y1;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 118/1756 nvmet: reject keep-alive timeouts that would overflow
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yingjie Wang <[email protected]>
[ Upstream commit 96ae13f40ce5930cd58c43128e385131476f2a66 ]
nvmet_set_feat_kato() and nvmet_alloc_ctrl() convert the 32-bit millisecond KATO from the host to seconds with DIV_ROUND_UP(kato, 1000). The addition in DIV_ROUND_UP() is done in 32 bits, so any KATO above 4294966296 ms wraps around and rounds to 0 seconds. A Set Features command with KATO 0xffffffff then succeeds but disables the keep-alive
timer: Get Features returns 0 and Keep Alive fails with Keep Alive Timeout Invalid. A Connect command with such a KATO creates a controller without a keep-alive timer.
The converted value has more consumers that can overflow. Get Features multiplies it by 1000, and the timer paths multiply it by HZ in 32 bits and arm a delay that must not exceed MAX_JIFFY_OFFSET.
Reject a KATO whose rounded value does not fit all of these. Return Keep Alive Timeout Invalid from both Set Features and Connect. Validate Set Features before stopping the current timer so a failed update leaves its timeout unchanged. Round in 64 bits. A KATO of 0 keeps its current meaning.
--- drivers/nvme/target/admin-cmd.c | 7 ++++++- drivers/nvme/target/core.c | 7 ++++++- drivers/nvme/target/nvmet.h | 8 ++++++++ 3 files changed, 20 insertions(+), 2 deletions(-)
drivers/nvme/target/admin-cmd.c +6 -1
@@ -811,8 +811,13 @@ u16 nvmet_set_feat_kato(struct nvmet_req *req) {u32 val32 =le32_to_cpu (req->cmd->common.cdw11); +if (val32 >NVMET_MAX_KATO *MSEC_PER_SEC ) { + req->error_loc = offsetof(struct nvme_common_command , cdw11); +return NVME_SC_KA_TIMEOUT_INVALID |NVME_STATUS_DNR ; + } +nvmet_stop_keep_alive_timer (req->sq->ctrl); - req->sq->ctrl->kato =DIV_ROUND_UP (val32,1000 ); + req->sq->ctrl->kato =DIV_ROUND_UP_ULL (val32,MSEC_PER_SEC );nvmet_start_keep_alive_timer (req->sq->ctrl);nvmet_set_result (req, req->sq->ctrl->kato);
drivers/nvme/target/core.c +6 -1
@@ -1422,6 +1422,11 @@ u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn,int ret;u16 status; +if (kato >NVMET_MAX_KATO *MSEC_PER_SEC ) { + req->error_loc = offsetof(struct nvmf_connect_command , kato); +return NVME_SC_KA_TIMEOUT_INVALID |NVME_STATUS_DNR ; + } + status =NVME_SC_CONNECT_INVALID_PARAM |NVME_STATUS_DNR ; subsys =nvmet_find_get_subsys (req->port, subsysnqn);if (!subsys) {
@@ -1487,7 +1492,7 @@ u16 nvmet_alloc_ctrl(const char *subsysnqn, const char *hostnqn, kato =NVMET_DISC_KATO_MS ;/* keep-alive timeout in seconds */ - ctrl->kato =DIV_ROUND_UP (kato,1000 ); + ctrl->kato =DIV_ROUND_UP_ULL (kato,MSEC_PER_SEC ); ctrl->err_counter =0 ;spin_lock_init (&ctrl->error_lock);
drivers/nvme/target/nvmet.h +8 -0
@@ -7,6 +7,7 @@#define _NVMET_H#include <linux/dma-mapping.h> +#include <linux/jiffies.h> #include <linux/types.h> #include <linux/device.h> #include <linux/kref.h>
@@ -586,6 +587,13 @@ bool nvmet_subsys_nsid_exists(struct nvmet_subsys *subsys, u32 nsid);#define NVMET_KAS 10#define NVMET_DISC_KATO_MS 120000 +/* +* Largest keep-alive timeout in seconds that can be reported back in +* milliseconds and converted to jiffies without overflowing. +*/ +#define NVMET_MAX_KATO \ + min3(U32_MAX / MSEC_PER_SEC, U32_MAX / HZ, MAX_JIFFY_OFFSET / HZ) +int __init nvmet_init_configfs (void ); void __exit nvmet_exit_configfs(void);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 119/1756 drm/amd/display: Minimize wait for pending updates
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilya Bakoulin <[email protected]>
[ Upstream commit caccee7b296b1f6c37f09b5d4808606c66438e9d ]
[Why/How]
Move the wait for pending updates past prepare_bandwidth if the previous update was not a full update to reduce the average time it takes to complete a full update.
Stable-dep-of: f3afbf7d832a ("drm/amd/display: Reset DET of HUBPs without a plane before outstanding updates")
--- drivers/gpu/drm/amd/display/dc/core/dc.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/display/dc/core/dc.c +4 -1
@@ -3802,7 +3802,7 @@ static void commit_planes_for_stream(struct dc *dc,dc_exit_ips_for_hw_access (dc);dc_z10_restore (dc); -if (update_type ==UPDATE_TYPE_FULL ) +if (update_type ==UPDATE_TYPE_FULL && dc->optimized_required)hwss_process_outstanding_hw_updates (dc, dc->current_state);for (i =0 ; i < dc->res_pool->pipe_count; i++) {
@@ -3829,6 +3829,9 @@ static void commit_planes_for_stream(struct dc *dc,context_clock_trace (dc, context); } +if (update_type ==UPDATE_TYPE_FULL ) +hwss_wait_for_outstanding_hw_updates (dc, dc->current_state); + top_pipe_to_program =resource_get_otg_master_for_stream ( &context->res_ctx, stream);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 120/1756 drm/amd/display: Reset DET of HUBPs without a plane before outstanding updates
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Roman Li <[email protected]>
[ Upstream commit f3afbf7d832ab138655afc96bd42226775d03ce7 ]
[WHY]
DC asserts with:
WARNING: dc/hubbub/dcn401/dcn401_hubbub.c at dcn401_program_compbuf_segments
Call Trace: <TASK> dcn401_program_outstanding_updates+0x36/0x60 [amdgpu] hwss_process_outstanding_hw_updates+0x33/0x40 [amdgpu] commit_planes_for_stream+0x171f/0x1ff0 [amdgpu] dc_update_state_execute+0xaa/0x170 [amdgpu] dc_update_planes_and_stream+0x42/0x70 [amdgpu] amdgpu_dm_atomic_commit_tail+0x16a9/0x4020 [amdgpu] commit_tail+0xc3/0x1b0 [drm_kms_helper]
The DET left by the VBIOS on a HUBP without a plane can be larger than the DET planned for the new state. The compbuf is sized for the planned DET, so DET + compbuf can exceed the CRB size. Programming the compbuf then triggers the ASSERT and sets CONFIG_ERROR in hardware.
[HOW]
Release the DET of HUBPs without a plane before the compbuf is programmed.
Add hwss_reset_unused_det() and call it in the commit and flip paths, to cover both seamless and non-seamless boots.
--- drivers/gpu/drm/amd/display/dc/core/dc.c | 6 +++- .../drm/amd/display/dc/core/dc_hw_sequencer.c | 32 +++++++++++++++++++ .../drm/amd/display/dc/hwss/hw_sequencer.h | 3 ++ 3 files changed, 40 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/display/dc/core/dc.c +5 -1
@@ -2062,6 +2062,8 @@ static enum dc_status dc_commit_state_no_check(struct dc *dc, struct dc_state *c* update pending complete before optimizing bandwidth. */ hwss_wait_for_odm_update_pending_complete (dc, context); +/* No DET may stay allocated to a HUBP without a plane (e.g. left over from VBIOS) */ +hwss_reset_unused_det (dc, context);/* pplib is notified if disp_num changed */ dc->hwss.optimize_bandwidth (dc, context);/* Need to do otg sync again as otg could be out of sync due to otg
@@ -3802,8 +3804,10 @@ static void commit_planes_for_stream(struct dc *dc,dc_exit_ips_for_hw_access (dc);dc_z10_restore (dc); -if (update_type ==UPDATE_TYPE_FULL && dc->optimized_required) +if (update_type ==UPDATE_TYPE_FULL && dc->optimized_required) { +hwss_reset_unused_det (dc, dc->current_state);hwss_process_outstanding_hw_updates (dc, dc->current_state); + }for (i =0 ; i < dc->res_pool->pipe_count; i++) {struct pipe_ctx *pipe = &context->res_ctx.pipe_ctx[i];
drivers/gpu/drm/amd/display/dc/core/dc_hw_sequencer.c +32 -0
@@ -32,6 +32,7 @@#include "resource.h" #include "dc_dmub_srv.h" #include "dc_state_priv.h" +#include "dchubbub.h" #define NUM_ELEMENTS (a) (sizeof(a) / sizeof((a)[0]))
@@ -1056,6 +1057,37 @@ void hwss_wait_for_odm_update_pending_complete(struct dc *dc, struct dc_state *chwss_wait_for_all_blank_complete (dc, context); } +void hwss_reset_unused_det (struct dc *dc,struct dc_state *context) +{ +struct hubbub *hubbub = dc->res_pool->hubbub; +unsigned int i, j; + +if (!hubbub || !hubbub->funcs->program_det_segments) +return ; + +for (i =0 ; i < dc->res_pool->pipe_count; i++) { +struct hubp *hubp = dc->res_pool->hubps[i]; +bool hubp_in_use = false; + +if (!hubp) +continue ; + +for (j =0 ; j < dc->res_pool->pipe_count; j++) { +const struct pipe_ctx *pipe = &context->res_ctx.pipe_ctx[j]; + +/* A plane-less pipe renders from the DPG, its HUBP (assigned with the stream) needs no DET */ +if (pipe->plane_state && pipe->plane_res.hubp && + pipe->plane_res.hubp->inst == hubp->inst) { + hubp_in_use = true; +break ; + } + } + +if (!hubp_in_use) + hubbub->funcs->program_det_segments (hubbub, hubp->inst,0 ); + } +} +void hwss_wait_for_no_pipes_pending (struct dc *dc,struct dc_state *context) {int i;
drivers/gpu/drm/amd/display/dc/hwss/hw_sequencer.h +3 -0
@@ -537,6 +537,9 @@ void hwss_wait_for_odm_update_pending_complete(struct dc *dc,void hwss_wait_for_no_pipes_pending (struct dc *dc,struct dc_state *context); +void hwss_reset_unused_det (struct dc *dc, +struct dc_state *context); +void hwss_wait_for_outstanding_hw_updates (struct dc *dc,struct dc_state *dc_context);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 121/1756 mm/shmem: fix accounting of swapin-error markers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Hildenbrand (Arm) <[email protected]>
[ Upstream commit 66ce68a249f4ac56cd6968aa6d8ded20fb4b7d09 ]
A failed swap read replaces the swap entry with a swapin-error marker in the page-cache and subtracts its pages from "alloced" and "swapped"; however, it leaves their block charge in place.
Removing the marker during truncate then subtracts from "swapped" again. This can underflow the counters or make swapped reach zero while other pages remain swapped out, causing swapoff to loop without finding them.
When installing the marker, subtract only from "swapped" and let shmem_recalc_inode() reduce "alloced" and release the block charge.
Make shmem_free_swap() report successful removal separately from the number of swap pages freed, so removing a swapin-error marker does not subtract from "swapped" again.
It's a bit confusing, but replacing a swapped out page by a swapin-error marker in shmem_set_folio_swapin_error() behaves as follows:
Initially:
alloced=1, swapped=1, nrpages=0 Calling shmem_recalc_inode(inode, 0, -1) -> swapped = 0 -> freed = 1 - 0 - 0 = 1 -> alloced -= freed -> alloced=0, swapped=0, block charge released
--- mm/shmem.c | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-)
mm/shmem.c +17 -18
@@ -873,14 +873,14 @@ static void shmem_delete_from_page_cache(struct folio *folio, void *radswap) }/* -* Remove swap entry from page cache, free the swap and its page cache. Returns -* the number of pages being freed. 0 means entry not found in XArray (0 pages -* being freed). +* Remove a swap entry or swapin-error marker wholly within [index, end]. +* Return whether it was removed, counting freed swap pages in nr_swaps_freed. */ -static long shmem_free_swap (struct address_space *mapping, -pgoff_t index,pgoff_t end,void *radswap) +static bool shmem_free_swap (struct address_space *mapping, +pgoff_t index,pgoff_t end,void *radswap,long *nr_swaps_freed) {XA_STATE (xas, &mapping->i_pages, index); +const swp_entry_t swp =radix_to_swp_entry (radswap);unsigned int nr_pages =0 ;pgoff_t base;void *entry;
@@ -897,8 +897,11 @@ static long shmem_free_swap(struct address_space *mapping, }xas_unlock_irq (&xas); -if (nr_pages) -free_swap_and_cache_nr (radix_to_swp_entry (radswap), nr_pages); +/* A swapin-error marker holds no swap slot, so just drop it. */ +if (nr_pages && !non_swap_entry (swp)) { +free_swap_and_cache_nr (swp, nr_pages); + *nr_swaps_freed += nr_pages; + }return nr_pages; }
@@ -1051,8 +1054,8 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,if (xa_is_value (folio)) {if (unfalloc)continue ; - nr_swaps_freed +=shmem_free_swap (mapping, indices[i], - end -1 , folio); +shmem_free_swap (mapping, indices[i], end -1 , + folio, &nr_swaps_freed);continue ; }
@@ -1119,13 +1122,11 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend,if (xa_is_value (folio)) {int order; -long swaps_freed;if (unfalloc)continue ; - swaps_freed =shmem_free_swap (mapping, indices[i], - end -1 , folio); -if (!swaps_freed) { +if (!shmem_free_swap (mapping, indices[i], end -1 , + folio, &nr_swaps_freed)) {pgoff_t base = indices[i]; order = shmem_confirm_swap(mapping, indices[i],
@@ -1146,7 +1147,6 @@ static void shmem_undo_range(struct inode *inode, loff_t lstart, loff_t lend, index = base;break ; } - nr_swaps_freed += swaps_freed;continue ; }
@@ -2071,11 +2071,10 @@ static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,folio_wait_writeback (folio);delete_from_swap_cache (folio);/* -* Don't treat swapin error folio as alloced. Otherwise inode->i_blocks -* won't be 0 when inode is released and thus trigger WARN_ON(i_blocks) -* in shmem_evict_inode(). +* Let shmem_recalc_inode() reduce alloced and release the block charge +* for the freed swap pages. */ -shmem_recalc_inode (inode, -nr_pages, -nr_pages); +shmem_recalc_inode (inode,0 , -nr_pages);swap_free_nr (swap, nr_pages); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 122/1756 mm/cma: accept memory of CMA areas reserved at a fixed address
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mike Rapoport (Microsoft) <[email protected]>
[ Upstream commit f8f9cbc34a309a388c052706f3329d1b52985aa3 ]
CMA areas allocated from memblock have their memory accepted by memblock_alloc_range_nid(), but areas reserved at a fixed address with memblock_reserve() are not.
If a fixed CMA area is requested by the cma=<size>@<base> command line parameter, it may be in regular RAM and on TDX and SEV-SNP guests it must be accepted.
Accept the memory of fixed CMA areas as well, so that all CMA areas are accepted regardless of how they were reserved.
--- mm/cma.c | 2 ++ 1 file changed, 2 insertions(+)
mm/cma.c +2 -0
@@ -313,6 +313,8 @@ int __init cma_declare_contiguous_nid(phys_addr_t base, ret = -EBUSY ; goto err; } + +accept_memory (base, size); }else {phys_addr_t addr =0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 123/1756 ovl: inherit FMODE_NONOTIFY when reading directory layers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amir Goldstein <[email protected]>
[ Upstream commit 9ff338af0e002fe217cfa16b1289b76f6b21fc72 ]
Listing a merged or impure overlay directory opens the real layer directories from ovl_dir_read(), when the readdir cache is filled. Those opens use plain ovl_path_open(), so when the directory fd is one that fanotify created for a permission event, they can still raise FS_OPEN_PERM. A listener that also marks the backing filesystem and calls getdents() on the event fd before answering then deadlocks the same way as with the directory open fixed by the previous commit.
Store the overlay user file in struct ovl_readdir_data and pass it to ovl_path_open_realfile() from ovl_dir_read(), for both the merged and the impure cache. Internal readers such as ovl_check_empty_dir() and the mount-time workdir cleanup still pass no user file.
A note about severity and real world impact: The FAN_OPEN_PERM event is traditionally used by anti-malware protection agents and security/audit agents. The scope that is often used in those use cases is FAN_MARK_MOUNT and agents typically monitor multiple mounts in a mount namespace. FAN_OPEN_PERM from directory open requires user opt-in with FAN_ONDIR. It is often not the case that anti-malware agents monitor open of directories. Security/audit engines are more likely to opt-into FAN_OPEN_PERM on directories, but are less likely to list the content of a directory within the scope of FAN_OPEN_PERM event, so the real world impact of this bug is likely not significant.
--- fs/overlayfs/readdir.c | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-)
fs/overlayfs/readdir.c +20 -11
@@ -38,6 +38,7 @@ struct ovl_dir_cache {struct ovl_readdir_data {struct dir_context ctx; +const struct file *user_file;struct dentry *dentry;bool is_lowest;struct rb_root *root;
@@ -299,9 +300,13 @@ static inline int ovl_dir_read(const struct path *realpath, struct ovl_readdir_data *rdd) {struct file *realfile; +int flags =O_RDONLY |O_LARGEFILE ;int err; - realfile =ovl_path_open (realpath,O_RDONLY |O_LARGEFILE ); +if (rdd->user_file &&FMODE_FSNOTIFY_NONE (rdd->user_file->f_mode)) + flags |= __FMODE_NONOTIFY; + + realfile =ovl_path_open (realpath, flags);if (IS_ERR (realfile))return PTR_ERR (realfile);
@@ -345,12 +350,13 @@ static void ovl_dir_reset(struct file *file) }static int ovl_dir_read_merged (struct dentry *dentry,struct list_head *list, -struct rb_root *root) +struct rb_root *root,const struct file *user_file) {int err;struct path realpath;struct ovl_readdir_data rdd = { .ctx.actor = ovl_fill_merge, + .user_file = user_file, .dentry = dentry, .list = list, .root = root,
@@ -397,9 +403,10 @@ static void ovl_seek_cursor(struct ovl_dir_file *od, loff_t pos) od->cursor = p; } -static struct ovl_dir_cache *ovl_cache_get (struct dentry *dentry) +static struct ovl_dir_cache *ovl_dir_cache_get (struct file *file) {int res; +struct dentry *dentry = file->f_path.dentry;struct ovl_dir_cache *cache;struct inode *inode =d_inode (dentry);
@@ -419,7 +426,7 @@ static struct ovl_dir_cache *ovl_cache_get(struct dentry *dentry)INIT_LIST_HEAD (&cache->entries); cache->root =RB_ROOT ; - res =ovl_dir_read_merged (dentry, &cache->entries, &cache->root); + res =ovl_dir_read_merged (dentry, &cache->entries, &cache->root, file);if (res) {ovl_cache_free (&cache->entries);kfree (cache);
@@ -563,14 +570,15 @@ static bool ovl_fill_plain(struct dir_context *ctx, const char *name,return true; } -static int ovl_dir_read_impure (const struct path *path,struct list_head *list, -struct rb_root *root) +static int ovl_dir_read_impure (const struct path *path,struct list_head *list, +struct rb_root *root,const struct file *user_file) {int err;struct path realpath;struct ovl_cache_entry *p, *n;struct ovl_readdir_data rdd = { .ctx.actor = ovl_fill_plain, + .user_file = user_file, .list = list, .root = root, };
@@ -608,9 +616,10 @@ static int ovl_dir_read_impure(const struct path *path, struct list_head *list,return 0 ; } -static struct ovl_dir_cache *ovl_cache_get_impure (const struct path *path) +static struct ovl_dir_cache *ovl_cache_get_impure (struct file *file) {int res; +const struct path *path = &file->f_path;struct dentry *dentry = path->dentry;struct inode *inode =d_inode (dentry);struct ovl_fs *ofs =OVL_FS (dentry->d_sb);
@@ -628,7 +637,7 @@ static struct ovl_dir_cache *ovl_cache_get_impure(const struct path *path)if (!cache)return ERR_PTR (-ENOMEM ); - res =ovl_dir_read_impure (path, &cache->entries, &cache->root); + res =ovl_dir_read_impure (path, &cache->entries, &cache->root, file);if (res) {ovl_cache_free (&cache->entries);kfree (cache);
@@ -744,7 +753,7 @@ static int ovl_iterate_real(struct file *file, struct dir_context *ctx)dput (parent);if (ovl_is_impure_dir (file)) { - rdt.cache =ovl_cache_get_impure (&file->f_path); + rdt.cache =ovl_cache_get_impure (file);if (IS_ERR (rdt.cache))return PTR_ERR (rdt.cache); }
@@ -792,7 +801,7 @@ static int ovl_iterate(struct file *file, struct dir_context *ctx)if (!od->cache) {struct ovl_dir_cache *cache; - cache =ovl_cache_get (dentry); + cache =ovl_dir_cache_get (file); err =PTR_ERR (cache);if (IS_ERR (cache)) goto out;
@@ -1007,7 +1016,7 @@ int ovl_check_empty_dir(struct dentry *dentry, struct list_head *list)const struct cred *old_cred; old_cred =ovl_override_creds (dentry->d_sb); - err =ovl_dir_read_merged (dentry, list, &root); + err =ovl_dir_read_merged (dentry, list, &root,NULL );revert_creds (old_cred);if (err)return err;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 124/1756 netfilter: flowtable: ensure sufficient headroom in xmit path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pablo Neira Ayuso <[email protected]>
commit ef4f741e8627512cb8c82f59a1fc7aacd854aadf upstream.
Check for headroom and call skb_expand_head() like in the IP output path to ensure there is sufficient headroom for the mac header when forwarding this packet as suggested by sashiko.
[ aq: the upstream commit does not apply to 6.12: 6.12 predates
b5964aac51e0, and FLOW_OFFLOAD_XMIT_NEIGH flows are still sent through neigh_xmit() from nf_flow_offload_ip_hook() and nf_flow_offload_ipv6_hook(). Do the same headroom check there, before skb->dev is switched to the output device, and in nf_flow_queue_xmit().
Without it, a forwarded skb reaches the output device's header_ops->create() with only the headroom it was received with. A UDP socket behind a veth (e.g. a container) leaves 16 bytes; virtio_net leaves 26 for frames larger than GOOD_COPY_LEN. GRE, ip6gre and VLAN have since been hardened individually, 6LoWPAN has not:
lowpan_header_create() stores struct lowpan_addr_info (32 bytes) in front of skb->data after a mere WARN_ON_ONCE(), i.e. an out-of-bounds write before the skb head. Seen on v6.12.117 with IPv6 forwarded by a flowtable from a veth to a 6LoWPAN interface:
WARNING: CPU: 1 PID: 4719 at net/ieee802154/6lowpan/tx.c:21 lowpan_header_create+0x165/0x1b0 [ieee802154_6lowpan]
Call Trace:
neigh_connected_output+0xa3/0xf0
neigh_xmit+0xbb/0x210
nf_flow_offload_ipv6_hook+0x540/0x7c0
nf_hook_slow+0x39/0xe0
__netif_receive_skb_core.constprop.0+0xe4c/0x1010
__netif_receive_skb_one_core+0x37/0xa0
process_backlog+0x77/0x140 Before e67c577d8989 ("ipv4: ip_gre: make ipgre_header() robust") the same path panicked with multipoint GRE (DMVPN) output devices:
skb_under_panic in ipgre_header() via nf_flow_offload_ip_hook(). ]
--- net/netfilter/nf_flow_table_ip.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
net/netfilter/nf_flow_table_ip.c +26 -0
@@ -330,6 +330,22 @@ static void nf_flow_encap_pop(struct sk_buff *skb, } } +/* Make room for the link layer header of @dev, like ip_finish_output2() does. +* The flowtable fast path skips the IP output path, and a device with +* header_ops (e.g. an NBMA GRE tunnel) may need more headroom than the skb +* was received with. On failure the skb has been freed. +*/ +static struct sk_buff *nf_flow_xmit_headroom (struct sk_buff *skb, +struct net_device *dev) +{ +unsigned int hh_len =LL_RESERVED_SPACE (dev); + +if (unlikely (skb_headroom (skb) < hh_len && dev->header_ops)) + skb =skb_expand_head (skb, hh_len); + +return skb; +} +static unsigned int nf_flow_queue_xmit (struct net *net,struct sk_buff *skb,const struct flow_offload_tuple_rhash *tuplehash,unsigned short type)
@@ -340,6 +356,10 @@ static unsigned int nf_flow_queue_xmit(struct net *net, struct sk_buff *skb,if (!outdev)return NF_DROP ; + skb =nf_flow_xmit_headroom (skb, outdev); +if (!skb) +return NF_STOLEN ; + skb->dev = outdev;dev_hard_header (skb, skb->dev, type, tuplehash->tuple.out.h_dest, tuplehash->tuple.out.h_source, skb->len);
@@ -452,6 +472,9 @@ nf_flow_offload_ip_hook(void *priv, struct sk_buff *skb,case FLOW_OFFLOAD_XMIT_NEIGH : rt =dst_rtable (tuplehash->tuple.dst_cache); outdev = rt->dst.dev; + skb =nf_flow_xmit_headroom (skb, outdev); +if (!skb) +return NF_STOLEN ; skb->dev = outdev; nexthop =rt_nexthop (rt, flow->tuplehash[!dir].tuple.src_v4.s_addr);skb_dst_drop (skb);
@@ -748,6 +771,9 @@ nf_flow_offload_ipv6_hook(void *priv, struct sk_buff *skb,case FLOW_OFFLOAD_XMIT_NEIGH : rt =dst_rt6_info (tuplehash->tuple.dst_cache); outdev = rt->dst.dev; + skb =nf_flow_xmit_headroom (skb, outdev); +if (!skb) +return NF_STOLEN ; skb->dev = outdev; nexthop =rt6_nexthop (rt, &flow->tuplehash[!dir].tuple.src_v6);skb_dst_drop (skb);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 125/1756 comedi: addi_apci_3xxx: fix subdevice count underallocation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yang Zi <[email protected]>
[ Upstream commit 3de5aa458dede472a253266d02902bd95af8e849 ]
In apci3xxx_auto_attach(), the number of subdevices is computed with
n_subdevices = (board->ai_n_chan ? 0 : 1) + board->has_ao + ...
The ternary is inverted: when the board has analog input channels (ai_n_chan != 0), it counts 0 instead of 1, so the AI subdevice that is actually created is not accounted for. As a result comedi_alloc_subdevices() allocates one entry too few, and the later subdevice initialization (notably the TTL Digital I/O subdevice, which is populated last) writes past the end of the allocated array, causing a slab out-of-bounds write.
Flip the ternary to count 1 when ai_n_chan is non-zero and 0 otherwise, matching the subdevice creation order in the function.
--- drivers/comedi/drivers/addi_apci_3xxx.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/addi_apci_3xxx.c +1 -1
@@ -787,7 +787,7 @@ static int apci3xxx_auto_attach(struct comedi_device *dev, dev->irq = pcidev->irq; } - n_subdevices = (board->ai_n_chan ?0 :1 ) + board->has_ao + + n_subdevices = (board->ai_n_chan ?1 :0 ) + board->has_ao + board->has_dig_in + board->has_dig_out + board->has_ttl_io; ret =comedi_alloc_subdevices (dev, n_subdevices);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 126/1756 comedi: dt2811: fix shift-out-of-bounds in IRQ check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
[ Upstream commit 471ce96a9c415b8a67bd5081ac2089a458cacc2f ]
The IRQ number passed via comedi_devconfig->options[1] is a signed int that comes from userspace. The check it->options[1] <= 7 does not reject negative values, so a negative IRQ number reaches BIT(it->options[1]), which is undefined behavior and triggers a UBSAN shift-out-of-bounds warning:
UBSAN: shift-out-of-bounds in drivers/comedi/drivers/dt2811.c:570:31 shift exponent -251 is negative
Add an explicit lower bound check (it->options[1] >= 0) so that only valid IRQ numbers 0..7 are accepted before the shift.
--- drivers/comedi/drivers/dt2811.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/comedi/drivers/dt2811.c +1 -1
@@ -566,7 +566,7 @@ static int dt2811_attach(struct comedi_device *dev, struct comedi_devconfig *it)dt2811_reset (dev);/* IRQ's 2,3,5,7 are valid for async command support */ -if (it->options[1 ] <=7 && (BIT (it->options[1 ]) &0xac )) { +if (it->options[1 ] >=0 && it->options[1 ] <=7 && (BIT (it->options[1 ]) &0xac )) { ret =request_irq (it->options[1 ], dt2811_interrupt,0 , dev->board_name, dev);if (ret ==0 )
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 127/1756 r8169: align RTL8125/RTL8126 PHY config with vendor driver
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Heiner Kallweit <[email protected]>
[ Upstream commit 4af2f60bf7378bd5c92b15a528d8c6c7d02bed6c ]
This aligns some parameters with vendor driver r8125/r8126 to avoid compatibility issues. Note that for RTL8125B there's no functional change, just the open-coded version of the function is replaced.
--- drivers/net/ethernet/realtek/r8169_phy_config.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/net/ethernet/realtek/r8169_phy_config.c +5 -1
@@ -1068,8 +1068,8 @@ static void rtl8125b_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) {r8169_apply_firmware (tp); +rtl8168g_enable_gphy_10m (phydev); -phy_modify_paged (phydev,0xa44 ,0x11 ,0x0000 ,0x0800 );phy_modify_paged (phydev,0xac4 ,0x13 ,0x00f0 ,0x0090 );phy_modify_paged (phydev,0xad3 ,0x10 ,0x0003 ,0x0001 );
@@ -1108,6 +1108,7 @@ static void rtl8125d_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) {r8169_apply_firmware (tp); +rtl8168g_enable_gphy_10m (phydev);rtl8125_legacy_force_mode (phydev);rtl8168g_disable_aldps (phydev);rtl8125b_config_eee_phy (phydev);
@@ -1117,6 +1118,9 @@ static void rtl8126a_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev) {r8169_apply_firmware (tp); +rtl8168g_enable_gphy_10m (phydev); +rtl8125_legacy_force_mode (phydev); +rtl8168g_disable_aldps (phydev); } void r8169_hw_phy_config(struct rtl8169_private *tp, struct phy_device *phydev,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 128/1756 xfs: add a flag to convert unwritten extents without allocating blocks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daejun Park <[email protected]>
[ Upstream commit f3ca3498dfe624f9b604c934263538a3acd55af5 ]
xfs_bmapi_write() with XFS_BMAPI_CONVERT also allocates blocks for holes and delalloc extents in the range. Add XFS_BMAPI_CONVERT_ONLY for callers that may only convert already allocated blocks. It stops at a hole or delalloc extent, and returns -ENOSR if it stops before mapping anything.
Marked for stable because "xfs: refuse a pNFS LAYOUTCOMMIT of a range without blocks" needs it.
--- fs/xfs/libxfs/xfs_bmap.c | 14 ++++++++++++-- fs/xfs/libxfs/xfs_bmap.h | 10 +++++++++- 2 files changed, 21 insertions(+), 3 deletions(-)
fs/xfs/libxfs/xfs_bmap.c +12 -2
@@ -4380,6 +4380,8 @@ xfs_bmapi_finish(* Returns a negative error code on failure, including -ENOSPC when it could not * allocate any blocks and -ENOSR when it did allocate blocks to convert a * delalloc range, but those blocks were before the passed in range. +* With XFS_BMAPI_CONVERT_ONLY, it stops at a hole or a delalloc extent instead +* of allocating blocks, and returns -ENOSR if it stops before mapping anything. */ int xfs_bmapi_write(
@@ -4439,6 +4441,8 @@ xfs_bmapi_write(*/ ASSERT ((flags & (XFS_BMAPI_PREALLOC |XFS_BMAPI_ZERO )) != (XFS_BMAPI_PREALLOC |XFS_BMAPI_ZERO )); +ASSERT (!(flags &XFS_BMAPI_CONVERT_ONLY ) || + (flags &XFS_BMAPI_CONVERT ));if (XFS_IS_CORRUPT (mp, !xfs_ifork_has_extents (ifp)) ||XFS_TEST_ERROR (mp,XFS_ERRTAG_BMAPIFORMAT )) {
@@ -4487,6 +4491,9 @@ xfs_bmapi_write(* that we found, if any. */ if (need_alloc || wasdelay) { +if (flags &XFS_BMAPI_CONVERT_ONLY ) +break ; + bma.eof = eof; bma.conv = !!(flags &XFS_BMAPI_CONVERT ); bma.wasdel = wasdelay;
@@ -4581,10 +4588,13 @@ xfs_bmapi_write(* * To avoid a successful return with *nmap set to 0, return the magic * -ENOSR error code for this particular case so that the caller can -* handle it. +* handle it. The same goes for XFS_BMAPI_CONVERT_ONLY stopping at a +* hole or a delalloc extent at the start of the range, in which case +* nothing has been changed. */ if (!n) { -ASSERT (bma.nallocs >= *nmap); +ASSERT ((flags &XFS_BMAPI_CONVERT_ONLY ) ? bma.nallocs ==0 : + bma.nallocs >= *nmap);return -ENOSR ; } *nmap = n;
fs/xfs/libxfs/xfs_bmap.h +9 -1
@@ -87,6 +87,13 @@ struct xfs_bmalloca {/* Do not update the rmap btree. Used for reconstructing bmbt from rmapbt. */ #define XFS_BMAPI_NORMAP (1u << 10) +/* +* Use with XFS_BMAPI_CONVERT to convert unwritten extents without allocating +* blocks. Stop at a hole or a delalloc extent: return the mappings found so +* far, or -ENOSR if there are none. +*/ +#define XFS_BMAPI_CONVERT_ONLY (1u << 12) +#define XFS_BMAPI_FLAGS \ { XFS_BMAPI_ENTIRE, "ENTIRE" }, \ { XFS_BMAPI_METADATA, "METADATA" }, \
@@ -98,7 +105,8 @@ struct xfs_bmalloca { { XFS_BMAPI_REMAP, "REMAP" }, \ { XFS_BMAPI_COWFORK, "COWFORK" }, \ { XFS_BMAPI_NODISCARD, "NODISCARD" }, \ - { XFS_BMAPI_NORMAP, "NORMAP" } + { XFS_BMAPI_NORMAP, "NORMAP" }, \ + { XFS_BMAPI_CONVERT_ONLY, "CONVERT_ONLY" } static inline int xfs_bmapi_aflag(int w)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 129/1756 x86/microcode/AMD: Move the no-revision fixup to get_patch_level()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Borislav Petkov (AMD) <[email protected]>
[ Upstream commit 098bcea71b8d257d80b0037b97b66070806600a5 ]
On machines which don't have microcode applied yet, the revision is 0. However, this doesn't work with the Zen family/model/stepping patch arithmetic. So move the fixup to the patch level getter function and this way make sure the patch level is always proper and thus the arithmetic always works.
And now that it can be called on any family, make this Zen-only.
--- arch/x86/kernel/cpu/microcode/amd.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-)
arch/x86/kernel/cpu/microcode/amd.c +7 -5
@@ -221,11 +221,6 @@ static bool need_sha_check(u32 cur_rev) {u32 cutoff; -if (!cur_rev) { - cur_rev =cpuid_to_ucode_rev (bsp_cpuid_1_eax); -pr_info_once ("No current revision, generating the lowest one: 0x%x\n" , cur_rev); - } - cutoff =get_cutoff_revision (cur_rev);if (cutoff)return cur_rev <= cutoff;
@@ -297,6 +292,13 @@ static u32 get_patch_level(void)u32 rev, dummy__always_unused ;native_rdmsr (MSR_AMD64_PATCH_LEVEL , rev, dummy); +if (!rev) { +if (x86_family (bsp_cpuid_1_eax) <0x17 ) +return rev; + + rev =cpuid_to_ucode_rev (bsp_cpuid_1_eax); +pr_info_once ("No current revision, generating the lowest one: 0x%x\n" , rev); + }return rev; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 130/1756 fs/stat.c: avoid harmless garbage value problem in vfs_statx_path()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Su Hui <[email protected]>
commit 0fac3ed473dd2955053be6671cdd747807f5e488 upstream.
Clang static checker(scan-build) warning:fs/stat.c:287:21: warning: The left expression of the compound assignment is an uninitialized value. The computed value will also be garbage.
287 | stat->result_mask |= STATX_MNT_ID_UNIQUE;
| ~~~~~~~~~~~~~~~~~ ^fs/stat.c:290:21: warning: The left expression of the compound assignment is an uninitialized value. The computed value will also be garbage.
290 | stat->result_mask |= STATX_MNT_ID;
When vfs_getattr() failed because of security_inode_getattr(), 'stat' is uninitialized. In this case, there is a harmless garbage problem in vfs_statx_path(). It's better to return error directly when vfs_getattr() failed, avoiding garbage value and more clearly.
--- fs/stat.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
fs/stat.c +3 -1
@@ -253,6 +253,8 @@ static int vfs_statx_path(struct path *p u32 request_mask) {int error =vfs_getattr (path, stat, request_mask, flags); +if (error) +return error;if (request_mask &STATX_MNT_ID_UNIQUE ) { stat->mnt_id =real_mount (path->mnt)->mnt_id_unique;
@@ -274,7 +276,7 @@ static int vfs_statx_path(struct path *pif (S_ISBLK (stat->mode))bdev_statx (path, stat, request_mask); -return error; +return 0 ; } static int vfs_statx_fd(int fd, int flags, struct kstat *stat,
Greg Kroah-Hartman
maintainerPATCH 131/1756 drm/komeda: Fix bits parsing of GLB_CORE_ID
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Raveendra Talabattula <[email protected]>
[ Upstream commit ec902de0221747094f9ccbb61454e9633fbf282f ]
GLB_CORE_ID contains the product and version information returned by the hardware. The current macros parses VERSION_MINOR as a 4-bit field and VERSION_STATUS as an 8-bit field, which does not match the register layout. As a result, the driver reports an incorrect version number.
Fix the parsing macros to match the hardware specification:
- VERSION_MINOR is 8 bits at [11:4]
- VERSION_STATUS is 4 bits at [3:0]
--- drivers/gpu/drm/arm/display/include/malidp_product.h | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/gpu/drm/arm/display/include/malidp_product.h +7 -3
@@ -8,14 +8,18 @@#define _MALIDP_PRODUCT_H_/* Product identification */ +/* GLB_CORE_ID fields as per HW specification: +* MINOR is 8 bits ([11:4]) and STATUS is 4 bits ([3:0]). +* Update masks/shifts accordingly. +*/ #define MALIDP_CORE_ID (__product, __major, __minor, __status) \ ((((__product) & 0xFFFF) << 16) | (((__major) & 0xF) << 12) | \ - (((__minor) & 0xF) << 8) | ((__status) & 0xFF)) + (((__minor) & 0xFF) << 4) | ((__status) & 0xF))#define MALIDP_CORE_ID_PRODUCT_ID (__core_id) ((__u32)(__core_id) >> 16)#define MALIDP_CORE_ID_MAJOR (__core_id) (((__u32)(__core_id) >> 12) & 0xF) -#define MALIDP_CORE_ID_MINOR (__core_id) (((__u32)(__core_id) >> 8) & 0xF) -#define MALIDP_CORE_ID_STATUS (__core_id) (((__u32)(__core_id)) & 0xFF) +#define MALIDP_CORE_ID_MINOR (__core_id) (((__u32)(__core_id) >> 4) & 0xFF) +#define MALIDP_CORE_ID_STATUS (__core_id) ((__u32)(__core_id) & 0xF)/* Mali-display product IDs */ #define MALIDP_D71_PRODUCT_ID 0x0071
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 132/1756 accel/qaic: reject BO sizes that overflow page count
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hao-Qun Huang <[email protected]>
[ Upstream commit 568d4cb5dcc5ec4e22975699b6ea67a30806884c ]
create_sgt() receives the BO size as a u64 but stores the number of pages in an int. qaic_create_bo_ioctl() page-aligns the user-supplied size without an upper bound, so DIV_ROUND_UP(size, PAGE_SIZE) can exceed INT_MAX and truncate when assigned to nr_pages.
When the page count wraps to a small positive value (for example a BO larger than 16 TiB on a 4 KiB page kernel), create_sgt() succeeds after allocating only a handful of pages while the GEM object still records the full size, so the request never fails with -ENOMEM. The temporary pages array and the allocation loop both use the truncated count, so the backing SG table ends up smaller than obj->size. Later slice operations validate against obj->size and then clone ranges from this short sgt.
Compute the page count as a u64 and reject sizes that do not fit in nr_pages before the narrowing conversion.
--- drivers/accel/qaic/qaic_data.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/accel/qaic/qaic_data.c +7 -1
@@ -15,6 +15,7 @@#include <linux/math64.h> #include <linux/mm.h> #include <linux/moduleparam.h> +#include <linux/overflow.h> #include <linux/scatterlist.h> #include <linux/spinlock.h> #include <linux/srcu.h>
@@ -454,7 +455,12 @@ static int create_sgt(struct qaic_device *qdev, struct sg_table **sgt_out, u64 sint order;if (size) { - nr_pages =DIV_ROUND_UP (size,PAGE_SIZE ); +u64 nr_pages_u64 =DIV_ROUND_UP_ULL (size,PAGE_SIZE ); + +if (overflows_type (nr_pages_u64, int)) +return -E2BIG ; + + nr_pages = nr_pages_u64;/* * calculate how much extra we are going to allocate, to remove * later
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 133/1756 drm/panfrost: Prevent division by 0
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adrián Larumbe <[email protected]>
[ Upstream commit fd4227f03546c323b5b21568f727233e9792d298 ]
When updating and debug-printing devfreq stats, in the very unlikely off-chance that total device time is less than 100 ns, division by 0 would happen. Fix the divisor when relevant and rearrange operands.
--- drivers/gpu/drm/panfrost/panfrost_devfreq.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/panfrost/panfrost_devfreq.c +1 -1
@@ -76,7 +76,7 @@ static int panfrost_devfreq_get_dev_status(struct device *dev,dev_dbg (pfdev->dev,"busy %lu total %lu %lu %% freq %lu MHz\n" , status->busy_time, status->total_time, - status->busy_time / (status->total_time /100 ), + status->busy_time *100 /MAX (status->total_time,1 ), status->current_frequency /1000 /1000 );return 0 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 134/1756 bpf: Mark dentry->d_inode as trusted_or_null
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Song Liu <[email protected]>
[ Upstream commit a766cfbbeb3a74397965a8fa2e9a402026d3e1d8 ]
LSM hooks such as security_path_mknod() and security_inode_rename() have access to newly allocated negative dentry, which has NULL d_inode. Therefore, it is necessary to do the NULL pointer check for d_inode.
Also add selftests that checks the verifier enforces the NULL pointer check.
Stable-dep-of: aed1bf1a352a ("bpf: sched_ext: Mark ops argument container pointer fields as trusted")
--- kernel/bpf/verifier.c | 5 ++--- .../selftests/bpf/progs/verifier_vfs_accept.c | 18 ++++++++++++++++++ .../selftests/bpf/progs/verifier_vfs_reject.c | 15 +++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-)
kernel/bpf/verifier.c +2 -3
@@ -6850,8 +6850,7 @@ BTF_TYPE_SAFE_TRUSTED(struct file) {struct inode *f_inode; }; -BTF_TYPE_SAFE_TRUSTED(struct dentry) { -/* no negative dentry-s in places where bpf can see it */ +BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {struct inode *d_inode; };
@@ -6889,7 +6888,6 @@ static bool type_is_trusted(struct bpf_verifier_env *env,BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task ));BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct linux_binprm ));BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct file )); -BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct dentry ));return btf_nested_type_is_trusted (&env->log, reg, field_name, btf_id,"__safe_trusted" ); }
@@ -6899,6 +6897,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env, const char *field_name, u32 btf_id) {BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED_OR_NULL (struct socket )); +BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry ));return btf_nested_type_is_trusted (&env->log, reg, field_name, btf_id,"__safe_trusted_or_null" );
tools/testing/selftests/bpf/progs/verifier_vfs_accept.c +18 -0
@@ -2,6 +2,7 @@/* Copyright (c) 2024 Google LLC. */ #include <vmlinux.h> +#include <errno.h> #include <bpf/bpf_helpers.h> #include <bpf/bpf_tracing.h>
@@ -82,4 +83,21 @@ int BPF_PROG(path_d_path_from_file_argument, struct file *file)return 0 ; } +SEC("lsm.s/inode_rename") +__success +int BPF_PROG (inode_rename ,struct inode *old_dir,struct dentry *old_dentry, +struct inode *new_dir,struct dentry *new_dentry, +unsigned int flags) +{ +struct inode *inode = new_dentry->d_inode; +ino_t ino; + +if (!inode) +return 0 ; + ino = inode->i_ino; +if (ino ==0 ) +return -EACCES ; +return 0 ; +} + char _license[] SEC("license") = "GPL";
tools/testing/selftests/bpf/progs/verifier_vfs_reject.c +15 -0
@@ -2,6 +2,7 @@/* Copyright (c) 2024 Google LLC. */ #include <vmlinux.h> +#include <errno.h> #include <bpf/bpf_helpers.h> #include <bpf/bpf_tracing.h> #include <linux/limits.h>
@@ -158,4 +159,18 @@ int BPF_PROG(path_d_path_kfunc_non_lsm, struct path *path, struct file *f)return 0 ; } +SEC("lsm.s/inode_rename") +__failure __msg("invalid mem access 'trusted_ptr_or_null_'") +int BPF_PROG(inode_rename, struct inode *old_dir, struct dentry *old_dentry, + struct inode *new_dir, struct dentry *new_dentry, + unsigned int flags) +{ +struct inode *inode = new_dentry->d_inode; +ino_t ino; + + ino = inode->i_ino; +if (ino ==0 ) +return -EACCES ; +return 0 ; +} char _license[] SEC("license") = "GPL";
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 135/1756 bpf: sched_ext: Mark ops argument container pointer fields as trusted
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tejun Heo <[email protected]>
[ Upstream commit aed1bf1a352acd4f5ffd2a81e23d2bb6e8e9b636 ]
Walking an unannotated pointer field of a trusted struct yields a bare PTR_TO_BTF_ID in non-sleepable programs, which kfuncs and helpers accept, but PTR_UNTRUSTED in sleepable programs, which they reject. This gets in the way of making ops.init_task() sleepable, which schedulers want for allocations. For example, passing args->cgroup into bpf_cgrp_storage_get() then fails verification and the only recourse is round-tripping through the cgroup ID with bpf_cgroup_from_id().
The pointer fields in the sched_ext ops argument containers are all pinned by the callers for the duration of the ops calls and are never NULL. Add them to the verifier's trusted-fields whitelist so that they are PTR_TRUSTED in both sleepable and non-sleepable programs.
--- kernel/bpf/verifier.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+)
kernel/bpf/verifier.c +26 -0
@@ -6850,6 +6850,28 @@ BTF_TYPE_SAFE_TRUSTED(struct file) {struct inode *f_inode; }; +/* +* The pointer fields in the sched_ext ops argument containers are pinned by the +* callers for the duration of the ops calls and are never NULL. +*/ +BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args) { +#ifdef CONFIG_EXT_GROUP_SCHED +struct cgroup *cgroup; +#endif +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args) { +struct task_struct *task; +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args) { +struct sched_ext_ops *ops; +}; + +BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args) { +struct sched_ext_ops *ops; +}; + BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) {struct inode *d_inode; };
@@ -6888,6 +6910,10 @@ static bool type_is_trusted(struct bpf_verifier_env *env,BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task ));BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct linux_binprm ));BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct file )); +BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct scx_init_task_args )); +BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct scx_cpu_release_args )); +BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct scx_sub_attach_args )); +BTF_TYPE_EMIT (BTF_TYPE_SAFE_TRUSTED(struct scx_sub_detach_args ));return btf_nested_type_is_trusted (&env->log, reg, field_name, btf_id,"__safe_trusted" ); }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 136/1756 drm/omap: dsi: avoid sending bta sync all the time in writes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andreas Kemnade <[email protected]>
[ Upstream commit 20207f78382ff339f3a7f7c5db2c0219b157d32a ]
Some chips need configuration commands to be sent first, before they can send data. TC358762 for example needs PPI_LPTXTIMECNT configured and PPI_STARTPPI set to 1 to be able to transmit anything. To be able to configure such chips, do not send bta sync during writes if no acks are requested. Instead just wait for the packet to be sent to avoid FIFO overflows. There might be more to do about acks, but there seem to be virtually no users of that flag.
This came to light when fiddling with the Epson Moverio BT-200 display which consists of 2 TC358762 bridges with SPI funneled through to the unknown display chip. With that patch the bridge can be accessed, Reading back registers works, when the above-mentioned registers are set.
In Command-Mode update, there was a nop sent, apparently the most relevant part was the bta sync to actually force low power mode.
Video mode panel at OMAP4 (BT-200) and video mode at OMAP5 was tested.
--- drivers/gpu/drm/omapdrm/dss/dsi.c | 63 +++++++++++++++---------------- 1 file changed, 31 insertions(+), 32 deletions(-)
drivers/gpu/drm/omapdrm/dss/dsi.c +31 -32
@@ -58,9 +58,6 @@ static void dsi_uninit_dispc(struct dsi_data *dsi);static int dsi_vc_send_null (struct dsi_data *dsi,int vc,int channel); -static ssize_t _omap_dsi_host_transfer (struct dsi_data *dsi,int vc, -const struct mipi_dsi_msg *msg); -#ifdef DSI_PERF_MEASURE static bool dsi_perf;module_param (dsi_perf, bool,0644 );
@@ -2189,28 +2186,45 @@ static int dsi_vc_send_null(struct dsi_data *dsi, int vc, int channel)static int dsi_vc_write_common (struct omap_dss_device *dssdev,int vc,const struct mipi_dsi_msg *msg) { +DECLARE_COMPLETION_ONSTACK (completion);struct dsi_data *dsi =to_dsi_data (dssdev); +u32 err;int r; +/* wait for IRQ for packet transmission confirmation */ + r =dsi_register_isr_vc (dsi, vc, dsi_completion_handler, + &completion,DSI_VC_IRQ_PACKET_SENT ); +if (r) +return r; +if (mipi_dsi_packet_format_is_short (msg->type)) r =dsi_vc_send_short (dsi, vc, msg);else r =dsi_vc_send_long (dsi, vc, msg); -if (r <0 ) +if ((!r) &&wait_for_completion_timeout (&completion, +msecs_to_jiffies (500 )) ==0 ) + r = -EIO ; + +dsi_unregister_isr_vc (dsi, vc, dsi_completion_handler, + &completion,DSI_VC_IRQ_PACKET_SENT ); +if (r)return r; -/* -* TODO: we do not always have to do the BTA sync, for example -* we can improve performance by setting the update window -* information without sending BTA sync between the commands. -* In that case we can return early. -*/ +/* TODO: find out if more needs to be done for MIPI_DSI_MSG_REQ_ACK */ - r =dsi_vc_send_bta_sync (dssdev, vc); -if (r) { -DSSERR ("bta sync failed\n" ); -return r; +if (msg->flags &MIPI_DSI_MSG_REQ_ACK ) { + r =dsi_vc_send_bta_sync (dssdev, vc); +if (r) { +DSSERR ("bta sync failed\n" ); +return r; + } + }else { + err =dsi_get_errors (dsi); +if (err) { +DSSERR ("Error while sending: %x\n" , err); +return -EIO ; + } }/* RX_FIFO_NOT_EMPTY */
@@ -3228,21 +3242,6 @@ static int _dsi_update(struct dsi_data *dsi)return 0 ; } -static int _dsi_send_nop (struct dsi_data *dsi,int vc,int channel) -{ -const u8 payload[] = {MIPI_DCS_NOP }; -const struct mipi_dsi_msg msg = { - .channel = channel, - .type =MIPI_DSI_DCS_SHORT_WRITE , - .tx_len =1 , - .tx_buf = payload, - }; - -WARN_ON (!dsi_bus_is_locked (dsi)); - -return _omap_dsi_host_transfer (dsi, vc, &msg); -} -static int dsi_update_channel (struct omap_dss_device *dssdev,int vc) {struct dsi_data *dsi =to_dsi_data (dssdev);
@@ -3263,13 +3262,13 @@ static int dsi_update_channel(struct omap_dss_device *dssdev, int vc)DSSDBG ("dsi_update_channel: %d" , vc);/* -* Send NOP between the frames. If we don't send something here, the +* Transition to LP here. If we don't send something here, the * updates stop working. This is probably related to DSI spec stating * that the DSI host should transition to LP at least once per frame. */ - r =_dsi_send_nop (dsi,VC_CMD , dsi->dsidev->channel); + r =dsi_vc_send_bta_sync (dssdev,VC_CMD );if (r <0 ) { -DSSWARN ("failed to send nop between frames: %d\n" , r); +DSSWARN ("failed to send bta sync between frames: %d\n" , r); goto err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 137/1756 drm: of: Fix drm_of_get_data_lanes_count_ep() return value documentation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marek Vasut <[email protected]>
[ Upstream commit e3eca845ef7d6cd8c407f9b42beb45af94ff096b ]
Update drm_of_get_data_lanes_count_ep() return value documentation to match the drm_of_get_data_lanes_count() return value documentation. The drm_of_get_data_lanes_count_ep() is only a wrapper around the drm_of_get_data_lanes_count() and therefore returns the same error codes.
Simplify the return code description of drm_of_get_data_lanes_count() and drm_of_get_data_lanes_count_ep() to -ENODATA and -EINVAL.
--- drivers/gpu/drm/drm_of.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/gpu/drm/drm_of.c +4 -4
@@ -444,8 +444,8 @@ EXPORT_SYMBOL_GPL(drm_of_lvds_get_data_mapping);* * Return: * * min..max - positive integer count of "data-lanes" elements -* * -ve - the "data-lanes" property is missing or invalid -* * -EINVAL - the "data-lanes" property is unsupported +* * -ENODATA - the property does not have a value. +* * -EINVAL - the "data-lanes" property is missing or invalid */ int drm_of_get_data_lanes_count (const struct device_node *endpoint,const unsigned int min,const unsigned int max)
@@ -476,8 +476,8 @@ EXPORT_SYMBOL_GPL(drm_of_get_data_lanes_count);* * Return: * * min..max - positive integer count of "data-lanes" elements -* * -EINVAL - the "data-mapping" property is unsupported -* * -ENODEV - the "data-mapping" property is missing +* * -ENODATA - the property does not have a value. +* * -EINVAL - the "data-lanes" property is missing or invalid */ int drm_of_get_data_lanes_count_ep(const struct device_node *port, int port_reg, int reg,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 138/1756 libbpf: Improve log message formatting
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tony Ambardar <[email protected]>
[ Upstream commit e8957c0dde3c945db2403beb3131a5ad84860b5f ]
Fix missing newlines and extraneous terminal spaces in messages.
Stable-dep-of: e40f61a31688 ("libbpf: Avoid overflow in BTF.ext bounds check")
--- tools/lib/bpf/btf.c | 6 +++--- tools/lib/bpf/btf_dump.c | 2 +- tools/lib/bpf/btf_relocate.c | 2 +- tools/lib/bpf/libbpf.c | 4 ++-- tools/lib/bpf/relo_core.c | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-)
tools/lib/bpf/btf.c +3 -3
@@ -2942,7 +2942,7 @@ static int btf_ext_setup_info(struct btf_ext *btf_ext,/* If no records, return failure now so .BTF.ext won't be used. */ if (!info_left) { -pr_debug ("%s section in .BTF.ext has no records" , ext_sec->desc); +pr_debug ("%s section in .BTF.ext has no records\n" , ext_sec->desc);return -EINVAL ; }
@@ -3030,7 +3030,7 @@ static int btf_ext_parse_hdr(__u8 *data, __u32 data_size) if (data_size < offsetofend(struct btf_ext_header, hdr_len) || data_size < hdr->hdr_len) { -pr_debug ("BTF.ext header not found" ); +pr_debug ("BTF.ext header not found\n" );return -EINVAL ; }
@@ -3292,7 +3292,7 @@ int btf__dedup(struct btf *btf, const struct btf_dedup_opts *opts) d =btf_dedup_new (btf, opts);if (IS_ERR (d)) { -pr_debug ("btf_dedup_new failed: %ld" ,PTR_ERR (d)); +pr_debug ("btf_dedup_new failed: %ld\n" ,PTR_ERR (d));return libbpf_err (-EINVAL ); }
tools/lib/bpf/btf_dump.c +1 -1
@@ -1307,7 +1307,7 @@ static void btf_dump_emit_type_decl(struct btf_dump *d, __u32 id,* chain, restore stack, emit warning, and try to * proceed nevertheless */ -pr_warn ("not enough memory for decl stack:%d" , err); +pr_warn ("not enough memory for decl stack: %d\n" , err); d->decl_stack_cnt = stack_start;return ; }
tools/lib/bpf/btf_relocate.c +1 -1
@@ -428,7 +428,7 @@ static int btf_relocate_rewrite_strs(struct btf_relocate *r, __u32 i) }else { off = r->str_map[*str_off];if (!off) { -pr_warn ("string '%s' [offset %u] is not mapped to base BTF" , +pr_warn ("string '%s' [offset %u] is not mapped to base BTF\n" ,btf__str_by_offset (r->btf, off), *str_off);return -ENOENT ; }
tools/lib/bpf/libbpf.c +2 -2
@@ -12819,7 +12819,7 @@ struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog, }if (prog->type !=BPF_PROG_TYPE_EXT ) { -pr_warn ("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace" , +pr_warn ("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n" , prog->name);return libbpf_err_ptr (-EINVAL ); }
@@ -13892,7 +13892,7 @@ int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s) map_type =btf__type_by_id (btf, map_type_id);if (!btf_is_datasec (map_type)) { -pr_warn ("type for map '%1$s' is not a datasec: %2$s" , +pr_warn ("type for map '%1$s' is not a datasec: %2$s\n" ,bpf_map__name (map),__btf_kind_str (btf_kind (map_type)));return libbpf_err (-EINVAL );
tools/lib/bpf/relo_core.c +1 -1
@@ -1345,7 +1345,7 @@ int bpf_core_calc_relo_insn(const char *prog_name, cands->cands[i].id, cand_spec);if (err <0 ) {bpf_core_format_spec (spec_buf,sizeof (spec_buf), cand_spec); -pr_warn ("prog '%s': relo #%d: error matching candidate #%d %s: %d\n " , +pr_warn ("prog '%s': relo #%d: error matching candidate #%d %s: %d\n" , prog_name, relo_idx, i, spec_buf, err);return err; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 139/1756 libbpf: Support BTF.ext loading and output in either endianness
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tony Ambardar <[email protected]>
[ Upstream commit cf579164e9ea9cd41c7c1da931683a319d224890 ]
Support for handling BTF data of either endianness was added in [1], but did not include BTF.ext data for lack of use cases. Later, support for static linking [2] provided a use case, but this feature and later ones were restricted to native-endian usage.
Add support for BTF.ext handling in either endianness. Convert BTF.ext data to native endianness when read into memory for further processing, and support raw data access that restores the original byte-order for output. Add internal header functions for byte-swapping func, line, and core info records.
Add new API functions btf_ext__endianness() and btf_ext__set_endianness() for query and setting byte-order, as already exist for BTF data.
[1] 3289959b97ca ("libbpf: Support BTF loading and raw data output in both endianness")
[2] 8fd27bf69b86 ("libbpf: Add BPF static linker BTF and BTF.ext support")
Stable-dep-of: e40f61a31688 ("libbpf: Avoid overflow in BTF.ext bounds check")
--- tools/lib/bpf/btf.c | 276 +++++++++++++++++++++++++------- tools/lib/bpf/btf.h | 3 + tools/lib/bpf/libbpf.map | 2 + tools/lib/bpf/libbpf_internal.h | 29 ++++ 4 files changed, 253 insertions(+), 57 deletions(-)
tools/lib/bpf/btf.c +219 -57
@@ -2886,7 +2886,7 @@ int btf__add_decl_tag(struct btf *btf, const char *value, int ref_type_id,return btf_commit_type (btf, sz); } -struct btf_ext_sec_setup_param { +struct btf_ext_sec_info_param {__u32 off;__u32 len;__u32 min_rec_size;
@@ -2894,14 +2894,20 @@ struct btf_ext_sec_setup_param {const char *desc; }; -static int btf_ext_setup_info (struct btf_ext *btf_ext, -struct btf_ext_sec_setup_param *ext_sec) +/* +* Parse a single info subsection of the BTF.ext info data: +* - validate subsection structure and elements +* - save info subsection start and sizing details in struct btf_ext +* - endian-independent operation, for calling before byte-swapping +*/ +static int btf_ext_parse_sec_info (struct btf_ext *btf_ext, +struct btf_ext_sec_info_param *ext_sec, +bool is_native) {const struct btf_ext_info_sec *sinfo;struct btf_ext_info *ext_info;__u32 info_left, record_size;size_t sec_cnt =0 ; -/* The start of the info sec (including the __u32 record_size). */ void *info;if (ext_sec->len ==0 )
@@ -2913,6 +2919,7 @@ static int btf_ext_setup_info(struct btf_ext *btf_ext,return -EINVAL ; } +/* The start of the info sec (including the __u32 record_size). */ info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; info_left = ext_sec->len;
@@ -2928,9 +2935,13 @@ static int btf_ext_setup_info(struct btf_ext *btf_ext,return -EINVAL ; } -/* The record size needs to meet the minimum standard */ - record_size = *(__u32 *)info; +/* The record size needs to meet either the minimum standard or, when +* handling non-native endianness data, the exact standard so as +* to allow safe byte-swapping. +*/ + record_size = is_native ? *(__u32 *)info :bswap_32 (*(__u32 *)info);if (record_size < ext_sec->min_rec_size || + (!is_native && record_size != ext_sec->min_rec_size) || record_size &0x03 ) {pr_debug ("%s section in .BTF.ext has invalid record size %u\n" , ext_sec->desc, record_size);
@@ -2957,7 +2968,7 @@ static int btf_ext_setup_info(struct btf_ext *btf_ext,return -EINVAL ; } - num_records = sinfo->num_info; + num_records = is_native ? sinfo->num_info :bswap_32 (sinfo->num_info);if (num_records ==0 ) {pr_debug ("%s section has incorrect num_records in .BTF.ext\n" , ext_sec->desc);
@@ -2985,64 +2996,157 @@ static int btf_ext_setup_info(struct btf_ext *btf_ext,return 0 ; } -static int btf_ext_setup_func_info (struct btf_ext *btf_ext) +/* Parse all info secs in the BTF.ext info data */ +static int btf_ext_parse_info (struct btf_ext *btf_ext,bool is_native) { -struct btf_ext_sec_setup_param param = { +struct btf_ext_sec_info_param func_info = { .off = btf_ext->hdr->func_info_off, .len = btf_ext->hdr->func_info_len, .min_rec_size =sizeof (struct bpf_func_info_min ), .ext_info = &btf_ext->func_info, .desc ="func_info" }; - -return btf_ext_setup_info (btf_ext, ¶m); -} - -static int btf_ext_setup_line_info (struct btf_ext *btf_ext) -{ -struct btf_ext_sec_setup_param param = { +struct btf_ext_sec_info_param line_info = { .off = btf_ext->hdr->line_info_off, .len = btf_ext->hdr->line_info_len, .min_rec_size =sizeof (struct bpf_line_info_min ), .ext_info = &btf_ext->line_info, .desc ="line_info" , }; - -return btf_ext_setup_info (btf_ext, ¶m); -} - -static int btf_ext_setup_core_relos (struct btf_ext *btf_ext) -{ -struct btf_ext_sec_setup_param param = { +struct btf_ext_sec_info_param core_relo = { .off = btf_ext->hdr->core_relo_off, .len = btf_ext->hdr->core_relo_len, .min_rec_size =sizeof (struct bpf_core_relo ), .ext_info = &btf_ext->core_relo_info, .desc ="core_relo" , }; +int err; + + err =btf_ext_parse_sec_info (btf_ext, &func_info, is_native); +if (err) +return err; + + err =btf_ext_parse_sec_info (btf_ext, &line_info, is_native); +if (err) +return err; + + if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) +return 0 ;/* skip core relos parsing */ -return btf_ext_setup_info (btf_ext, ¶m); + err =btf_ext_parse_sec_info (btf_ext, &core_relo, is_native); +if (err) +return err; + +return 0 ; } -static int btf_ext_parse_hdr (__u8 *data,__u32 data_size) +/* Swap byte-order of BTF.ext header with any endianness */ +static void btf_ext_bswap_hdr (struct btf_ext_header *h) { -const struct btf_ext_header *hdr = (struct btf_ext_header *)data; +bool is_native = h->magic ==BTF_MAGIC ; +__u32 hdr_len; - if (data_size < offsetofend(struct btf_ext_header, hdr_len) || - data_size < hdr->hdr_len) { -pr_debug ("BTF.ext header not found\n" ); + hdr_len = is_native ? h->hdr_len :bswap_32 (h->hdr_len); + + h->magic =bswap_16 (h->magic); + h->hdr_len =bswap_32 (h->hdr_len); + h->func_info_off =bswap_32 (h->func_info_off); + h->func_info_len =bswap_32 (h->func_info_len); + h->line_info_off =bswap_32 (h->line_info_off); + h->line_info_len =bswap_32 (h->line_info_len); + + if (hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) +return ; + + h->core_relo_off =bswap_32 (h->core_relo_off); + h->core_relo_len =bswap_32 (h->core_relo_len); +} + +/* Swap byte-order of generic info subsection */ +static void btf_ext_bswap_info_sec (void *info,__u32 len,bool is_native, +info_rec_bswap_fn bswap_fn) +{ +struct btf_ext_info_sec *sec; +__u32 info_left, rec_size, *rs; + +if (len ==0 ) +return ; + + rs = info;/* info record size */ + rec_size = is_native ? *rs :bswap_32 (*rs); + *rs =bswap_32 (*rs); + + sec = info +sizeof (__u32);/* info sec #1 */ + info_left = len -sizeof (__u32); +while (info_left) { +unsigned int sec_hdrlen =sizeof (struct btf_ext_info_sec ); +__u32 i, num_recs; +void *p; + + num_recs = is_native ? sec->num_info :bswap_32 (sec->num_info); + sec->sec_name_off =bswap_32 (sec->sec_name_off); + sec->num_info =bswap_32 (sec->num_info); + p = sec->data;/* info rec #1 */ +for (i =0 ; i < num_recs; i++, p += rec_size) +bswap_fn (p); + sec = p; + info_left -= sec_hdrlen + (__u64 )rec_size * num_recs; + } +} + +/* +* Swap byte-order of all info data in a BTF.ext section +* - requires BTF.ext hdr in native endianness +*/ +static void btf_ext_bswap_info (struct btf_ext *btf_ext,void *data) +{ +const bool is_native = btf_ext->swapped_endian; +const struct btf_ext_header *h = data; +void *info; + +/* Swap func_info subsection byte-order */ + info = data + h->hdr_len + h->func_info_off; +btf_ext_bswap_info_sec (info, h->func_info_len, is_native, + (info_rec_bswap_fn )bpf_func_info_bswap); + +/* Swap line_info subsection byte-order */ + info = data + h->hdr_len + h->line_info_off; +btf_ext_bswap_info_sec (info, h->line_info_len, is_native, + (info_rec_bswap_fn )bpf_line_info_bswap); + +/* Swap core_relo subsection byte-order (if present) */ + if (h->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) +return ; + + info = data + h->hdr_len + h->core_relo_off; +btf_ext_bswap_info_sec (info, h->core_relo_len, is_native, + (info_rec_bswap_fn )bpf_core_relo_bswap); +} + +/* Parse hdr data and info sections: check and convert to native endianness */ +static int btf_ext_parse (struct btf_ext *btf_ext) +{ +__u32 hdr_len, data_size = btf_ext->data_size; +struct btf_ext_header *hdr = btf_ext->hdr; +bool swapped_endian = false; +int err; + + if (data_size < offsetofend(struct btf_ext_header, hdr_len)) { +pr_debug ("BTF.ext header too short\n" );return -EINVAL ; } + hdr_len = hdr->hdr_len;if (hdr->magic ==bswap_16 (BTF_MAGIC )) { -pr_warn ("BTF.ext in non-native endianness is not supported\n" ); -return -ENOTSUP ; + swapped_endian = true; + hdr_len =bswap_32 (hdr_len); }else if (hdr->magic !=BTF_MAGIC ) {pr_debug ("Invalid BTF.ext magic:%x\n" , hdr->magic);return -EINVAL ; } -if (hdr->version !=BTF_VERSION ) { +/* Ensure known version of structs, current BTF_VERSION == 1 */ +if (hdr->version !=1 ) {pr_debug ("Unsupported BTF.ext version:%u\n" , hdr->version);return -ENOTSUP ; }
@@ -3052,11 +3156,39 @@ static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)return -ENOTSUP ; } -if (data_size == hdr->hdr_len) { +if (data_size < hdr_len) { +pr_debug ("BTF.ext header not found\n" ); +return -EINVAL ; + }else if (data_size == hdr_len) {pr_debug ("BTF.ext has no data\n" );return -EINVAL ; } +/* Verify mandatory hdr info details present */ + if (hdr_len < offsetofend(struct btf_ext_header, line_info_len)) { +pr_warn ("BTF.ext header missing func_info, line_info\n" ); +return -EINVAL ; + } + +/* Keep hdr native byte-order in memory for introspection */ +if (swapped_endian) +btf_ext_bswap_hdr (btf_ext->hdr); + +/* Validate info subsections and cache key metadata */ + err =btf_ext_parse_info (btf_ext, !swapped_endian); +if (err) +return err; + +/* Keep infos native byte-order in memory for introspection */ +if (swapped_endian) +btf_ext_bswap_info (btf_ext, btf_ext->data); + +/* +* Set btf_ext->swapped_endian only after all header and info data has +* been swapped, helping bswap functions determine if their data are +* in native byte-order when called. +*/ + btf_ext->swapped_endian = swapped_endian;return 0 ; }
@@ -3068,6 +3200,7 @@ void btf_ext__free(struct btf_ext *btf_ext)free (btf_ext->line_info.sec_idxs);free (btf_ext->core_relo_info.sec_idxs);free (btf_ext->data); +free (btf_ext->data_swapped);free (btf_ext); }
@@ -3088,29 +3221,7 @@ struct btf_ext *btf_ext__new(const __u8 *data, __u32 size) }memcpy (btf_ext->data, data, size); - err =btf_ext_parse_hdr (btf_ext->data, size); -if (err) - goto done; - - if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, line_info_len)) { - err = -EINVAL ; - goto done; - } - - err =btf_ext_setup_func_info (btf_ext); -if (err) - goto done; - - err =btf_ext_setup_line_info (btf_ext); -if (err) - goto done; - - if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) - goto done;/* skip core relos parsing */ - - err =btf_ext_setup_core_relos (btf_ext); -if (err) - goto done; + err =btf_ext_parse (btf_ext); done:if (err) {
@@ -3121,15 +3232,66 @@ struct btf_ext *btf_ext__new(const __u8 *data, __u32 size)return btf_ext; } +static void *btf_ext_raw_data (const struct btf_ext *btf_ext_ro,bool swap_endian) +{ +struct btf_ext *btf_ext = (struct btf_ext *)btf_ext_ro; +const __u32 data_sz = btf_ext->data_size; +void *data; + +/* Return native data (always present) or swapped data if present */ +if (!swap_endian) +return btf_ext->data; +else if (btf_ext->data_swapped) +return btf_ext->data_swapped; + +/* Recreate missing swapped data, then cache and return */ + data =calloc (1 , data_sz); +if (!data) +return NULL ; +memcpy (data, btf_ext->data, data_sz); + +btf_ext_bswap_info (btf_ext, data); +btf_ext_bswap_hdr (data); + btf_ext->data_swapped = data; +return data; +} +const void *btf_ext__raw_data (const struct btf_ext *btf_ext,__u32 *size) { +void *data; + + data =btf_ext_raw_data (btf_ext, btf_ext->swapped_endian); +if (!data) +return errno =ENOMEM ,NULL ; + *size = btf_ext->data_size; -return btf_ext->data; +return data; } __attribute__((alias ("btf_ext__raw_data" )))const void *btf_ext__get_raw_data (const struct btf_ext *btf_ext,__u32 *size); +enum btf_endianness btf_ext__endianness (const struct btf_ext *btf_ext) +{ +if (is_host_big_endian ()) +return btf_ext->swapped_endian ?BTF_LITTLE_ENDIAN :BTF_BIG_ENDIAN ; +else +return btf_ext->swapped_endian ?BTF_BIG_ENDIAN :BTF_LITTLE_ENDIAN ; +} + +int btf_ext__set_endianness (struct btf_ext *btf_ext,enum btf_endianness endian) +{ +if (endian !=BTF_LITTLE_ENDIAN && endian !=BTF_BIG_ENDIAN ) +return libbpf_err (-EINVAL ); + + btf_ext->swapped_endian =is_host_big_endian () != (endian ==BTF_BIG_ENDIAN ); + +if (!btf_ext->swapped_endian) { +free (btf_ext->data_swapped); + btf_ext->data_swapped =NULL ; + } +return 0 ; +}struct btf_dedup ;
tools/lib/bpf/btf.h +3 -0
@@ -167,6 +167,9 @@ LIBBPF_API const char *btf__str_by_offset(const struct btf *btf, __u32 offset); LIBBPF_API struct btf_ext *btf_ext__new(const __u8 *data, __u32 size); LIBBPF_API void btf_ext__free(struct btf_ext *btf_ext); LIBBPF_API const void *btf_ext__raw_data(const struct btf_ext *btf_ext, __u32 *size); +LIBBPF_API enum btf_endianness btf_ext__endianness(const struct btf_ext *btf_ext); +LIBBPF_API int btf_ext__set_endianness(struct btf_ext *btf_ext, +enum btf_endianness endian); LIBBPF_API int btf__find_str(struct btf *btf, const char *s); LIBBPF_API int btf__add_str(struct btf *btf, const char *s);
tools/lib/bpf/libbpf.map +2 -0
@@ -421,6 +421,8 @@ LIBBPF_1.5.0 { global: btf__distill_base; btf__relocate; + btf_ext__endianness; + btf_ext__set_endianness; bpf_map__autoattach; bpf_map__set_autoattach; bpf_object__token_fd;
tools/lib/bpf/libbpf_internal.h +29 -0
@@ -10,6 +10,7 @@#define __LIBBPF_LIBBPF_INTERNAL_H#include <stdlib.h> +#include <byteswap.h> #include <limits.h> #include <errno.h> #include <linux/err.h>
@@ -484,6 +485,8 @@ struct btf_ext {struct btf_ext_header *hdr;void *data; }; +void *data_swapped; +bool swapped_endian;struct btf_ext_info func_info;struct btf_ext_info line_info;struct btf_ext_info core_relo_info;
@@ -511,6 +514,32 @@ struct bpf_line_info_min {__u32 line_col; }; +/* Functions to byte-swap info records */ + +typedef void (*info_rec_bswap_fn )(void *); + +static inline void bpf_func_info_bswap (struct bpf_func_info *i) +{ + i->insn_off =bswap_32 (i->insn_off); + i->type_id =bswap_32 (i->type_id); +} + +static inline void bpf_line_info_bswap (struct bpf_line_info *i) +{ + i->insn_off =bswap_32 (i->insn_off); + i->file_name_off =bswap_32 (i->file_name_off); + i->line_off =bswap_32 (i->line_off); + i->line_col =bswap_32 (i->line_col); +} + +static inline void bpf_core_relo_bswap (struct bpf_core_relo *i) +{ + i->insn_off =bswap_32 (i->insn_off); + i->type_id =bswap_32 (i->type_id); + i->access_str_off =bswap_32 (i->access_str_off); + i->kind =bswap_32 (i->kind); +} +enum btf_field_iter_kind {BTF_FIELD_ITER_IDS ,BTF_FIELD_ITER_STRS ,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 140/1756 libbpf: Avoid overflow in BTF.ext bounds check
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Darren Carreras <[email protected]>
[ Upstream commit e40f61a31688898e7cf81e91074a42f805883e4d ]
A malformed BTF.ext subsection length in an ELF input can wrap the pointer addition used by btf_ext_parse_sec_info() on 32-bit builds. The wrapped pointer passes the bounds check and parsing then reads beyond the copied BTF.ext data.
Ensure the header fits in the copied data, then validate the subsection offset and length with subtraction before forming its pointer.
--- tools/lib/bpf/btf.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-)
tools/lib/bpf/btf.c +9 -5
@@ -2906,7 +2906,7 @@ static int btf_ext_parse_sec_info(struct btf_ext *btf_ext, {const struct btf_ext_info_sec *sinfo;struct btf_ext_info *ext_info; -__u32 info_left, record_size; +__u32 data_left, info_left, record_size;size_t sec_cnt =0 ;void *info;
@@ -2919,16 +2919,20 @@ static int btf_ext_parse_sec_info(struct btf_ext *btf_ext,return -EINVAL ; } -/* The start of the info sec (including the __u32 record_size). */ - info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; - info_left = ext_sec->len; +if (btf_ext->hdr->hdr_len > btf_ext->data_size) +return -EINVAL ; -if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) { + data_left = btf_ext->data_size - btf_ext->hdr->hdr_len; +if (ext_sec->off > data_left || ext_sec->len > data_left - ext_sec->off) {pr_debug ("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n" , ext_sec->desc, ext_sec->off, ext_sec->len);return -EINVAL ; } +/* The start of the info sec (including the __u32 record_size). */ + info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off; + info_left = ext_sec->len; +/* At least a record size */ if (info_left <sizeof (__u32)) {pr_debug (".BTF.ext %s record size not found\n" , ext_sec->desc);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 141/1756 selftests/bpf: Allocate a larger timeout for connection
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alexis Lothoré (eBPF Foundation) <[email protected]>
[ Upstream commit 669e4fa766000ae4137bb02eb22ce75ba78ad32d ]
Some tests, like tc_tunnel or tc_edt, sporadically fail in CI with the following logs:
(network_helpers.c:309: errno: Operation now in progress) \
Failed to connect to server
send_and_test_data:FAIL:connect to server unexpected error: -115
This is due to SO_RCVTIMEO and SO_SNDTIMEO being set on the client socket (see settimeo() in client_socket()), allowing connect() to return an error and to set errno to EINPROGRESS instead of ETIMEDOUT. Increasing the timeout value for those tests is likely not a good solution (and it has already been done by commit 2790db208b44 ("selftests/bpf: Improve tc_tunnel test reliability")): some tests expect some data transfer to fail, and so the timeout value would increase overall test execution duration again (not only the connection, but any socket operation).
Another solution is to allocate a timeout budget specific to the
connection: we can apply a larger timeout only for connections, and once the connection is established, set back the timeout configured through opts->timeout_ms; this would allow connection to succeed under heavy CI load, while keeping timeout reasonable for the rest of the test traffic.
Create a dedicated connect helper that sets a large timeout for the connect step, tries to connect, and if successful, finally sets the timeout value to the one configured by the test.
--- tools/testing/selftests/bpf/network_helpers.c | 46 ++++++++++++++----- 1 file changed, 35 insertions(+), 11 deletions(-)
tools/testing/selftests/bpf/network_helpers.c +35 -11
@@ -49,6 +49,8 @@ errno = __save; \ }) +#define CONNECT_MIN_TIMEOUT_MS 5000 +struct ipv4_packet pkt_v4 = { .eth.h_proto =__bpf_constant_htons (ETH_P_IP ), .iph.ihl =5 ,
@@ -291,6 +293,37 @@ int client_socket(int family, int type,return -1 ; } +static int connect_with_timeout (int fd,const struct sockaddr_storage *addr, +socklen_t addrlen,int timeout_ms) +{ +int connect_timeout_ms =MAX (timeout_ms,CONNECT_MIN_TIMEOUT_MS ); + +/* +* Override timeout configuration with a larger value for the +* connection +*/ +if (settimeo (fd, connect_timeout_ms)) { +log_err ("Failed to set connect timeout" ); +return -1 ; + } + +if (connect (fd, (const struct sockaddr *)addr, addrlen)) { +log_err ("Failed to connect" ); +return -1 ; + } + +/* +* If the timeout configured by the test is different from the +* connect timeout, restore it +*/ +if (timeout_ms != connect_timeout_ms &&settimeo (fd, timeout_ms)) { +log_err ("Failed to set timeout for connected socket" ); +return -1 ; + } + +return 0 ; +} +int connect_to_addr (int type,const struct sockaddr_storage *addr,socklen_t addrlen,const struct network_helper_opts *opts) {
@@ -305,8 +338,7 @@ int connect_to_addr(int type, const struct sockaddr_storage *addr, socklen_t addreturn -1 ; } -if (connect (fd, (const struct sockaddr *)addr, addrlen)) { -log_err ("Failed to connect to server" ); +if (connect_with_timeout (fd, addr, addrlen, opts->timeout_ms)) {save_errno_close (fd);return -1 ; }
@@ -376,20 +408,12 @@ int connect_fd_to_fd(int client_fd, int server_fd, int timeout_ms)struct sockaddr_storage addr;socklen_t len =sizeof (addr); -if (settimeo (client_fd, timeout_ms)) -return -1 ; -if (getsockname (server_fd, (struct sockaddr *)&addr, &len)) {log_err ("Failed to get server addr" );return -1 ; } -if (connect (client_fd, (const struct sockaddr *)&addr, len)) { -log_err ("Failed to connect to server" ); -return -1 ; - } - -return 0 ; +return connect_with_timeout (client_fd, &addr, len, timeout_ms); } int make_sockaddr(int family, const char *addr_str, __u16 port,
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 142/1756 drm/panthor: Take reqs_lock in soft_reset for clearing pending_reqs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nicolas Frattaroli <[email protected]>
[ Upstream commit 2d354adc5bbabe2e818be09bbe13f6bfde4a30c7 ]
panthor_gpu_soft_reset() sets pending_reqs to 0 without taking the requisite reqs_lock.
Fix this by taking the lock for the duration of the modification.
--- drivers/gpu/drm/panthor/panthor_gpu.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/gpu/drm/panthor/panthor_gpu.c +4 -1
@@ -459,7 +459,10 @@ int panthor_gpu_soft_reset(struct panthor_device *ptdev)return -ETIMEDOUT ; } - ptdev->gpu->pending_reqs =0 ; + scoped_guard(spinlock, &ptdev->gpu->reqs_lock) { + ptdev->gpu->pending_reqs =0 ; + } +return 0 ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 143/1756 gpio: pcf857x: use new GPIO line value setter callbacks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bartosz Golaszewski <[email protected]>
[ Upstream commit 4027438be823abdcfb50ee2abed06fa4e6af4b7c ]
struct gpio_chip now has callbacks for setting line values that return an integer, allowing to indicate failures. Convert the driver to using them.
Stable-dep-of: ed14364ae8c3 ("gpio: pcf857x: implement get_direction()")
--- drivers/gpio/gpio-pcf857x.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-)
drivers/gpio/gpio-pcf857x.c +10 -7
@@ -169,21 +169,24 @@ static int pcf857x_output(struct gpio_chip *chip, unsigned int offset, int valuereturn status; } -static void pcf857x_set (struct gpio_chip *chip,unsigned int offset,int value) +static int pcf857x_set (struct gpio_chip *chip,unsigned int offset,int value) { -pcf857x_output (chip, offset, value); +return pcf857x_output (chip, offset, value); } -static void pcf857x_set_multiple (struct gpio_chip *chip,unsigned long *mask, -unsigned long *bits) +static int pcf857x_set_multiple (struct gpio_chip *chip,unsigned long *mask, +unsigned long *bits) {struct pcf857x *gpio =gpiochip_get_data (chip); +int status;mutex_lock (&gpio->lock); gpio->out &= ~*mask; gpio->out |= *bits & *mask; - gpio->write (gpio->client, gpio->out); + status = gpio->write (gpio->client, gpio->out);mutex_unlock (&gpio->lock); + +return status; }/*-------------------------------------------------------------------------*/
@@ -291,8 +294,8 @@ static int pcf857x_probe(struct i2c_client *client) gpio->chip.owner =THIS_MODULE ; gpio->chip.get = pcf857x_get; gpio->chip.get_multiple = pcf857x_get_multiple; - gpio->chip.set = pcf857x_set; - gpio->chip.set_multiple = pcf857x_set_multiple; + gpio->chip.set_rv = pcf857x_set; + gpio->chip.set_multiple_rv = pcf857x_set_multiple; gpio->chip.direction_input = pcf857x_input; gpio->chip.direction_output = pcf857x_output; gpio->chip.ngpio = (uintptr_t )i2c_get_match_data (client);
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 144/1756 gpio: pcf857x: implement get_direction()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tapio Reijonen <[email protected]>
[ Upstream commit ed14364ae8c310cc3f3f649ffcbc7f82befe1579 ]
The GPIO core warns (and taints the kernel) when a gpiochip lacks .get_direction() and a consumer queries a line's direction, for example via /sys/kernel/debug/gpio. pcf857x provided direction_input/output but no get_direction.
These quasi-bidirectional expanders cannot report direction in hardware, and the 'out' software latch alone is ambiguous - a released (input) line and an output driven high both read back as a set bit. Track the direction explicitly in a 'dir' latch updated by the direction_input(), direction_output() and set_multiple() paths, and return it from get_direction(). Initialise it from the same reset state as 'out':
released lines are inputs, lines flagged in the power-on latch are driven-low outputs.
--- drivers/gpio/gpio-pcf857x.c | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-)
drivers/gpio/gpio-pcf857x.c +15 -1
@@ -68,8 +68,9 @@ MODULE_DEVICE_TABLE(of, pcf857x_of_table);struct pcf857x {struct gpio_chip chip;struct i2c_client *client; -struct mutex lock;/* protect 'out' */ +struct mutex lock;/* protect 'out' and 'dir' */ unsigned int out;/* software latch */ +unsigned int dir;/* direction latch (1 = input) */ unsigned int status;/* current status */ unsigned int irq_enabled;/* enabled irqs */
@@ -122,12 +123,21 @@ static int pcf857x_input(struct gpio_chip *chip, unsigned int offset)mutex_lock (&gpio->lock); gpio->out |= (1 << offset); + gpio->dir |= (1 << offset); status = gpio->write (gpio->client, gpio->out);mutex_unlock (&gpio->lock);return status; } +static int pcf857x_get_direction (struct gpio_chip *chip,unsigned int offset) +{ +struct pcf857x *gpio =gpiochip_get_data (chip); + +return (gpio->dir & (1 << offset)) ?GPIO_LINE_DIRECTION_IN + :GPIO_LINE_DIRECTION_OUT ; +} +static int pcf857x_get (struct gpio_chip *chip,unsigned int offset) {struct pcf857x *gpio =gpiochip_get_data (chip);
@@ -163,6 +173,7 @@ static int pcf857x_output(struct gpio_chip *chip, unsigned int offset, int value gpio->out |= bit; else gpio->out &= ~bit; + gpio->dir &= ~bit; status = gpio->write (gpio->client, gpio->out);mutex_unlock (&gpio->lock);
@@ -183,6 +194,7 @@ static int pcf857x_set_multiple(struct gpio_chip *chip, unsigned long *mask,mutex_lock (&gpio->lock); gpio->out &= ~*mask; gpio->out |= *bits & *mask; + gpio->dir &= ~*mask; status = gpio->write (gpio->client, gpio->out);mutex_unlock (&gpio->lock);
@@ -298,6 +310,7 @@ static int pcf857x_probe(struct i2c_client *client) gpio->chip.set_multiple_rv = pcf857x_set_multiple; gpio->chip.direction_input = pcf857x_input; gpio->chip.direction_output = pcf857x_output; + gpio->chip.get_direction = pcf857x_get_direction; gpio->chip.ngpio = (uintptr_t )i2c_get_match_data (client);/* NOTE: the OnSemi jlc1562b is also largely compatible with
@@ -369,6 +382,7 @@ static int pcf857x_probe(struct i2c_client *client)* reset state. Otherwise it flags pins to be driven low. */ gpio->out = ~n_latch; + gpio->dir = ~n_latch; gpio->status = gpio->read (gpio->client);/* Enable irqchip if we have an interrupt */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 145/1756 bpftool: Fix spurious batch file read error
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yuan Chen <[email protected]>
[ Upstream commit 713c02b59e21840f623a3e31c43d967026c75181 ]
do_batch() checks errno after the read loop to detect read failures, but fgets() does not clear errno on success, so a stale errno left by a previously executed command (e.g. map dump's EBADF from a double close) makes bpftool report a batch file read failure and exit with an error even though every command succeeded.
Clear errno before each fgets() call, so the post-loop check only sees the outcome of the last read: zero on success or EOF, E2BIG for an overlong line, and a genuine errno when fgets() fails.
Since errno is now reset before every read in batch mode, drop the USE_LIBCAP errno reset in main() that existed only to keep errno clean for the batch mode.
--- tools/bpf/bpftool/main.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-)
tools/bpf/bpftool/main.c +5 -11
@@ -354,7 +354,11 @@ static int do_batch(int argc, char **argv)if (json_output)jsonw_start_array (json_wtr); -while (fgets (buf,sizeof (buf), fp)) { +for (;;) { + errno =0 ; +if (!fgets (buf,sizeof (buf), fp)) +break ; + cp =strchr (buf,'#' );if (cp) *cp ='\0' ;
@@ -455,16 +459,6 @@ int main(int argc, char **argv)setlinebuf (stdout); -#ifdef USE_LIBCAP -/* Libcap < 2.63 hooks before main() to compute the number of -* capabilities of the running kernel, and doing so it calls prctl() -* which may fail and set errno to non-zero. -* Let's reset errno to make sure this does not interfere with the -* batch mode. -*/ - errno =0 ; -#endif - last_do_help = do_help; pretty_output = false; json_output = false;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 146/1756 regulator: fixed: reject incompatible platform devices
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chandradhar Kumar <[email protected]>
[ Upstream commit f7396c2dbbc1bed6c2c554d1ddf80d16e4780a7d ]
The fixed regulator driver expects non-DT platform devices to provide their configuration through platform_data as a struct fixed_voltage_config.
An explicitly bound driver can bypass the normal platform device/driver matching and attach the fixed regulator driver to an unrelated platform device. This causes the driver's platform_data to be interpreted as a struct fixed_voltage_config even though it contains data for a different device.
Reject non-DT platform devices whose name does not match the fixed regulator driver before accessing their platform data.
--- drivers/regulator/fixed.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/regulator/fixed.c +4 -0
@@ -29,6 +29,7 @@#include <linux/regulator/of_regulator.h> #include <linux/regulator/machine.h> #include <linux/clk.h> +#include <linux/string.h> /* Default time in millisecond to wait for emergency shutdown */ #define FV_DEF_EMERG_SHUTDWN_TMO 10
@@ -229,6 +230,9 @@ static int reg_fixed_voltage_probe(struct platform_device *pdev)enum gpiod_flags gflags;int ret; +if (!pdev->dev.of_node &&strcmp (pdev->name,"reg-fixed-voltage" )) +return -ENODEV ; + drvdata =devm_kzalloc (&pdev->dev,sizeof (struct fixed_voltage_data ),GFP_KERNEL );if (!drvdata)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 147/1756 spi: sh-msiof: SITMDR1/SIRMDR1 bitfield conversion
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Geert Uytterhoeven <[email protected]>
[ Upstream commit 6bae252a9452ca8496670230a7821c34450763a2 ]
Convert MSIOF Transmit and Receive Mode Register 1 field accesses to use the FIELD_PREP() bitfield access macro.
This gets rid of explicit shifts.
Stable-dep-of: 152867998da9 ("spi: sh-msiof: propagate setup runtime-PM errors")
--- drivers/spi/spi-sh-msiof.c | 45 ++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 21 deletions(-)
drivers/spi/spi-sh-msiof.c +24 -21
@@ -7,6 +7,7 @@* Copyright (C) 2014-2017 Glider bvba */ +#include <linux/bitfield.h> #include <linux/bitmap.h> #include <linux/clk.h> #include <linux/completion.h>
@@ -83,20 +84,19 @@ struct sh_msiof_spi_priv {/* SITMDR1 and SIRMDR1 */ #define SIMDR1_TRMD BIT(31)/* Transfer Mode (1 = Master mode) */ -#define SIMDR1_SYNCMD_MASK GENMASK(29, 28)/* SYNC Mode */ -#define SIMDR1_SYNCMD_SPI (2 << 28)/* Level mode/SPI */ -#define SIMDR1_SYNCMD_LR (3 << 28)/* L/R mode */ -#define SIMDR1_SYNCAC_SHIFT 25/* Sync Polarity (1 = Active-low) */ -#define SIMDR1_BITLSB_SHIFT 24/* MSB/LSB First (1 = LSB first) */ -#define SIMDR1_DTDL_SHIFT 20/* Data Pin Bit Delay for MSIOF_SYNC */ -#define SIMDR1_SYNCDL_SHIFT 16/* Frame Sync Signal Timing Delay */ -#define SIMDR1_FLD_MASK GENMASK(3, 2)/* Frame Sync Signal Interval (0-3) */ -#define SIMDR1_FLD_SHIFT 2 +#define SIMDR1_SYNCMD GENMASK(29, 28)/* SYNC Mode */ +#define SIMDR1_SYNCMD_SPI 2U/* Level mode/SPI */ +#define SIMDR1_SYNCMD_LR 3U/* L/R mode */ +#define SIMDR1_SYNCAC BIT(25)/* Sync Polarity (1 = Active-low) */ +#define SIMDR1_BITLSB BIT(24)/* MSB/LSB First (1 = LSB first) */ +#define SIMDR1_DTDL GENMASK(22, 20)/* Data Pin Bit Delay for MSIOF_SYNC */ +#define SIMDR1_SYNCDL GENMASK(18, 16)/* Frame Sync Signal Timing Delay */ +#define SIMDR1_FLD GENMASK(3, 2)/* Frame Sync Signal Interval (0-3) */ #define SIMDR1_XXSTP BIT(0)/* Transmission/Reception Stop on FIFO */ /* SITMDR1 */ #define SITMDR1_PCON BIT(30)/* Transfer Signal Connection */ -#define SITMDR1_SYNCCH_MASK GENMASK(27, 26)/* Sync Signal Channel Select */ -#define SITMDR1_SYNCCH_SHIFT 26/* 0=MSIOF_SYNC, 1=MSIOF_SS1, 2=MSIOF_SS2 */ +#define SITMDR1_SYNCCH GENMASK(27, 26)/* Sync Signal Channel Select */ +/* 0=MSIOF_SYNC, 1=MSIOF_SS1, 2=MSIOF_SS2 */ /* SITMDR2 and SIRMDR2 */ #define SIMDR2_BITLEN1 (i) (((i) - 1) << 24)/* Data Size (8-32 bits) */
@@ -340,8 +340,9 @@ static u32 sh_msiof_spi_get_dtdl_and_syncdl(struct sh_msiof_spi_priv *p)return 0 ; } - val =sh_msiof_get_delay_bit (p->info->dtdl) <<SIMDR1_DTDL_SHIFT ; - val |=sh_msiof_get_delay_bit (p->info->syncdl) <<SIMDR1_SYNCDL_SHIFT ; + val =FIELD_PREP (SIMDR1_DTDL ,sh_msiof_get_delay_bit (p->info->dtdl)) | +FIELD_PREP (SIMDR1_SYNCDL , +sh_msiof_get_delay_bit (p->info->syncdl));return val; }
@@ -360,16 +361,18 @@ static void sh_msiof_spi_set_pin_regs(struct sh_msiof_spi_priv *p, u32 ss,* 1 0 11 11 0 0 * 1 1 11 11 1 1 */ - tmp =SIMDR1_SYNCMD_SPI |1 <<SIMDR1_FLD_SHIFT |SIMDR1_XXSTP ; - tmp |= !cs_high <<SIMDR1_SYNCAC_SHIFT ; - tmp |= lsb_first <<SIMDR1_BITLSB_SHIFT ; + tmp =FIELD_PREP (SIMDR1_SYNCMD ,SIMDR1_SYNCMD_SPI ) | +FIELD_PREP (SIMDR1_FLD ,1 ) |SIMDR1_XXSTP | +FIELD_PREP (SIMDR1_SYNCAC , !cs_high) | +FIELD_PREP (SIMDR1_BITLSB , lsb_first); tmp |=sh_msiof_spi_get_dtdl_and_syncdl (p);if (spi_controller_is_target (p->ctlr)) {sh_msiof_write (p,SITMDR1 , tmp |SITMDR1_PCON ); }else {sh_msiof_write (p,SITMDR1 , tmp |SIMDR1_TRMD |SITMDR1_PCON | - (ss <MAX_SS ? ss :0 ) <<SITMDR1_SYNCCH_SHIFT ); +FIELD_PREP (SITMDR1_SYNCCH , + ss <MAX_SS ? ss :0 )); }if (p->ctlr->flags &SPI_CONTROLLER_MUST_TX ) {/* These bits are reserved if RX needs TX */
@@ -564,12 +567,12 @@ static int sh_msiof_spi_setup(struct spi_device *spi)return 0 ;/* Configure native chip select mode/polarity early */ - clr =SIMDR1_SYNCMD_MASK ; - set =SIMDR1_SYNCMD_SPI ; + clr =SIMDR1_SYNCMD ; + set =FIELD_PREP (SIMDR1_SYNCMD ,SIMDR1_SYNCMD_SPI );if (spi->mode &SPI_CS_HIGH ) - clr |=BIT (SIMDR1_SYNCAC_SHIFT ); + clr |=SIMDR1_SYNCAC ;else - set |=BIT (SIMDR1_SYNCAC_SHIFT ); + set |=SIMDR1_SYNCAC ;pm_runtime_get_sync (&p->pdev->dev); tmp =sh_msiof_read (p,SITMDR1 ) & ~clr;sh_msiof_write (p,SITMDR1 , tmp | set |SIMDR1_TRMD |SITMDR1_PCON );
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 148/1756 spi: sh-msiof: propagate setup runtime-PM errors
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pengpeng Hou <[email protected]>
[ Upstream commit 152867998da9f331d6235d76aae1c7e1650708a9 ]
sh_msiof_spi_setup() ignores pm_runtime_get_sync() before programming native chip-select registers and marking the configuration initialized.
Use the checked runtime-PM helper and return failure before register access.
--- drivers/spi/spi-sh-msiof.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/spi/spi-sh-msiof.c +4 -1
@@ -558,6 +558,7 @@ static int sh_msiof_spi_setup(struct spi_device *spi)struct sh_msiof_spi_priv *p =spi_controller_get_devdata (spi->controller);u32 clr, set, tmp; +int ret;if (spi_get_csgpiod (spi,0 ) ||spi_controller_is_target (p->ctlr))return 0 ;
@@ -573,7 +574,9 @@ static int sh_msiof_spi_setup(struct spi_device *spi) clr |=SIMDR1_SYNCAC ; else set |= SIMDR1_SYNCAC; -pm_runtime_get_sync (&p->pdev->dev); + ret =pm_runtime_resume_and_get (&p->pdev->dev); +if (ret <0 ) +return ret; tmp =sh_msiof_read (p,SITMDR1 ) & ~clr;sh_msiof_write (p,SITMDR1 , tmp | set |SIMDR1_TRMD |SITMDR1_PCON ); tmp =sh_msiof_read (p,SIRMDR1 ) & ~clr;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 149/1756 iio: humidity: hts221: report available values via read_avail()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Adi Nata <[email protected]>
[ Upstream commit 003e99cf33e344a380ba10b3e04ccb862f3d9dc3 ]
Replace the custom oversampling_ratio_available sysfs attributes with the standard IIO read_avail() callback. This lets the IIO core create and format *_available attributes and exposes the lists to in-kernel consumers.
As a consequence, the incorrectly named in_humidity_oversampling_ratio_available attribute is replaced by the standard in_humidityrelative_oversampling_ratio_available name for the IIO_HUMIDITYRELATIVE channel. The temperature oversampling and sampling frequency available attribute names are unchanged.
--- drivers/iio/humidity/hts221_core.c | 106 +++++++++++------------------ 1 file changed, 40 insertions(+), 66 deletions(-)
drivers/iio/humidity/hts221_core.c +40 -66
@@ -10,7 +10,6 @@#include <linux/kernel.h> #include <linux/module.h> #include <linux/device.h> -#include <linux/iio/sysfs.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/regmap.h>
@@ -49,7 +48,7 @@ struct hts221_odr {struct hts221_avg {u8 addr;u8 mask; -u16 avg_avl[HTS221_AVG_DEPTH ]; +int avg_avl[HTS221_AVG_DEPTH ]; };static const struct hts221_odr hts221_odr_table[] = {
@@ -58,6 +57,8 @@ static const struct hts221_odr hts221_odr_table[] = { { 13, 0x03 }, /* 12.5Hz */ }; +static const int hts221_odr_avail[] = { 1, 7, 13 }; + static const struct hts221_avg hts221_avg_list[] = { { .addr = 0x10,
@@ -97,7 +98,11 @@ static const struct iio_chan_spec hts221_channels[] = {BIT (IIO_CHAN_INFO_OFFSET ) |BIT (IIO_CHAN_INFO_SCALE ) | BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), + .info_mask_separate_available = + BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), + .info_mask_shared_by_all_available = + BIT(IIO_CHAN_INFO_SAMP_FREQ), .scan_index = 0, .scan_type = { .sign = 's',
@@ -113,7 +118,11 @@ static const struct iio_chan_spec hts221_channels[] = {BIT (IIO_CHAN_INFO_OFFSET ) |BIT (IIO_CHAN_INFO_SCALE ) | BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), + .info_mask_separate_available = + BIT(IIO_CHAN_INFO_OVERSAMPLING_RATIO), .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ), + .info_mask_shared_by_all_available = + BIT(IIO_CHAN_INFO_SAMP_FREQ), .scan_index = 1, .scan_type = { .sign = 's',
@@ -192,53 +201,35 @@ static int hts221_update_avg(struct hts221_hw *hw,return 0 ; } -static ssize_t hts221_sysfs_sampling_freq (struct device *dev, -struct device_attribute *attr, -char *buf) -{ -int i; -ssize_t len =0 ; - -for (i =0 ; i <ARRAY_SIZE (hts221_odr_table); i++) - len +=scnprintf (buf + len,PAGE_SIZE - len,"%d " , - hts221_odr_table[i].hz); - buf[len -1 ] ='\n' ; - -return len; -} - -static ssize_t -hts221_sysfs_rh_oversampling_avail (struct device *dev, -struct device_attribute *attr, -char *buf) -{ -const struct hts221_avg *avg = &hts221_avg_list[HTS221_SENSOR_H ]; -ssize_t len =0 ; -int i; - -for (i =0 ; i <ARRAY_SIZE (avg->avg_avl); i++) - len +=scnprintf (buf + len,PAGE_SIZE - len,"%d " , - avg->avg_avl[i]); - buf[len -1 ] ='\n' ; - -return len; -} - -static ssize_t -hts221_sysfs_temp_oversampling_avail (struct device *dev, -struct device_attribute *attr, -char *buf) +static int hts221_read_avail (struct iio_dev *indio_dev, +struct iio_chan_spec const *chan, +const int **vals,int *type,int *length, +long mask) { -const struct hts221_avg *avg = &hts221_avg_list[HTS221_SENSOR_T ]; -ssize_t len =0 ; -int i; - -for (i =0 ; i <ARRAY_SIZE (avg->avg_avl); i++) - len +=scnprintf (buf + len,PAGE_SIZE - len,"%d " , - avg->avg_avl[i]); - buf[len -1 ] ='\n' ; - -return len; +switch (mask) { +case IIO_CHAN_INFO_OVERSAMPLING_RATIO : +switch (chan->type) { +case IIO_HUMIDITYRELATIVE : + *vals = hts221_avg_list[HTS221_SENSOR_H ].avg_avl; + *length =ARRAY_SIZE (hts221_avg_list[HTS221_SENSOR_H ].avg_avl); +break ; +case IIO_TEMP : + *vals = hts221_avg_list[HTS221_SENSOR_T ].avg_avl; + *length =ARRAY_SIZE (hts221_avg_list[HTS221_SENSOR_T ].avg_avl); +break ; +default : +return -EINVAL ; + } + *type =IIO_VAL_INT ; +return IIO_AVAIL_LIST ; +case IIO_CHAN_INFO_SAMP_FREQ : + *vals = hts221_odr_avail; + *type =IIO_VAL_INT ; + *length =ARRAY_SIZE (hts221_odr_avail); +return IIO_AVAIL_LIST ; +default : +return -EINVAL ; + } }int hts221_set_enable (struct hts221_hw *hw,bool enable)
@@ -522,27 +513,10 @@ static int hts221_validate_trigger(struct iio_dev *iio_dev,return hw->trig == trig ?0 : -EINVAL ; } -static IIO_DEVICE_ATTR(in_humidity_oversampling_ratio_available, S_IRUGO, - hts221_sysfs_rh_oversampling_avail, NULL, 0); -static IIO_DEVICE_ATTR(in_temp_oversampling_ratio_available, S_IRUGO, - hts221_sysfs_temp_oversampling_avail, NULL, 0); -static IIO_DEV_ATTR_SAMP_FREQ_AVAIL (hts221_sysfs_sampling_freq); - -static struct attribute *hts221_attributes[] = { - &iio_dev_attr_sampling_frequency_available.dev_attr.attr, - &iio_dev_attr_in_humidity_oversampling_ratio_available.dev_attr.attr, - &iio_dev_attr_in_temp_oversampling_ratio_available.dev_attr.attr, -NULL , -}; - -static const struct attribute_group hts221_attribute_group = { - .attrs = hts221_attributes, -}; -static const struct iio_info hts221_info = { - .attrs = &hts221_attribute_group, .read_raw = hts221_read_raw, .write_raw = hts221_write_raw, + .read_avail = hts221_read_avail, .validate_trigger = hts221_validate_trigger, };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 150/1756 dt-bindings: iio: light: ltr501: Sort compatible enum array
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Esben Haabendal <[email protected]>
[ Upstream commit 6c430006fbcb63dc8baee3c3bf356b264ba7f61e ]
Restore alphabetical sorting of the properties.compatible.enum array.
Stable-dep-of: 198ed7962e42 ("dt-bindings: iio: light: ltr501: Add missing ltr303 compatible")
--- Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml +1 -1
@@ -15,9 +15,9 @@ allOf: properties: compatible: enum: + - liteon,ltr301 - liteon,ltr501 - liteon,ltr559 - - liteon,ltr301 reg: maxItems: 1
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 151/1756 dt-bindings: iio: light: ltr501: Add missing ltr303 compatible
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Esben Haabendal <[email protected]>
[ Upstream commit 198ed7962e42f1e45b7f48b9abc70aad9e3185f8 ]
When support for ltr303 was back in 2021, the bindings documentation was not updated accordingly.
--- Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml | 1 + 1 file changed, 1 insertion(+)
Documentation/devicetree/bindings/iio/light/liteon,ltr501.yaml +1 -0
@@ -16,6 +16,7 @@ properties: compatible: enum: - liteon,ltr301 + - liteon,ltr303 - liteon,ltr501 - liteon,ltr559
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 152/1756 iio: temperature: tmp117: fix calibbias cache update on I2C write failure
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Salah Triki <[email protected]>
[ Upstream commit 61fff9cebbfdf39bbd04d366882476d1def14047 ]
The calibbias cache (data->calibbias) was updated before the I2C write to TMP117_REG_TEMP_OFFSET was known to succeed. If the write failed, the function correctly returned an error, but the driver's internal cache had already been updated to the new value.
This causes the cache and the actual hardware register to go out of
sync: a subsequent write of the same value would be silently skipped by the early "if (off == data->calibbias) return 0;" check, since the cache matches even though the register was never successfully updated.
Update data->calibbias only after confirming the I2C write succeeded, so the cache always reflects the actual state of the device.
Found by code inspection.
--- drivers/iio/temperature/tmp117.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/iio/temperature/tmp117.c +7 -2
@@ -95,15 +95,20 @@ static int tmp117_write_raw(struct iio_dev *indio_dev, struct iio_chan_spec {struct tmp117_data *data =iio_priv (indio_dev);s16 off; +int ret;switch (mask) {case IIO_CHAN_INFO_CALIBBIAS : off =clamp_t (int, val,S16_MIN ,S16_MAX );if (off == data->calibbias)return 0 ; + + ret =i2c_smbus_write_word_swapped (data->client,TMP117_REG_TEMP_OFFSET , off); +if (ret) +return ret; + data->calibbias = off; -return i2c_smbus_write_word_swapped (data->client, -TMP117_REG_TEMP_OFFSET , off); +return 0 ;default :return -EINVAL ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 153/1756 iio: pressure: rohm-bm1390: Fix AVE_NUM initialization
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Matti Vaittinen <[email protected]>
[ Upstream commit 64f4173ad1a7f1b247296c84e624f5095be170c7 ]
The BM1390 tries to initialize the AVE_NUM to 110b at the start-up. The field location is not taken into account, and value is written unsifted. This causes the AVE_NUM to be initialized to zero.
Use FIELD_PREP() to shift the intended AVE_NUM value to correct field.
--- drivers/iio/pressure/rohm-bm1390.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/iio/pressure/rohm-bm1390.c +3 -1
@@ -484,6 +484,7 @@ static const struct iio_info bm1390_info = {static int bm1390_chip_init (struct bm1390_data *data) { +u8 regval;int ret; ret = regmap_write_bits(data->regmap, BM1390_REG_POWER,
@@ -517,8 +518,9 @@ static int bm1390_chip_init(struct bm1390_data *data)* Default to use IIR filter in "middle" mode. Also the AVE_NUM must * be fixed when IIR is in use. */ + regval =FIELD_PREP (BM1390_MASK_AVE_NUM ,BM1390_IIR_AVE_NUM ); ret =regmap_update_bits (data->regmap,BM1390_REG_MODE_CTRL , -BM1390_MASK_AVE_NUM ,BM1390_IIR_AVE_NUM ); +BM1390_MASK_AVE_NUM , regval);if (ret)return ret;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 154/1756 ata: pata_parport: Fix use-after-free in new_device_store
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pei Xiao <[email protected]>
[ Upstream commit bd46a0b22933fb45f4ff009fa4a3836124df34b3 ]
The function new_device_store() calls driver_find() without any protection against concurrent driver unregistration. This can lead to a use-after-free (UAF) when a driver is unloaded (via rmmod) in parallel with a new device addition via sysfs.
The race window exists because driver_find() returns a pointer to the driver's private data, but does not increase its reference count. The caller is responsible for ensuring the driver remains valid, but new_device_store() did not hold any lock or reference during the lookup and subsequent use.
Concurrently, pata_parport_unregister_driver() releases the pi_mutex before calling driver_unregister(), allowing new_device_store to proceed with a stale pointer after the driver has been freed.
Fix this by expanding the critical section protected by pi_mutex in both functions:
- In new_device_store(): acquire pi_mutex before calling driver_find(), and keep it held until all uses of the found driver pointer are completed.
- In pata_parport_unregister_driver(): hold pi_mutex throughout the entire unregistration process, including the driver_unregister() call, so that no concurrent lookup can see a partially removed driver.
Thread A (new_device_store) | Thread B (pata_parport_unregister_driver)
driver_find("ate") |
| mutex_lock(&pi_mutex)
| idr_remove(&protocols, id)
| mutex_unlock(&pi_mutex)
| driver_unregister(&pr->driver)
| (frees driver_private)
/* continues using stale driv */|
-> UAF! |Logs:
BUG: KASAN: slab-use-after-free in driver_find+0xd0/0xd4 Read of size 8 at addr ffffff9f970dc690 by task sh/4737 Call trace: show_stack+0x14/0x1c (C) dump_stack_lvl+0x70/0x84 print_report+0xf4/0x5a4 kasan_report+0xa0/0xe4 __asan_report_load8_noabort+0x18/0x20 driver_find+0xd0/0xd4 new_device_store+0x140/0x30c [pata_parport] bus_attr_store+0x5c/0x94 sysfs_kf_write+0x1c4/0x25c ... Allocated by task 4734: kasan_save_stack+0x28/0x4c kasan_save_track+0x1c/0x34 kasan_save_alloc_info+0x3c/0x4c __kasan_kmalloc+0x98/0xac __kmalloc_cache_noprof+0x158/0x3cc bus_add_driver+0x70/0x4d8 driver_register+0xf0/0x3b0 pata_parport_register_driver+0xb8/0x1c4 [pata_parport] 0xffffffc07f5ce014 do_one_initcall+0xb8/0x36c do_init_module+0x230/0x6d4 ... Freed by task 4737: kasan_save_stack+0x28/0x4c kasan_save_track+0x1c/0x34 kasan_save_free_info+0x48/0x8c __kasan_slab_free+0x5c/0x84 kfree+0x174/0x3e0 driver_release+0x1c/0x7c kobject_put+0x178/0x47c driver_find+0x78/0xd4 new_device_store+0x140/0x30c [pata_parport] bus_attr_store+0x5c/0x94 sysfs_kf_write+0x1c4/0x25c ...
--- drivers/ata/pata_parport/pata_parport.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/ata/pata_parport/pata_parport.c +4 -3
@@ -626,8 +626,9 @@ void pata_parport_unregister_driver(struct pi_protocol *pr)break ; }idr_remove (&protocols, id); -mutex_unlock (&pi_mutex);driver_unregister (&pr->driver); +mutex_unlock (&pi_mutex); + }EXPORT_SYMBOL_GPL (pata_parport_unregister_driver);
@@ -654,18 +655,18 @@ static ssize_t new_device_store(const struct bus_type *bus, const char *buf, siz port_wanted =-1 ; } +mutex_lock (&pi_mutex); drv =driver_find (protocol, &pata_parport_bus_type);if (!drv) {if (strcmp (protocol,"auto" )) {pr_err ("protocol %s not found\n" , protocol); +mutex_unlock (&pi_mutex);return -EINVAL ; } pr_wanted =NULL ; }else { pr_wanted = container_of(drv, struct pi_protocol, driver); } - -mutex_lock (&pi_mutex);/* walk all parports */ idr_for_each_entry (&parport_list, parport, port_num) {if (port_num == port_wanted || port_wanted ==-1 ) {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 155/1756 ARM: dts: helios4: fix lm75 supply name
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit ef473a83c63e3173ac472e42727e990b923b99db ]
The lm75 driver requests a regulator named "vs" (the +VS power pin of the chip). The Helios4 DTS incorrectly used vcc-supply instead of vs-supply, causing the regulator core to emit:
lm75 0-004c: supply vs not found, using dummy regulator
Fix the property name to match the binding and the driver.
--- arch/arm/boot/dts/marvell/armada-388-helios4.dts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm/boot/dts/marvell/armada-388-helios4.dts +1 -1
@@ -200,7 +200,7 @@ usb3-ilimit-hog { temp_sensor: temp@4c { compatible = "ti,lm75"; reg = <0x4c>; - vcc-supply = <®_3p3v>; + vs-supply = <®_3p3v>; }; eeprom@53 {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 156/1756 ARM: dts: armada-385-clearfog-gtr: fix vmmc property name
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit 337d10963f601d5a3dfb4b7aa273ca8c0b4d5172 ]
The SDHCI node references the 3.3V regulator through a bare "vmmc" property, which is not part of the mmc controller DT binding; the correct property is "vmmc-supply".
--- arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm/boot/dts/marvell/armada-385-clearfog-gtr.dtsi +1 -1
@@ -235,7 +235,7 @@ sdhci@d8000 { pinctrl-0 = <&cf_gtr_sdhci_pins>; pinctrl-names = "default"; status = "okay"; - vmmc = <®_3p3v>; + vmmc-supply = <®_3p3v>; wp-inverted; };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 157/1756 ARM: dts: armada-395-gp: drop unsupported SDHCI clock-frequency
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit a56183c7f15215d804290808a2b5a1fa997aa9cd ]
The SDHCI node carries a "clock-frequency" property, but the marvell,armada-380-sdhci binding does not define it and dtbs_check rejects the node as a result. No driver consumes it either: only a few other sdhci-pltfm based drivers (imx, mcf, iproc, arasan, dwcmshc, xenon) read that property, while sdhci-pxav3 derives the maximum clock from the io clock rate.
Remove the property.
--- arch/arm/boot/dts/marvell/armada-395-gp.dts | 1 - 1 file changed, 1 deletion(-)
arch/arm/boot/dts/marvell/armada-395-gp.dts +0 -1
@@ -59,7 +59,6 @@ sata@a8000 { /* CON18 */ sdhci@d8000 { - clock-frequency = <200000000>; broken-cd; wp-inverted; bus-width = <8>;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 158/1756 ARM: dts: armada-388-helios4: fix vmmc property name
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit 008e9faadef8c0aaa9b8a3ff05a2126e3c5b08b7 ]
The sdhci@d8000 node references the 3.3V regulator through a bare "vmmc" property, which is not part of the mmc controller DT binding. The binding requires supply properties in the form "vmmc-supply", so the current entry is ignored by the driver.
Rename the property to "vmmc-supply" so the fixed regulator is correctly wired up as the card power supply.
--- arch/arm/boot/dts/marvell/armada-388-helios4.dts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm/boot/dts/marvell/armada-388-helios4.dts +1 -1
@@ -269,7 +269,7 @@ sdhci@d8000 { &helios_sdhci_cd_pins>; pinctrl-names = "default"; status = "okay"; - vmmc = <®_3p3v>; + vmmc-supply = <®_3p3v>; wp-inverted; };
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 159/1756 ARM: dts: helios4: fix vbus-supply for USB2 PHY
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit a132798a133e76a7bb575ba95b2b64eadd245438 ]
The usb-nop-xceiv binding and driver use "vbus-supply"; the driver acquires the VBUS regulator via devm_regulator_get_exclusive("vbus") (phy-generic.c). The stale "vbus-regulator" name is never read by the driver and dtbs_check rejects it as an unknown property. Rename the property so reg_5p0v_usb is honored.
--- arch/arm/boot/dts/marvell/armada-388-helios4.dts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm/boot/dts/marvell/armada-388-helios4.dts +1 -1
@@ -140,7 +140,7 @@ fan2: j17-pwm { usb2_phy: usb2-phy { compatible = "usb-nop-xceiv"; - vbus-regulator = <®_5p0v_usb>; + vbus-supply = <®_5p0v_usb>; }; usb3_phy: usb3-phy {
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 160/1756 ARM: dts: helios4: fix spi1 location
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rosen Penev <[email protected]>
[ Upstream commit 5df4320a30a87f9bb918ace7b389026917c8d896 ]
This spi node is specified in armada-38x.dtsi with proper compatible strings whereas they are not present here. Instead of copy and pasting various lines, just reference the node in the dtsi.
This dts seems to predate the move of spi from internal-regs to the soc node so this moves it in line there.
Allows proper probing of SPI at runtime.
Remove the microsom_spi1_cs_pins pinctrl group and its reference in &spi1. The group only muxed mpp59 to the "spi1" function, but that pin (SPI1 cs0) is already covered by spi1_pins, which selects the same function for mpp56-59 in armada-38x.dtsi.
--- .../arm/boot/dts/marvell/armada-388-helios4.dts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-)
arch/arm/boot/dts/marvell/armada-388-helios4.dts +6 -11
@@ -254,13 +254,6 @@ sata3: sata-port@1 { }; }; - spi@10680 { - pinctrl-0 = <&spi1_pins - µsom_spi1_cs_pins>; - pinctrl-names = "default"; - status = "okay"; - }; - sdhci@d8000 { bus-width = <4>; cd-gpios = <&gpio0 20 GPIO_ACTIVE_LOW>;
@@ -327,11 +320,13 @@ helios_fan2_pins: helios_fan2_pins { marvell,pins = "mpp48", "mpp55"; marvell,function = "gpio"; }; - microsom_spi1_cs_pins: spi1-cs-pins { - marvell,pins = "mpp59"; - marvell,function = "spi1"; - }; }; }; }; }; + +&spi1 { + pinctrl-0 = <&spi1_pins>; + pinctrl-names = "default"; + status = "okay"; +};
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 161/1756 kexec_file: stop the top-down search before it underflows
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Breno Leitao <[email protected]>
[ Upstream commit c711461303af9f796b293b5ac06f49a885e46e71 ]
locate_mem_hole_top_down() walks candidates downwards by subtracting PAGE_SIZE whenever the window conflicts with an existing segment or with an architecture exclude range.
Nothing stops that subtraction at zero, so a search that reaches the bottom of the address space wraps temp_start around and continues.
The walk starts inside the range being scanned and only moves down, so bail out once a candidate ends up above end. That covers every step in the loop rather than the subtractions alone, and it matches locate_mem_hole_bottom_up(), which already bounds its candidate on both sides.
This is a better check than subtracting with check_sub_overflow(), given that we would have 3 subtractions in this block, and this single fix would take care of them all (instead of three check_sub_overflow()).
--- kernel/kexec_file.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/kexec_file.c +3 -1
@@ -474,7 +474,9 @@ static int locate_mem_hole_top_down(unsigned long start, unsigned long end,/* align down start */ temp_start =ALIGN_DOWN (temp_start, kbuf->buf_align); -if (temp_start < start || temp_start < kbuf->buf_min) +/* A candidate above the range means the walk wrapped around */ +if (temp_start < start || temp_start < kbuf->buf_min || + temp_start > end)return 0 ; temp_end = temp_start + kbuf->memsz -1 ;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 162/1756 perf jitdump: Fix extended header read that always fails
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit 598e905931380f0714d5fd50cecfac615a1ec742 ]
jit_open() sets bsz = bs before the fread() that uses bs - bsz as the read size, making the expression always evaluate to zero. fread() with size 0 returns 0, which triggers the ret != 1 error path — so extended jitdump headers (total_size > sizeof(header)) have been silently broken since the original implementation.
Additionally, when 0 < bs <= bsz the if (bs > bsz) block is skipped entirely, leaving extended header bytes unread in the stream. Subsequent jit_get_next_entry() calls then parse those leftover bytes as a jr_prefix, corrupting the record stream.
Fix by separating the buffer growth from the read: realloc only when bs > bsz, then unconditionally fread bs bytes when bs > 0.
--- tools/perf/util/jitdump.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
tools/perf/util/jitdump.c +5 -3
@@ -223,10 +223,12 @@ jit_open(struct jit_buf_desc *jd, const char *name) n =realloc (buf, bs);if (!n) goto error; - bsz = bs; buf = n; -/* read extra we do not know about */ - ret =fread (buf, bs - bsz,1 , jd->in); + bsz = bs; + } +if (bs >0 ) { +/* consume extended header bytes from the stream */ + ret =fread (buf, bs,1 , jd->in);if (ret !=1 ) goto error; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 163/1756 perf jitdump: Fix debug_data and unwinding_data leaks
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit 2bd967f3adcba1d3e54f10b0d8b25f950e4f03fd ]
jit_repipe_debug_info() overwrites jd->debug_data without freeing the previous allocation. If two consecutive JIT_CODE_DEBUG_INFO records appear without an intervening LOAD record consuming the data, the first allocation leaks.
The sibling jit_repipe_unwinding_info() already frees the old jd->unwinding_data before reassignment — add the same pattern to jit_repipe_debug_info() using zfree().
Also add cleanup of both buffers in jit_close() so they are freed when the jitdump session ends, even if no LOAD record consumed them.
--- tools/perf/util/jitdump.c | 3 +++ 1 file changed, 3 insertions(+)
tools/perf/util/jitdump.c +3 -0
@@ -116,6 +116,8 @@ jit_close(struct jit_buf_desc *jd)funlockfile (jd->in);fclose (jd->in); jd->in =NULL ; +zfree (&jd->debug_data); +zfree (&jd->unwinding_data); } static int
@@ -646,6 +648,7 @@ static int jit_repipe_debug_info(struct jit_buf_desc *jd, union jr_entry *jr)memcpy (data, &jr->info.entries, sz); +zfree (&jd->debug_data); jd->debug_data = data;/*
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 164/1756 perf jitdump: Validate code_size against total_size in code load
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit 06c7cf7a072fcd52e68471628c56630d2bdcc650 ]
jit_repipe_code_load() reads code_size from the jitdump record and uses it to compute a pointer to the code blob:
code = (unsigned long)jr + jr->load.p.total_size - csize;
An oversized code_size underflows the pointer arithmetic, causing OOB reads into earlier heap memory. Validate that code_size fits within the record (total_size - sizeof(jr->load)) before the pointer computation.
code_size is uint64_t but csize is int; values above INT_MAX wrap negative when narrowed into csize, which defeats the bounds check and sends the code pointer past the end of the record. Reject those too.
--- tools/perf/util/jitdump.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
tools/perf/util/jitdump.c +11 -0
@@ -9,6 +9,7 @@#include <fcntl.h> #include <unistd.h> #include <inttypes.h> +#include <limits.h> #include <byteswap.h> #include <sys/stat.h> #include <sys/mman.h>
@@ -450,6 +451,16 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) csize = jr->load.code_size; usize = jd->unwinding_mapped_size; addr = jr->load.code_addr; + +/* code blob lives at the end of the record, validate it fits */ +if (jr->load.p.total_size <sizeof (jr->load) || + jr->load.code_size > jr->load.p.total_size -sizeof (jr->load) || + jr->load.code_size >INT_MAX ) { +pr_warning ("jitdump: invalid code_size %" PRIu64" (total_size=%u) in code_load record\n" , + (uint64_t )jr->load.code_size, jr->load.p.total_size); +return -1 ; + } + sym = (void *)((unsigned long )jr +sizeof (jr->load)); code = (unsigned long )jr + jr->load.p.total_size - csize; count = jr->load.code_index;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 165/1756 perf jitdump: Prevent integer underflow in debug info size calculation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit dfe8fe96efca3c32979dc0859f88e15b677d25f1 ]
jit_repipe_debug_info() and jit_repipe_unwinding_info() compute payload sizes by subtracting the fixed header size from total_size:
sz = jr->prefix.total_size - sizeof(jr->info);
When total_size is smaller than the header struct (from a truncated or corrupted jitdump record), the subtraction underflows to a massive value, causing an oversized allocation followed by an OOB memcpy.
Validate that total_size covers at least the fixed header before the subtraction in both functions.
--- tools/perf/util/jitdump.c | 8 ++++++++ 1 file changed, 8 insertions(+)
tools/perf/util/jitdump.c +8 -0
@@ -652,6 +652,10 @@ static int jit_repipe_debug_info(struct jit_buf_desc *jd, union jr_entry *jr)if (!(jd && jr))return -1 ; +/* total_size must cover at least the fixed header */ +if (jr->prefix.total_size <sizeof (jr->info)) +return -1 ; + sz = jr->prefix.total_size -sizeof (jr->info); data =malloc (sz);if (!data)
@@ -680,6 +684,10 @@ jit_repipe_unwinding_info(struct jit_buf_desc *jd, union jr_entry *jr)if (!(jd && jr))return -1 ; +/* total_size must cover at least the fixed header */ +if (jr->prefix.total_size <sizeof (jr->unwinding)) +return -1 ; + unwinding_data_size = jr->prefix.total_size -sizeof (jr->unwinding); unwinding_data =malloc (unwinding_data_size);if (!unwinding_data)
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 166/1756 perf jitdump: Bounds-check debug entry byte-swap loop
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit ede3cd8151675c2983cd49104b1e9b25a3712ed8 ]
The byte-swap loop for JIT_CODE_DEBUG_INFO uses array indexing (jr->info.entries[n]) to iterate debug entries. struct debug_entry has a flexible array member name[], so each entry has a different size. Array indexing computes offsets assuming fixed-size elements, landing inside variable-length name strings after the first entry and byte-swapping garbage.
Additionally, nr_entry is read from untrusted jitdump input without validation against total_size, so a crafted value causes OOB reads.
Replace the array indexing with debug_entry_next() pointer arithmetic (which correctly accounts for the variable-length name) and bounds-check each entry against the record's total_size before byte-swapping.
--- tools/perf/util/jitdump.c | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-)
tools/perf/util/jitdump.c +22 -4
@@ -318,14 +318,32 @@ jit_get_next_entry(struct jit_buf_desc *jd)switch (id) {case JIT_CODE_DEBUG_INFO :if (jd->needs_bswap) { +void *end = (void *)jr + jr->prefix.total_size; +struct debug_entry *ent;uint64_t n; + jr->info.code_addr =bswap_64 (jr->info.code_addr); jr->info.nr_entry =bswap_64 (jr->info.nr_entry); -for (n =0 ; n < jr->info.nr_entry; n++) { - jr->info.entries[n].addr =bswap_64 (jr->info.entries[n].addr); - jr->info.entries[n].lineno =bswap_32 (jr->info.entries[n].lineno); - jr->info.entries[n].discrim =bswap_32 (jr->info.entries[n].discrim); + +/* +* debug_entry has a variable-length name[], so array +* indexing would compute wrong offsets — use +* debug_entry_next() and bounds-check each entry. +*/ + ent = &jr->info.entries[0 ]; +for (n =0 ; n < jr->info.nr_entry; n++) { +if ((void *)ent +sizeof (*ent) > end) +break ; +/* name must be NUL-terminated within the record */ +if (!memchr (ent->name,'\0' , (char *)end - ent->name)) +break ; + ent->addr =bswap_64 (ent->addr); + ent->lineno =bswap_32 (ent->lineno); + ent->discrim =bswap_32 (ent->discrim); + ent =debug_entry_next (ent); } +/* clamp so downstream consumers don't overrun */ + jr->info.nr_entry = n; }break ;case JIT_CODE_UNWINDING_INFO :
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 167/1756 perf jitdump: Check snprintf return before computing header size
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit 0155f05ea6e133c18a04b8b5945cac59870da156 ]
snprintf() returns the would-have-been length on truncation. When the jitted filename exceeds PATH_MAX, the unclamped 'size' value inflates sizeof(event->mmap2.filename) - size into a massive underflow, causing the header.size computation to write an oversized header. The subsequent write to 'id = event + header.size - idr_size' then corrupts the heap.
Clamp size to PATH_MAX - 1 after snprintf in both jit_repipe_code_load() and jit_repipe_code_move().
--- tools/perf/util/jitdump.c | 6 ++++++ 1 file changed, 6 insertions(+)
tools/perf/util/jitdump.c +6 -0
@@ -493,6 +493,9 @@ static int jit_repipe_code_load(struct jit_buf_desc *jd, union jr_entry *jr) jd->dir, nspid, count); +/* snprintf returns would-be length on truncation, clamp to buffer */ +if (size >=sizeof (event->mmap2.filename)) + size =sizeof (event->mmap2.filename) -1 ; size++;/* for \0 */
@@ -607,6 +610,9 @@ static int jit_repipe_code_move(struct jit_buf_desc *jd, union jr_entry *jr) jd->dir, nspid, jr->move.code_index); +/* snprintf returns would-be length on truncation, clamp to buffer */ +if (size >=sizeof (event->mmap2.filename)) + size =sizeof (event->mmap2.filename) -1 ; size++;/* for \0 */
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 168/1756 perf jitdump: Fix funlockfile on unlocked stream in jit_open() error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arnaldo Carvalho de Melo <[email protected]>
[ Upstream commit bfde6848c1e24fd979d0138c57c1cc28c35093c3 ]
If the malloc() for the initial read buffer fails, jit_open() jumps to the error label which calls funlockfile(jd->in). However, flockfile() is called later in the function, so at this point the stream was never locked. Calling funlockfile() on an unlocked stream is undefined behavior per POSIX.
Split the error path into two labels: 'error' (after flockfile) calls funlockfile before cleanup, 'error_noflock' (before flockfile) skips the unlock.
--- tools/perf/util/jitdump.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
tools/perf/util/jitdump.c +3 -2
@@ -156,7 +156,7 @@ jit_open(struct jit_buf_desc *jd, const char *name) buf =malloc (bsz);if (!buf) - goto error; + goto error_noflock;/* * protect from writer modifying the file while we are reading it
@@ -244,8 +244,9 @@ jit_open(struct jit_buf_desc *jd, const char *name)return 0 ; error: -free (buf);funlockfile (jd->in); +error_noflock: +free (buf);fclose (jd->in);return retval; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerPATCH 169/1756 perf python: Constify variables and parameters
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ian Rogers <[email protected]>
[ Upstream commit b8816289ab390f63c7bfeb9a369defa732114f0e ]
Opportunistically constify variables and parameters when possible.
Stable-dep-of: 7fc5851aac60 ("perf jitdump: Free event in jit_repipe_code_move()")
--- tools/perf/util/python.c | 55 +++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 26 deletions(-)
tools/perf/util/python.c +29 -26
@@ -63,7 +63,7 @@ struct pyrf_event {sample_member_def (sample_period, period,T_ULONGLONG ,"event period" ), \sample_member_def (sample_cpu, cpu,T_UINT ,"event cpu" ), -static char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object."); +static const char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object.");static PyMemberDef pyrf_mmap_event__members[] = { sample_members
@@ -78,7 +78,7 @@ static PyMemberDef pyrf_mmap_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_mmap_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_mmap_event__repr (const struct pyrf_event *pevent) {PyObject *ret;char *s;
@@ -107,7 +107,7 @@ static PyTypeObject pyrf_mmap_event__type = { .tp_repr = (reprfunc)pyrf_mmap_event__repr, }; -static char pyrf_task_event__doc[] =PyDoc_STR ("perf task (fork/exit) event object." ); +static const char pyrf_task_event__doc[] =PyDoc_STR ("perf task (fork/exit) event object." );static PyMemberDef pyrf_task_event__members[] = { sample_members
@@ -120,7 +120,7 @@ static PyMemberDef pyrf_task_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_task_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_task_event__repr (const struct pyrf_event *pevent) { return PyUnicode_FromFormat("{ type: %s, pid: %u, ppid: %u, tid: %u, " "ptid: %u, time: %" PRI_lu64 "}",
@@ -142,7 +142,7 @@ static PyTypeObject pyrf_task_event__type = { .tp_repr = (reprfunc)pyrf_task_event__repr, }; -static char pyrf_comm_event__doc[] =PyDoc_STR ("perf comm event object." ); +static const char pyrf_comm_event__doc[] =PyDoc_STR ("perf comm event object." );static PyMemberDef pyrf_comm_event__members[] = { sample_members
@@ -153,7 +153,7 @@ static PyMemberDef pyrf_comm_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_comm_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_comm_event__repr (const struct pyrf_event *pevent) { return PyUnicode_FromFormat("{ type: comm, pid: %u, tid: %u, comm: %s }", pevent->event.comm.pid,
@@ -171,7 +171,7 @@ static PyTypeObject pyrf_comm_event__type = { .tp_repr = (reprfunc)pyrf_comm_event__repr, }; -static char pyrf_throttle_event__doc[] =PyDoc_STR ("perf throttle event object." ); +static const char pyrf_throttle_event__doc[] =PyDoc_STR ("perf throttle event object." );static PyMemberDef pyrf_throttle_event__members[] = { sample_members
@@ -182,9 +182,10 @@ static PyMemberDef pyrf_throttle_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_throttle_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_throttle_event__repr (const struct pyrf_event *pevent) { -struct perf_record_throttle *te = (struct perf_record_throttle *)(&pevent->event.header +1 ); +const struct perf_record_throttle *te = (const struct perf_record_throttle *) + (&pevent->event.header +1 ); return PyUnicode_FromFormat("{ type: %sthrottle, time: %" PRI_lu64 ", id: %" PRI_lu64 ", stream_id: %" PRI_lu64 " }",
@@ -202,7 +203,7 @@ static PyTypeObject pyrf_throttle_event__type = { .tp_repr = (reprfunc)pyrf_throttle_event__repr, }; -static char pyrf_lost_event__doc[] =PyDoc_STR ("perf lost event object." ); +static const char pyrf_lost_event__doc[] =PyDoc_STR ("perf lost event object." );static PyMemberDef pyrf_lost_event__members[] = { sample_members
@@ -211,7 +212,7 @@ static PyMemberDef pyrf_lost_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_lost_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_lost_event__repr (const struct pyrf_event *pevent) {PyObject *ret;char *s;
@@ -237,7 +238,7 @@ static PyTypeObject pyrf_lost_event__type = { .tp_repr = (reprfunc)pyrf_lost_event__repr, }; -static char pyrf_read_event__doc[] =PyDoc_STR ("perf read event object." ); +static const char pyrf_read_event__doc[] =PyDoc_STR ("perf read event object." );static PyMemberDef pyrf_read_event__members[] = { sample_members
@@ -246,7 +247,7 @@ static PyMemberDef pyrf_read_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_read_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_read_event__repr (const struct pyrf_event *pevent) { return PyUnicode_FromFormat("{ type: read, pid: %u, tid: %u }", pevent->event.read.pid,
@@ -267,7 +268,7 @@ static PyTypeObject pyrf_read_event__type = { .tp_repr = (reprfunc)pyrf_read_event__repr, }; -static char pyrf_sample_event__doc[] =PyDoc_STR ("perf sample event object." ); +static const char pyrf_sample_event__doc[] =PyDoc_STR ("perf sample event object." );static PyMemberDef pyrf_sample_event__members[] = { sample_members
@@ -275,7 +276,7 @@ static PyMemberDef pyrf_sample_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_sample_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_sample_event__repr (const struct pyrf_event *pevent) {PyObject *ret;char *s;
@@ -290,13 +291,13 @@ static PyObject *pyrf_sample_event__repr(struct pyrf_event *pevent) }#ifdef HAVE_LIBTRACEEVENT -static bool is_tracepoint (struct pyrf_event *pevent) +static bool is_tracepoint (const struct pyrf_event *pevent) {return pevent->evsel->core.attr.type ==PERF_TYPE_TRACEPOINT ; }static PyObject * -tracepoint_field (struct pyrf_event *pe,struct tep_format_field *field) +tracepoint_field (const struct pyrf_event *pe,struct tep_format_field *field) {struct tep_handle *pevent = field->event->tep;void *data = pe->sample.raw_data;
@@ -385,7 +386,7 @@ static PyTypeObject pyrf_sample_event__type = { .tp_getattro = (getattrofunc) pyrf_sample_event__getattro, }; -static char pyrf_context_switch_event__doc[] =PyDoc_STR ("perf context_switch event object." ); +static const char pyrf_context_switch_event__doc[] =PyDoc_STR ("perf context_switch event object." );static PyMemberDef pyrf_context_switch_event__members[] = { sample_members
@@ -395,7 +396,7 @@ static PyMemberDef pyrf_context_switch_event__members[] = { { .name = NULL, }, }; -static PyObject *pyrf_context_switch_event__repr (struct pyrf_event *pevent) +static PyObject *pyrf_context_switch_event__repr (const struct pyrf_event *pevent) {PyObject *ret;char *s;
@@ -475,7 +476,7 @@ static PyTypeObject *pyrf_event__type[] = { [PERF_RECORD_SWITCH_CPU_WIDE] = &pyrf_context_switch_event__type, }; -static PyObject *pyrf_event__new (union perf_event *event) +static PyObject *pyrf_event__new (const union perf_event *event) {struct pyrf_event *pevent;PyTypeObject *ptype;
@@ -548,7 +549,7 @@ static PySequenceMethods pyrf_cpu_map__sequence_methods = { .sq_item = pyrf_cpu_map__item, }; -static char pyrf_cpu_map__doc[] =PyDoc_STR ("cpu map object." ); +static const char pyrf_cpu_map__doc[] =PyDoc_STR ("cpu map object." );static PyTypeObject pyrf_cpu_map__type = {PyVarObject_HEAD_INIT (NULL ,0 )
@@ -617,7 +618,7 @@ static PySequenceMethods pyrf_thread_map__sequence_methods = { .sq_item = pyrf_thread_map__item, }; -static char pyrf_thread_map__doc[] =PyDoc_STR ("thread map object." ); +static const char pyrf_thread_map__doc[] =PyDoc_STR ("thread map object." );static PyTypeObject pyrf_thread_map__type = {PyVarObject_HEAD_INIT (NULL ,0 )
@@ -909,7 +910,7 @@ static PyMethodDef pyrf_evsel__methods[] = { { .ml_name = NULL, } }; -static char pyrf_evsel__doc[] =PyDoc_STR ("perf event selector list object." ); +static const char pyrf_evsel__doc[] =PyDoc_STR ("perf event selector list object." );static PyTypeObject pyrf_evsel__type = {PyVarObject_HEAD_INIT (NULL ,0 )
@@ -1194,7 +1195,7 @@ static PySequenceMethods pyrf_evlist__sequence_methods = { .sq_item = pyrf_evlist__item, }; -static char pyrf_evlist__doc[] =PyDoc_STR ("perf event selector list object." ); +static const char pyrf_evlist__doc[] =PyDoc_STR ("perf event selector list object." );static PyTypeObject pyrf_evlist__type = {PyVarObject_HEAD_INIT (NULL ,0 )
@@ -1216,10 +1217,12 @@ static int pyrf_evlist__setup_types(void)#define PERF_CONST (name) { #name, PERF_##name } -static struct { +struct perf_constant {const char *name;int value; -} perf__constants[] = { +}; + +static const struct perf_constant perf__constants[] = {PERF_CONST (TYPE_HARDWARE ),PERF_CONST (TYPE_SOFTWARE ),PERF_CONST (TYPE_TRACEPOINT ),
Signature · 1 line
2.53.0