6.12.112-rc1 review
Greg Kroah-Hartman
maintainerPATCH 608/877 udf: Move udf_map_block() up
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
[ Upstream commit 97e9d759a4193eabe4d8b6ecac093aac664c16e3 ]
Move udf_map_block() in the file to avoid forward declarations.
Stable-dep-of: 62333e480d12 ("udf: Fix data loss when converting inline inodes to out of line")
--- fs/udf/inode.c | 118 ++++++++++++++++++++++++++++----------------------------- 1 file changed, 59 insertions(+), 59 deletions(-)
fs/udf/inode.c +59 -59
@@ -330,65 +330,6 @@ const struct address_space_operations ud .migrate_folio = buffer_migrate_folio, }; -/* -* Expand file stored in ICB to a normal one-block-file -* -* This function requires i_mutex held -*/ -int udf_expand_file_adinicb (struct inode *inode) -{ -struct folio *folio; -struct udf_inode_info *iinfo =UDF_I (inode); -int err; - -WARN_ON_ONCE (!inode_is_locked (inode)); -if (!iinfo->i_lenAlloc) { -down_write (&iinfo->i_data_sem); -if (UDF_QUERY_FLAG (inode->i_sb,UDF_FLAG_USE_SHORT_AD )) - iinfo->i_alloc_type =ICBTAG_FLAG_AD_SHORT ; -else - iinfo->i_alloc_type =ICBTAG_FLAG_AD_LONG ; -up_write (&iinfo->i_data_sem); -mark_inode_dirty (inode); -return 0 ; - } - - folio =__filemap_get_folio (inode->i_mapping,0 , -FGP_LOCK |FGP_ACCESSED |FGP_CREAT ,GFP_KERNEL ); -if (IS_ERR (folio)) -return PTR_ERR (folio); - -if (!folio_test_uptodate (folio)) -udf_adinicb_read_folio (folio); -down_write (&iinfo->i_data_sem); -memset (iinfo->i_data + iinfo->i_lenEAttr,0x00 , - iinfo->i_lenAlloc); - iinfo->i_lenAlloc =0 ; -if (UDF_QUERY_FLAG (inode->i_sb,UDF_FLAG_USE_SHORT_AD )) - iinfo->i_alloc_type =ICBTAG_FLAG_AD_SHORT ; -else - iinfo->i_alloc_type =ICBTAG_FLAG_AD_LONG ; -folio_mark_dirty (folio); -folio_unlock (folio); -up_write (&iinfo->i_data_sem); - err =filemap_fdatawrite (inode->i_mapping); -if (err) { -/* Restore everything back so that we don't lose data... */ -folio_lock (folio); -down_write (&iinfo->i_data_sem); -memcpy_from_folio (iinfo->i_data + iinfo->i_lenEAttr, - folio,0 , inode->i_size); -folio_unlock (folio); - iinfo->i_alloc_type =ICBTAG_FLAG_AD_IN_ICB ; - iinfo->i_lenAlloc = inode->i_size; -up_write (&iinfo->i_data_sem); - } -folio_put (folio); -mark_inode_dirty (inode); - -return err; -} -#define UDF_MAP_CREATE 0x01/* Mapping can allocate new blocks */ #define UDF_MAP_NOPREALLOC 0x02/* Do not preallocate blocks */
@@ -449,6 +390,65 @@ out_read:return ret; } +/* +* Expand file stored in ICB to a normal one-block-file +* +* This function requires i_mutex held +*/ +int udf_expand_file_adinicb (struct inode *inode) +{ +struct folio *folio; +struct udf_inode_info *iinfo =UDF_I (inode); +int err; + +WARN_ON_ONCE (!inode_is_locked (inode)); +if (!iinfo->i_lenAlloc) { +down_write (&iinfo->i_data_sem); +if (UDF_QUERY_FLAG (inode->i_sb,UDF_FLAG_USE_SHORT_AD )) + iinfo->i_alloc_type =ICBTAG_FLAG_AD_SHORT ; +else + iinfo->i_alloc_type =ICBTAG_FLAG_AD_LONG ; +up_write (&iinfo->i_data_sem); +mark_inode_dirty (inode); +return 0 ; + } + + folio =__filemap_get_folio (inode->i_mapping,0 , +FGP_LOCK |FGP_ACCESSED |FGP_CREAT ,GFP_KERNEL ); +if (IS_ERR (folio)) +return PTR_ERR (folio); + +if (!folio_test_uptodate (folio)) +udf_adinicb_read_folio (folio); +down_write (&iinfo->i_data_sem); +memset (iinfo->i_data + iinfo->i_lenEAttr,0x00 , + iinfo->i_lenAlloc); + iinfo->i_lenAlloc =0 ; +if (UDF_QUERY_FLAG (inode->i_sb,UDF_FLAG_USE_SHORT_AD )) + iinfo->i_alloc_type =ICBTAG_FLAG_AD_SHORT ; +else + iinfo->i_alloc_type =ICBTAG_FLAG_AD_LONG ; +folio_mark_dirty (folio); +folio_unlock (folio); +up_write (&iinfo->i_data_sem); + err =filemap_fdatawrite (inode->i_mapping); +if (err) { +/* Restore everything back so that we don't lose data... */ +folio_lock (folio); +down_write (&iinfo->i_data_sem); +memcpy_from_folio (iinfo->i_data + iinfo->i_lenEAttr, + folio,0 , inode->i_size); +folio_unlock (folio); + iinfo->i_alloc_type =ICBTAG_FLAG_AD_IN_ICB ; + iinfo->i_lenAlloc = inode->i_size; +up_write (&iinfo->i_data_sem); + } +folio_put (folio); +mark_inode_dirty (inode); + +return err; +} +static int __udf_get_block (struct inode *inode,sector_t block,struct buffer_head *bh_result,int flags) {
Greg Kroah-Hartman
maintainerPATCH 609/877 udf: Fix data loss when converting inline inodes to out of line
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
[ Upstream commit 62333e480d12ab186f89fe2725b372d12f72d5eb ]
When udf_expand_file_adinicb() converts file from inline format to out of line, we use filemap_fdatawrite() to writeout the data to the new blocks. However since 36580ed08776 ("udf: Do not allocate blocks on page writeback") the writeback actually doesn't allocate the new block and the folio dirty bit is just silently cleared. Thus unless the file is written to after the conversion (as it can easily happen in case of truncate up), the data is just lost. Fix the problem by explicitely allocating the block underlying the data before starting writeback.
--- fs/udf/inode.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-)
fs/udf/inode.c +13 -2
@@ -399,6 +399,10 @@ int udf_expand_file_adinicb(struct inode {struct folio *folio;struct udf_inode_info *iinfo =UDF_I (inode); +struct udf_map_rq map = { + .lblk =0 , + .iflags =UDF_MAP_CREATE , + };int err;WARN_ON_ONCE (!inode_is_locked (inode));
@@ -428,20 +432,27 @@ int udf_expand_file_adinicb(struct inode iinfo->i_alloc_type =ICBTAG_FLAG_AD_SHORT ; else iinfo->i_alloc_type = ICBTAG_FLAG_AD_LONG; +up_write (&iinfo->i_data_sem); + +/* Allocate the block underlying the data */ + err =udf_map_block (inode, &map); +if (err <0 ) + goto restore; +folio_mark_dirty (folio);folio_unlock (folio); -up_write (&iinfo->i_data_sem); err =filemap_fdatawrite (inode->i_mapping);if (err) {/* Restore everything back so that we don't lose data... */ folio_lock (folio); +restore:down_write (&iinfo->i_data_sem);memcpy_from_folio (iinfo->i_data + iinfo->i_lenEAttr, folio,0 , inode->i_size); -folio_unlock (folio); iinfo->i_alloc_type =ICBTAG_FLAG_AD_IN_ICB ; iinfo->i_lenAlloc = inode->i_size;up_write (&iinfo->i_data_sem); +folio_unlock (folio); }folio_put (folio);mark_inode_dirty (inode);
Greg Kroah-Hartman
maintainerPATCH 610/877 usb: dwc3: gadget: Reinitiate stream for all host NoStream behavior
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thinh Nguyen <[email protected]>
[ Upstream commit dcfe437492e27d54f3ac491aed024da760f5c43c ]
There are too many different host behaviors when it comes to NoStream handling, and not everyone follows the USB and xHCI spec. The DWC3 driver attempts to do some guess work to interop with different hosts, but it can't cover everything. Let's keep it simple and treat every host the same: just retry on NoStream after a 100ms of no response delay. Note that some hosts cannot handle frequent retries. This may affect performance on certain defective hosts, but NoStream is a rare occurrence and interoperability is more important.
Stable-dep-of: b58e6200450d ("usb: dwc3: clear forceRM when issuing EndTransfer")
--- drivers/usb/dwc3/core.h | 3 - drivers/usb/dwc3/gadget.c | 109 ++++++++++++++++++++++++---------------------- 2 files changed, 59 insertions(+), 53 deletions(-)
drivers/usb/dwc3/core.h +2 -1
@@ -742,6 +742,7 @@ struct dwc3_event_buffer {*/ struct dwc3_ep {struct usb_ep endpoint; +struct delayed_work nostream_work;struct list_head cancelled_list;struct list_head pending_list;struct list_head started_list;
@@ -764,7 +765,7 @@ struct dwc3_ep {#define DWC3_EP_WAIT_TRANSFER_COMPLETE BIT(7)#define DWC3_EP_IGNORE_NEXT_NOSTREAM BIT(8)#define DWC3_EP_FORCE_RESTART_STREAM BIT(9) -#define DWC3_EP_FIRST_STREAM_PRIMED BIT(10) +#define DWC3_EP_STREAM_PRIMED BIT(10)#define DWC3_EP_PENDING_CLEAR_STALL BIT(11)#define DWC3_EP_TXFIFO_RESIZED BIT(12)#define DWC3_EP_DELAY_STOP BIT(13)
drivers/usb/dwc3/gadget.c +57 -52
143 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 611/877 usb: dwc3: clear forceRM when issuing EndTransfer
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Elson Serrao <[email protected]>
[ Upstream commit b58e6200450d350314db0ecda7d6d1bde3281e80 ]
The forceRM bit of the DEPCMD register controls the behavior of the EndTransfer command used to stop an active transfer. Older DWC3 programming guide revisions recommended setting forceRM=1 when issuing EndTransfer. Newer programming guide revisions recommend issuing EndTransfer with forceRM cleared.
With forceRM=1 on DWC_usb31 v2.00a and v2.10a controllers, a transfer aborted through the ep_dequeue path was observed to remain active after EndTransfer completion. A subsequent StartTransfer issued on the same endpoint triggered writes associated with the aborted transfer. This resulted in an SMMU fault because the transfer buffer had already been unmapped during EndTransfer command-completion cleanup.
Using forceRM=0 eliminates the issue. Although older DWC3 programming guide revisions recommended setting forceRM=1, no issues are known from using forceRM=0. Clear forceRM when issuing EndTransfer to provide consistent EndTransfer behavior and align with newer programming guide recommendations.
--- drivers/usb/dwc3/ep0.c | 2 +- drivers/usb/dwc3/gadget.c | 21 +++++++++++++-------- 2 files changed, 14 insertions(+), 9 deletions(-)
drivers/usb/dwc3/ep0.c +1 -1
@@ -304,7 +304,7 @@ void dwc3_ep0_out_start(struct dwc3 *dwc dwc3_ep->flags &= ~DWC3_EP_DELAY_STOP ;if (dwc->connected) -dwc3_stop_active_transfer (dwc3_ep, true, true); +dwc3_stop_active_transfer (dwc3_ep, false, true);else dwc3_remove_requests (dwc, dwc3_ep, -ESHUTDOWN ); }
drivers/usb/dwc3/gadget.c +13 -8
@@ -991,7 +991,7 @@ static int __dwc3_gadget_ep_enable(struc* controller to generate an ERDY to initiate the * stream. */ -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);/* * All stream eps will reinitiate stream on NoStream
@@ -1019,7 +1019,7 @@ void dwc3_remove_requests(struct dwc3 *d {struct dwc3_request *req; -dwc3_stop_active_transfer (dep, true, false); +dwc3_stop_active_transfer (dep, false, false);/* If endxfer is delayed, avoid unmapping requests */ if (dep->flags &DWC3_EP_DELAY_STOP )
@@ -1709,7 +1709,7 @@ static int __dwc3_gadget_kick_transfer(sif (ret == -EAGAIN )return ret; -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);list_for_each_entry_safe (req, tmp, &dep->started_list, list)dwc3_gadget_move_cancelled_request (req,DWC3_REQUEST_STATUS_DEQUEUED );
@@ -1746,6 +1746,11 @@ static int __dwc3_gadget_get_frame(struc* the controller won't update the TRB progress on command * completion. It also won't clear the HWO bit in the TRB. * The command will also not complete immediately in that case. +* +* Older programming guide revisions recommended setting ForceRM to 1 +* when ending a transfer. Newer programming guide revisions now +* recommend keeping ForceRM cleared, and TRBs are properly updated +* on command completion. */ static int __dwc3_stop_active_transfer (struct dwc3_ep *dep,bool force,bool interrupt) {
@@ -1871,7 +1876,7 @@ static int dwc3_gadget_start_isoc_quirk(* to wait for the next XferNotReady to test the command again */ if (cmd_status ==0 ) { -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);return 0 ; } }
@@ -2154,7 +2159,7 @@ static int dwc3_gadget_ep_dequeue(structstruct dwc3_request *t;/* wait until it is processed */ -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);/* * Remove any started request if the transfer is
@@ -2231,7 +2236,7 @@ int __dwc3_gadget_ep_set_halt(struct dwcreturn 0 ; } -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);list_for_each_entry_safe (req, tmp, &dep->started_list, list)dwc3_gadget_move_cancelled_request (req,DWC3_REQUEST_STATUS_STALLED );
@@ -3343,7 +3348,7 @@ static void dwc3_nostream_work(struct wodwc3_send_gadget_generic_command (dwc, cmd, dep->number); }else { dep->flags |=DWC3_EP_DELAY_START ; -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);spin_unlock_irqrestore (&dwc->lock, flags);return ; }
@@ -3687,7 +3692,7 @@ static bool dwc3_gadget_endpoint_trbs_coif (usb_endpoint_xfer_isoc (dep->endpoint.desc) &&list_empty (&dep->started_list) && (list_empty (&dep->pending_list) || status == -EXDEV )) -dwc3_stop_active_transfer (dep, true, true); +dwc3_stop_active_transfer (dep, false, true);else if (dwc3_gadget_ep_should_continue (dep))if (__dwc3_gadget_kick_transfer (dep) ==0 ) no_started_trb = false;
Greg Kroah-Hartman
maintainerPATCH 612/877 wifi: rtw89: cleanup unused rtwdev::roc_work
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zong-Zhe Yang <[email protected]>
[ Upstream commit c281bdb8821461047d3e74206afbff190d1f7846 ]
The needed one was moved to rtwvif::roc_work. And, rtwdev::roc_work is unused. So, remove it.
Stable-dep-of: 667c12782aaf ("wifi: rtw89: pci: add .shutdown callback to stop rfkill polling on reboot")
--- drivers/net/wireless/realtek/rtw89/core.h | 1 - 1 file changed, 1 deletion(-)
drivers/net/wireless/realtek/rtw89/core.h +0 -1
@@ -5604,7 +5604,6 @@ struct rtw89_dev {struct delayed_work coex_rfk_chk_work;struct delayed_work cfo_track_work;struct delayed_work forbid_ba_work; -struct delayed_work roc_work;struct delayed_work antdiv_work;struct rtw89_ppdu_sts_info ppdu_sts;u8 total_sta_assoc;
Greg Kroah-Hartman
maintainerPATCH 613/877 wifi: rtw89: Hide some errors when the device is unplugged
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bitterblue Smith <[email protected]>
[ Upstream commit 0740c6beefae03066a562e3047959528d8893709 ]
A few unnecessary error messages are printed when the device is unplugged. "read swsi busy" in particular can appear ~1000 times when RTL8851BU is unplugged.
Add a new flag RTW89_FLAG_UNPLUGGED and print some error messages only when this flag is not set. The new USB driver will set the flag when the device is unplugged.
Stable-dep-of: 667c12782aaf ("wifi: rtw89: pci: add .shutdown callback to stop rfkill polling on reboot")
--- drivers/net/wireless/realtek/rtw89/core.h | 1 + drivers/net/wireless/realtek/rtw89/mac.c | 13 ++++++++----- drivers/net/wireless/realtek/rtw89/phy.c | 3 ++- 3 files changed, 11 insertions(+), 6 deletions(-)
drivers/net/wireless/realtek/rtw89/core.h +1 -0
@@ -4724,6 +4724,7 @@ enum rtw89_flags {RTW89_FLAG_FORBIDDEN_TRACK_WROK ,RTW89_FLAG_CHANGING_INTERFACE ,RTW89_FLAG_HW_RFKILL_STATE , +RTW89_FLAG_UNPLUGGED , NUM_OF_RTW89_FLAGS, };
drivers/net/wireless/realtek/rtw89/mac.c +8 -5
@@ -88,7 +88,7 @@ int rtw89_mac_write_lte(struct rtw89_dev ret =read_poll_timeout (rtw89_read8, lte_ctrl, (lte_ctrl &BIT (5 )) !=0 ,50 ,50000 , false, rtwdev,R_AX_LTE_CTRL +3 ); -if (ret) +if (ret && !test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags))rtw89_err (rtwdev,"[ERR]lte not ready(W)\n" );rtw89_write32 (rtwdev,R_AX_LTE_WDATA , val);
@@ -104,7 +104,7 @@ int rtw89_mac_read_lte(struct rtw89_dev ret =read_poll_timeout (rtw89_read8, lte_ctrl, (lte_ctrl &BIT (5 )) !=0 ,50 ,50000 , false, rtwdev,R_AX_LTE_CTRL +3 ); -if (ret) +if (ret && !test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags))rtw89_err (rtwdev,"[ERR]lte not ready(W)\n" );rtw89_write32 (rtwdev,R_AX_LTE_CTRL ,0x800F0000 | offset);
@@ -5666,13 +5666,15 @@ int rtw89_mac_coex_init(struct rtw89_dev ret =rtw89_mac_read_lte (rtwdev,R_AX_LTE_SW_CFG_2 , &val32);if (ret) { -rtw89_err (rtwdev,"Read R_AX_LTE_SW_CFG_2 fail!\n" ); +if (!test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags)) +rtw89_err (rtwdev,"Read R_AX_LTE_SW_CFG_2 fail!\n" );return ret; } val32 = val32 &B_AX_WL_RX_CTRL ; ret =rtw89_mac_write_lte (rtwdev,R_AX_LTE_SW_CFG_2 , val32);if (ret) { -rtw89_err (rtwdev,"Write R_AX_LTE_SW_CFG_2 fail!\n" ); +if (!test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags)) +rtw89_err (rtwdev,"Write R_AX_LTE_SW_CFG_2 fail!\n" );return ret; }
@@ -5796,7 +5798,8 @@ int rtw89_mac_cfg_gnt(struct rtw89_dev * ret =rtw89_mac_write_lte (rtwdev,R_AX_LTE_SW_CFG_1 , val);if (ret) { -rtw89_err (rtwdev,"Write LTE fail!\n" ); +if (!test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags)) +rtw89_err (rtwdev,"Write LTE fail!\n" );return ret; }
drivers/net/wireless/realtek/rtw89/phy.c +2 -1
@@ -881,7 +881,8 @@ static u32 rtw89_phy_read_rf_a(struct rt30 , false, rtwdev,R_SWSI_V1 , B_SWSI_R_DATA_DONE_V1);if (ret) { -rtw89_err (rtwdev,"read swsi busy\n" ); +if (!test_bit (RTW89_FLAG_UNPLUGGED , rtwdev->flags)) +rtw89_err (rtwdev,"read swsi busy\n" );return INV_RF_DATA ; }
Greg Kroah-Hartman
maintainerPATCH 614/877 wifi: rtw89: pci: add .shutdown callback to stop rfkill polling on reboot
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: "Yuhang.chen" <[email protected]>
[ Upstream commit 667c12782aaf8dd3cb2213e528fe63a73cb63345 ]
Since the hardware rfkill polling was introduced, arm64 platforms can panic with an asynchronous SError during warm reboot:
SError Interrupt on CPU8, code 0x00000000be000011 -- SError
Workqueue: events_power_efficient rfkill_poll [rfkill]
rtw89_pci_ops_read8+0x94/0x160 [rtw89_pci]
rtw89_core_rfkill_poll+0x50/0x1e0 [rtw89_core]
rtw89_ops_rfkill_poll+0x40/0x68 [rtw89_core]
ieee80211_rfkill_poll+0x3c/0x70 [mac80211]
cfg80211_rfkill_poll+0x40/0x2a0 [cfg80211]
rfkill_poll+0x30/0x88 [rfkill]
Kernel panic - not syncing: Asynchronous SError InterruptOn the reboot path the kernel only runs device_shutdown(), which calls each driver's .shutdown callback; .remove is not invoked. The rtw89 PCI driver had no .shutdown callback, so nothing stopped the rfkill polling work while the platform was tearing the PCIe link down. Once the link is gone, the next MMIO read from the poll handler targets a non-responding device and is reported as a fatal asynchronous SError on arm64.
Add rtw89_pci_shutdown(), wired to all rtw89 PCI device drivers, which sets a new RTW89_FLAG_SHUTDOWN flag (mirroring the USB RTW89_FLAG_UNPLUGGED pattern). When the flag is set, rtw89_ops_rfkill_poll() returns early, so no MMIO read is issued to the chip after shutdown begins and the SError no longer occurs.
This does not call the full .remove path from .shutdown, to keep the shutdown handler minimal and avoid running the non-idempotent teardown twice.
--- drivers/net/wireless/realtek/rtw89/core.h | 1 + drivers/net/wireless/realtek/rtw89/mac80211.c | 3 ++- drivers/net/wireless/realtek/rtw89/pci.c | 13 +++++++++++++ drivers/net/wireless/realtek/rtw89/pci.h | 1 + drivers/net/wireless/realtek/rtw89/rtw8851be.c | 1 + drivers/net/wireless/realtek/rtw89/rtw8852ae.c | 1 + drivers/net/wireless/realtek/rtw89/rtw8852be.c | 1 + drivers/net/wireless/realtek/rtw89/rtw8852bte.c | 1 + drivers/net/wireless/realtek/rtw89/rtw8852ce.c | 1 + drivers/net/wireless/realtek/rtw89/rtw8922ae.c | 1 + 10 files changed, 23 insertions(+), 1 deletion(-)
drivers/net/wireless/realtek/rtw89/core.h +1 -0
@@ -4725,6 +4725,7 @@ enum rtw89_flags {RTW89_FLAG_CHANGING_INTERFACE ,RTW89_FLAG_HW_RFKILL_STATE ,RTW89_FLAG_UNPLUGGED , +RTW89_FLAG_SHUTDOWN , NUM_OF_RTW89_FLAGS, };
drivers/net/wireless/realtek/rtw89/mac80211.c +2 -1
@@ -1550,7 +1550,8 @@ static void rtw89_ops_rfkill_poll(structmutex_lock (&rtwdev->mutex);/* wl_disable GPIO get floating when entering LPS */ -if (test_bit (RTW89_FLAG_RUNNING , rtwdev->flags)) +if (test_bit (RTW89_FLAG_RUNNING , rtwdev->flags) || +test_bit (RTW89_FLAG_SHUTDOWN , rtwdev->flags)) goto out;rtw89_core_rfkill_poll (rtwdev, false);
drivers/net/wireless/realtek/rtw89/pci.c +13 -0
@@ -4465,6 +4465,19 @@ void rtw89_pci_remove(struct pci_dev *pd }EXPORT_SYMBOL (rtw89_pci_remove); +void rtw89_pci_shutdown (struct pci_dev *pdev) +{ +struct ieee80211_hw *hw =pci_get_drvdata (pdev); +struct rtw89_dev *rtwdev; + +if (!hw) +return ; + + rtwdev = hw->priv; +set_bit (RTW89_FLAG_SHUTDOWN , rtwdev->flags); +} +EXPORT_SYMBOL (rtw89_pci_shutdown); +MODULE_AUTHOR ("Realtek Corporation" );MODULE_DESCRIPTION ("Realtek PCI 802.11ax wireless driver" );MODULE_LICENSE ("Dual BSD/GPL" );
drivers/net/wireless/realtek/rtw89/pci.h +1 -0
@@ -1602,6 +1602,7 @@ struct pci_device_id;int rtw89_pci_probe (struct pci_dev *pdev,const struct pci_device_id *id);void rtw89_pci_remove (struct pci_dev *pdev); +void rtw89_pci_shutdown (struct pci_dev *pdev);void rtw89_pci_ops_reset (struct rtw89_dev *rtwdev);int rtw89_pci_ltr_set (struct rtw89_dev *rtwdev,bool en);int rtw89_pci_ltr_set_v1 (struct rtw89_dev *rtwdev,bool en);
drivers/net/wireless/realtek/rtw89/rtw8851be.c +1 -0
@@ -84,6 +84,7 @@ static struct pci_driver rtw89_8851be_dr .id_table = rtw89_8851be_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops, };module_pci_driver (rtw89_8851be_driver);
drivers/net/wireless/realtek/rtw89/rtw8852ae.c +1 -0
@@ -86,6 +86,7 @@ static struct pci_driver rtw89_8852ae_dr .id_table = rtw89_8852ae_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops, };module_pci_driver (rtw89_8852ae_driver);
drivers/net/wireless/realtek/rtw89/rtw8852be.c +1 -0
@@ -88,6 +88,7 @@ static struct pci_driver rtw89_8852be_dr .id_table = rtw89_8852be_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops, };module_pci_driver (rtw89_8852be_driver);
drivers/net/wireless/realtek/rtw89/rtw8852bte.c +1 -0
@@ -84,6 +84,7 @@ static struct pci_driver rtw89_8852bte_d .id_table = rtw89_8852bte_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops, };module_pci_driver (rtw89_8852bte_driver);
drivers/net/wireless/realtek/rtw89/rtw8852ce.c +1 -0
@@ -113,6 +113,7 @@ static struct pci_driver rtw89_8852ce_dr .id_table = rtw89_8852ce_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops, };module_pci_driver (rtw89_8852ce_driver);
drivers/net/wireless/realtek/rtw89/rtw8922ae.c +1 -0
@@ -82,6 +82,7 @@ static struct pci_driver rtw89_8922ae_dr .id_table = rtw89_8922ae_id_table, .probe = rtw89_pci_probe, .remove = rtw89_pci_remove, + .shutdown = rtw89_pci_shutdown, .driver.pm = &rtw89_pm_ops_be, };module_pci_driver (rtw89_8922ae_driver);
Greg Kroah-Hartman
maintainerPATCH 615/877 usb: typec: tcpm: fix debug accessory mode detection for sink ports
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xu Yang <[email protected]>
[ Upstream commit f6ec9bb4acc7182b25a793ad094a764e1cb819a7 ]
The port in debug accessory mode can be either a source or sink. The previous tcpm_port_is_debug() function only checked for source port.
Commit 8db73e6a42b6 ("usb: typec: tcpm: allow sink (ufp) to toggle into accessory mode debug") changed the detection logic to support both roles, but left some logic in _tcpm_cc_change() unchanged, This causes the state machine to transition to an incorrect state when operating as a sink in debug accessory mode. Log as below:
[ 978.637541] CC1: 0 -> 5, CC2: 0 -> 5 [state TOGGLING, polarity 0, connected] [ 978.637567] state change TOGGLING -> SRC_ATTACH_WAIT [rev1 NONE_AMS] [ 978.637596] pending state change SRC_ATTACH_WAIT -> DEBUG_ACC_ATTACHED @ 180 ms [rev1 NONE_AMS] [ 978.647098] CC1: 5 -> 0, CC2: 5 -> 5 [state SRC_ATTACH_WAIT, polarity 0, connected] [ 978.647115] state change SRC_ATTACH_WAIT -> SRC_ATTACH_WAIT [rev1 NONE_AMS]
It should go to SNK_ATTACH_WAIT instead of SRC_ATTACH_WAIT state.
To fix this, add tcpm_port_is_debug_source() and tcpm_port_is_debug_sink() helper to explicitly identify the power mode in debug accessory mode. Update the state transition logic in _tcpm_cc_change() to ensure the state machine transitions comply with Type-C specification. Also update the logic in run_state_machine() to keep consistency.
[Backport to 6.12: This tree lacks 8db73e6a42b6 and the associated sink debug-accessory state-machine support. Retain only the source-debug macro extraction and source-side call-site updates. Keep tcpm_port_is_debug() source-only and omit the sink-debug macro and all sink/audio attachment transitions introduced by the upstream dependency. This preserves existing detection and state transitions while providing tcpm_port_is_debug_source() for cd3b9cea675b ("usb: typec: tcpm: constrain TCPM_SOURCING_VBUS event handling"). No functions are added.]
Stable-dep-of: cd3b9cea675b ("usb: typec: tcpm: constrain TCPM_SOURCING_VBUS event handling")
--- drivers/usb/typec/tcpm/tcpm.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/usb/typec/tcpm/tcpm.c +7 -4
@@ -602,9 +602,12 @@ static const char * const pd_rev[] = { (tcpm_cc_is_source((port)->cc2) && \ !tcpm_cc_is_source((port)->cc1))) -#define tcpm_port_is_debug (port) \ +#define tcpm_port_is_debug_source (port) \ (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2)) +#define tcpm_port_is_debug (port) \ + tcpm_port_is_debug_source(port) +#define tcpm_port_is_audio (port) \ (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
@@ -4742,7 +4745,7 @@ static void run_state_machine(struct tcptcpm_set_state (port,SNK_UNATTACHED ,PD_T_DRP_SNK );break ;case SRC_ATTACH_WAIT : -if (tcpm_port_is_debug (port)) +if (tcpm_port_is_debug_source (port))tcpm_set_state (port,DEBUG_ACC_ATTACHED ,PD_T_CC_DEBOUNCE );else if (tcpm_port_is_audio (port))
@@ -5868,7 +5871,7 @@ static void _tcpm_cc_change(struct tcpm_switch (port->state) {case TOGGLING : -if (tcpm_port_is_debug (port) ||tcpm_port_is_audio (port) || +if (tcpm_port_is_debug_source (port) ||tcpm_port_is_audio (port) ||tcpm_port_is_source (port))tcpm_set_state (port,SRC_ATTACH_WAIT ,0 );else if (tcpm_port_is_sink (port))
@@ -5879,7 +5882,7 @@ static void _tcpm_cc_change(struct tcpm_break ;case SRC_UNATTACHED :case ACC_UNATTACHED : -if (tcpm_port_is_debug (port) ||tcpm_port_is_audio (port) || +if (tcpm_port_is_debug_source (port) ||tcpm_port_is_audio (port) ||tcpm_port_is_source (port))tcpm_set_state (port,SRC_ATTACH_WAIT ,0 );break ;
Greg Kroah-Hartman
maintainerPATCH 616/877 usb: typec: tcpm: constrain TCPM_SOURCING_VBUS event handling
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Sunil Dhamne <[email protected]>
[ Upstream commit cd3b9cea675bbfebc223f007dc2f4e79524fa54c ]
When a sink detach occurs while waiting for TX send status, the old TCPM_SOURCING_VBUS event along with TCPM_VBUS_EVENT and TCPM_CC_EVENT can be queued in port->pd_events. Because TCPM_SOURCING_VBUS is evaluated after TCPM_VBUS_EVENT and TCPM_CC_EVENT in tcpm_pd_event_handler(), a stale TCPM_SOURCING_VBUS event can override the detach handling and incorrectly set port->vbus_source and port->vbus_present to true.
Add a state guard to check that the port is either operating as a Source (tcpm_port_is_source(port)) or in a Fast Role Swap (FRS) state up to FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED before processing TCPM_SOURCING_VBUS. Otherwise, discard and log the event.
Log snippet for error condition before fix:
[72792.204955] state change SRC_ATTACHED -> SRC_STARTUP [rev3 NONE_AMS] [72792.204960] sourcing vbus [72792.204962] VBUS on [72792.204970] AMS POWER_NEGOTIATION start [72792.204974] cc:=4 [72792.205319] state change SRC_STARTUP -> AMS_START [rev3 POWER_NEGOTIATION] [72792.205325] state change AMS_START -> SRC_SEND_CAPABILITIES [rev3 POWER_NEGOTIATION] [72792.205332] PD TX, header: 0x11a1 [72792.216911] PD TX complete, status: 2 [72792.216957] pending state change SRC_SEND_CAPABILITIES -> SRC_SEND_CAPABILITIES @ 150 ms [rev3 POWER_NEGOTIATION] [72792.218005] VBUS off [72792.218013] pending state change SRC_SEND_CAPABILITIES -> SNK_UNATTACHED @ 650 ms [rev3 POWER_NEGOTIATION] [72792.218020] VBUS VSAFE0V [72792.218024] state change SRC_SEND_CAPABILITIES -> SNK_UNATTACHED [rev3 POWER_NEGOTIATION] [72792.218458] CC1: 2 -> 0, CC2: 0 -> 0 [state SNK_UNATTACHED, polarity 0, disconnected] [72792.218467] VBUS on --> VBUS left on [72792.218980] disable vbus discharge ret:0 [72792.235193] Start toggling
After fix:
[ 1195.291691] state change SRC_ATTACHED -> SRC_STARTUP [rev3 NONE_AMS] [ 1195.291698] sourcing vbus [ 1195.291700] VBUS on [ 1195.291707] AMS POWER_NEGOTIATION start [ 1195.291710] cc:=4 [ 1195.291758] state change SRC_STARTUP -> AMS_START [rev3 POWER_NEGOTIATION] [ 1195.291794] state change AMS_START -> SRC_SEND_CAPABILITIES [rev3 POWER_NEGOTIATION] [ 1195.291798] PD TX, header: 0x11a1 [ 1195.297056] PD TX complete, status: 2 [ 1195.297092] pending state change SRC_SEND_CAPABILITIES -> SRC_SEND_CAPABILITIES @ 150 ms [rev3 POWER_NEGOTIATION] [ 1195.297177] VBUS off [ 1195.297184] pending state change SRC_SEND_CAPABILITIES -> SNK_UNATTACHED @ 650 ms [rev3 POWER_NEGOTIATION] [ 1195.297227] CC1: 2 -> 0, CC2: 0 -> 0 [state SRC_SEND_CAPABILITIES, polarity 0, disconnected] [ 1195.307469] cc:=2 [ 1195.307544] pending state change SRC_SEND_CAPABILITIES -> SNK_UNATTACHED @ 650 ms [rev3 POWER_NEGOTIATION] [ 1195.307555] Discarding sourcing vbus! Invalid state SRC_SEND_CAPABILITIES [ 1195.957636] state change SRC_SEND_CAPABILITIES -> SNK_UNATTACHED [delayed 650 ms] [ 1195.957732] disable vbus discharge ret:0 [ 1195.970196] Start toggling [ 1195.970468] VBUS off [ 1196.051637] VBUS off [ 1196.051642] VBUS VSAFE0V
--- drivers/usb/typec/tcpm/tcpm.c | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-)
drivers/usb/typec/tcpm/tcpm.c +22 -6
@@ -6385,16 +6385,32 @@ static void tcpm_pd_event_handler(struct } }if (events &TCPM_SOURCING_VBUS ) { -tcpm_log (port,"sourcing vbus" );/* * In fast role swap case TCPC autonomously sources vbus. Set vbus_source -* true as TCPM wouldn't have called tcpm_set_vbus. +* true conditionally as TCPM wouldn't have called tcpm_set_vbus. +* If TCPM calls tcpm_set_vbus to source vbus, vbus_source would already +* be true. * -* When vbus is sourced on the command on TCPM i.e. TCPM called -* tcpm_set_vbus to source vbus, vbus_source would already be true. +* When TCPM_FRS_EVENT and TCPM_SOURCING_VBUS arrive simultaneously, +* handling TCPM_FRS_EVENT above transitions the state to AMS_START +* with upcoming_state FR_SWAP_SEND. */ - port->vbus_source = true; -_tcpm_pd_vbus_on (port); + +if (tcpm_port_is_source (port) || +tcpm_port_is_debug_source (port) || + (port->state ==AMS_START && port->upcoming_state ==FR_SWAP_SEND ) || + port->state ==FR_SWAP_SEND || + port->state ==FR_SWAP_SEND_TIMEOUT || + port->state ==FR_SWAP_SNK_SRC_TRANSITION_TO_OFF || + port->state ==FR_SWAP_SNK_SRC_NEW_SINK_READY || + port->state ==FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED ) { +tcpm_log (port,"sourcing vbus" ); + port->vbus_source = true; +_tcpm_pd_vbus_on (port); + }else { +tcpm_log (port,"Discarding sourcing vbus! Invalid state %s" , + tcpm_states[port->state]); + } }if (events &TCPM_PORT_CLEAN ) {tcpm_log (port,"port clean" );
Greg Kroah-Hartman
maintainerPATCH 617/877 wifi: mt76: mt7996: bound the device EEPROM address before the EFUSE copy
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryam Vargas <[email protected]>
[ Upstream commit 13b3c29a782033ce4a230be9e5618032813dbcd4 ]
mt7996_mcu_get_eeprom() derives the destination of the EFUSE/EXT block copy from the address reported by the MCU response (event->addr, a device-controlled __le32) and clamps only the copy length, never the destination offset into dev->mt76.eeprom.data. A malicious or malfunctioning device can report an arbitrary address and drive an out-of-bounds write of up to MT7996_EXT_EEPROM_BLOCK_SIZE bytes past eeprom.data.
Reject a response whose address would place the copy outside eeprom.data before deriving the destination pointer. Devices that echo the requested in-bounds offset are unaffected.
--- drivers/net/wireless/mediatek/mt76/mt7996/mcu.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/net/wireless/mediatek/mt76/mt7996/mcu.c +7 -1
@@ -3586,7 +3586,13 @@ int mt7996_mcu_get_eeprom(struct mt7996_ valid =le32_to_cpu (*(__le32 *)(skb->data +16 ));if (valid) {u32 addr =le32_to_cpu (*(__le32 *)(skb->data +12 )); -u8 *buf = (u8 *)dev->mt76.eeprom.data + addr; +u8 *buf; + +if (addr > dev->mt76.eeprom.size -MT7996_EEPROM_BLOCK_SIZE ) { +dev_kfree_skb (skb); +return -EINVAL ; + } + buf = (u8 *)dev->mt76.eeprom.data + addr;skb_pull (skb,48 );memcpy (buf, skb->data,MT7996_EEPROM_BLOCK_SIZE );
Greg Kroah-Hartman
maintainerPATCH 618/877 xhci: Cleanup Candence controller PCI device and vendor ID usage
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mathias Nyman <[email protected]>
[ Upstream commit f28a7d7db247af8b9f1090bd6b1ca1fa48a3f0e4 ]
Use predefined PCI vendor ID constant for Cadence controller in pci_ids.h Rename the Candence device ID to match the pattern other PCI vendor and device IDs use
Stable-dep-of: eae6460f6173 ("usb: cdnsp: fix wakeup from S3 after controller context loss")
--- drivers/usb/host/xhci-pci.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/usb/host/xhci-pci.c +3 -5
@@ -94,8 +94,7 @@#define PCI_DEVICE_ID_ASMEDIA_3042_XHCI 0x3042#define PCI_DEVICE_ID_ASMEDIA_3242_XHCI 0x3242 -#define PCI_DEVICE_ID_CADENCE 0x17CD -#define PCI_DEVICE_ID_CADENCE_SSP 0x0200 +#define PCI_DEVICE_ID_CDNS_SSP 0x0200static const char hcd_name[] ="xhci_hcd" ;
@@ -508,9 +507,8 @@ static void xhci_pci_quirks(struct devicif (pdev->device ==0x9203 ) xhci->quirks |=XHCI_TRB_OVERFETCH ; } - -if (pdev->vendor ==PCI_DEVICE_ID_CADENCE && - pdev->device ==PCI_DEVICE_ID_CADENCE_SSP ) +if (pdev->vendor ==PCI_VENDOR_ID_CDNS && + pdev->device ==PCI_DEVICE_ID_CDNS_SSP ) xhci->quirks |=XHCI_CDNS_SCTX_QUIRK ;/* xHC spec requires PCI devices to support D3hot and D3cold */
Greg Kroah-Hartman
maintainerPATCH 619/877 usb: cdns3: rename hibernated argument of role->resume() to lost_power
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Théo Lebrun <[email protected]>
[ Upstream commit 0bde749c58c72405c54a1eabf6266a0273377226 ]
The cdns_role_driver->resume() callback takes a second boolean argument named hibernated in its implementations. This is mistaken; the only potential caller is:
int cdns_resume(struct cdns *cdns)
{
/* ... */
if (cdns->roles[cdns->role]->resume)
cdns->roles[cdns->role]->resume(cdns, cdns_power_is_lost(cdns));
return 0;
}The argument can be true in cases outside of return from hibernation. Reflect the true meaning by renaming both arguments to lost_power.
Stable-dep-of: eae6460f6173 ("usb: cdnsp: fix wakeup from S3 after controller context loss")
--- drivers/usb/cdns3/cdns3-gadget.c | 4 ++-- drivers/usb/cdns3/cdnsp-gadget.c | 2 +- drivers/usb/cdns3/core.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-)
drivers/usb/cdns3/cdns3-gadget.c +2 -2
@@ -3484,7 +3484,7 @@ __must_hold(&cdns->lock)return 0 ; } -static int cdns3_gadget_resume (struct cdns *cdns,bool hibernated) +static int cdns3_gadget_resume (struct cdns *cdns,bool lost_power) {struct cdns3_device *priv_dev = cdns->gadget_dev;
@@ -3492,7 +3492,7 @@ static int cdns3_gadget_resume(struct cdreturn 0 ;cdns3_gadget_config (priv_dev); -if (hibernated) +if (lost_power)writel (USB_CONF_DEVEN , &priv_dev->regs->usb_conf);return 0 ;
drivers/usb/cdns3/cdnsp-gadget.c +1 -1
@@ -2025,7 +2025,7 @@ static int cdnsp_gadget_suspend(struct creturn 0 ; } -static int cdnsp_gadget_resume (struct cdns *cdns,bool hibernated) +static int cdnsp_gadget_resume (struct cdns *cdns,bool lost_power) {struct cdnsp_device *pdev = cdns->gadget_dev;enum usb_device_speed max_speed;
drivers/usb/cdns3/core.h +1 -1
@@ -30,7 +30,7 @@ struct cdns_role_driver {int (*start)(struct cdns *cdns);void (*stop)(struct cdns *cdns);int (*suspend)(struct cdns *cdns,bool do_wakeup); -int (*resume)(struct cdns *cdns,bool hibernated); +int (*resume)(struct cdns *cdns,bool lost_power);const char *name;#define CDNS_ROLE_STATE_INACTIVE 0#define CDNS_ROLE_STATE_ACTIVE 1
Greg Kroah-Hartman
maintainerPATCH 620/877 usb: cdnsp: fix wakeup from S3 after controller context loss
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Pawel Laszczak <[email protected]>
[ Upstream commit eae6460f617382044c5afe5ef202f4d8b2c099b5 ]
CDNSP controller may lose its runtime register programming across S3 suspend/resume, depending on SoC power domain configuration. After resume the operational and interrupter registers may contain reset values, which prevents the gadget side from recovering correctly and breaks wakeup from S3.
Fix this by detecting whether the controller lost its register context after resume and handling both cases:
- If context was lost (CFG_3XPORT_U1_PIPE_CLK_GATE_EN set or power lost): reset the controller and reprogram the state required for normal operation, including the command ring, DCBAA pointer, doorbell base, event ring, ERST base/size and event ring dequeue pointer.
- If context was retained: restart the controller directly without reprogramming registers. Issue a wakeup if the link was in U3 before suspend.
Move the basic controller register programming out of the one-time memory initialization path and make it reusable from the resume path. Also separate ring allocation from ring initialization so that rings can be reinitialized without reallocating DMA memory.
Always perform the full suspend sequence regardless of the current link state. Previously, if the device was already in U3, the suspend callback returned early without stopping the controller, which could lead to commands being issued on a disabled slot during resume.
--- drivers/usb/cdns3/cdnsp-gadget.c | 110 +++++++++++++++++++++++++++++++++++++-- drivers/usb/cdns3/cdnsp-gadget.h | 1 drivers/usb/cdns3/cdnsp-mem.c | 98 ++++++++++++---------------------- 3 files changed, 142 insertions(+), 67 deletions(-)
drivers/usb/cdns3/cdnsp-gadget.c +106 -4
@@ -1819,6 +1819,82 @@ static void cdnsp_get_rev_cap(struct cdn readl(&pdev->rev_cap->tx_buff_size)); } +static void cdnsp_set_event_deq (struct cdnsp_device *pdev) +{ +dma_addr_t deq; +u64 temp; + + deq =cdnsp_trb_virt_to_dma (pdev->event_ring->deq_seg, + pdev->event_ring->dequeue); + +/* Update controller event ring dequeue pointer */ + temp =cdnsp_read_64 (&pdev->ir_set->erst_dequeue); + temp &=ERST_PTR_MASK ; + +/* +* Don't clear the EHB bit (which is RW1C) because +* there might be more events to service. +*/ + temp &= ~ERST_EHB ; + +cdnsp_write_64 (((u64 )deq & (u64 )~ERST_PTR_MASK ) | temp, + &pdev->ir_set->erst_dequeue); +} + +static void cdnsp_add_interrupter (struct cdnsp_device *pdev) +{ +u64 erst_base; +u32 erst_size; + +/* Set ERST count with the number of entries in the segment table. */ + erst_size =readl (&pdev->ir_set->erst_size); + erst_size &=ERST_SIZE_MASK ; + erst_size |=ERST_NUM_SEGS ; +writel (erst_size, &pdev->ir_set->erst_size); + +/* Set the segment table base address. */ + erst_base =cdnsp_read_64 (&pdev->ir_set->erst_base); + erst_base &=ERST_PTR_MASK ; + erst_base |= (pdev->erst.erst_dma_addr & (u64 )~ERST_PTR_MASK ); +cdnsp_write_64 (erst_base, &pdev->ir_set->erst_base); + +/* Set the event ring dequeue address. */ +cdnsp_set_event_deq (pdev); +} + +/* Set up basic CDNSP registers */ +static void cdnsp_init (struct cdnsp_device *pdev) +{ +unsigned int val; +u64 val_64; + + val =readl (&pdev->op_regs->config_reg); + val |= ((val & ~MAX_DEVS ) |CDNSP_DEV_MAX_SLOTS ) |CONFIG_U3E ; +writel (val, &pdev->op_regs->config_reg); + +/* Initialize the Command ring */ +cdnsp_ring_init (pdev, pdev->cmd_ring); + +/* Set the address in the Command Ring Control register */ + val_64 =cdnsp_read_64 (&pdev->op_regs->cmd_ring); + val_64 = (val_64 & (u64 )CMD_RING_RSVD_BITS ) | + (pdev->cmd_ring->first_seg->dma & (u64 )~CMD_RING_RSVD_BITS ) | + pdev->cmd_ring->cycle_state; +cdnsp_write_64 (val_64, &pdev->op_regs->cmd_ring); + +/* Set Device Context Base Address Array pointer */ +cdnsp_write_64 (pdev->dcbaa->dma, &pdev->op_regs->dcbaa_ptr); + +/* Set Doorbell array pointer */ + val =readl (&pdev->cap_regs->db_off); + val &=DBOFF_MASK ; + pdev->dba = (void __iomem *)pdev->cap_regs + val; + +/* Initialize the Primary interrupter */ +cdnsp_ring_init (pdev, pdev->event_ring); +cdnsp_add_interrupter (pdev); +} +static int cdnsp_gen_setup (struct cdnsp_device *pdev) {int ret;
@@ -1884,6 +1960,8 @@ static int cdnsp_gen_setup(struct cdnsp_if (ret)return ret; +cdnsp_init (pdev); +/* * Software workaround for U1: after transition * to U1 the controller starts gating clock, and in some cases,
@@ -2014,9 +2092,6 @@ static int cdnsp_gadget_suspend(struct cstruct cdnsp_device *pdev = cdns->gadget_dev;unsigned long flags; -if (pdev->link_state ==XDEV_U3 ) -return 0 ; -spin_lock_irqsave (&pdev->lock, flags);cdnsp_disconnect_gadget (pdev);cdnsp_stop (pdev);
@@ -2030,12 +2105,38 @@ static int cdnsp_gadget_resume(struct cdstruct cdnsp_device *pdev = cdns->gadget_dev;enum usb_device_speed max_speed;unsigned long flags; +bool context_lost; +u32 val;int ret;if (!pdev->gadget_driver)return 0 ;spin_lock_irqsave (&pdev->lock, flags); + val =readl (&pdev->port3x_regs->mode_2); + context_lost = !!(val &CFG_3XPORT_U1_PIPE_CLK_GATE_EN ) || lost_power; + +if (context_lost) { +cdnsp_halt (pdev); +cdnsp_set_apb_timeout_value (pdev); + +/* Reset the internal controller memory state and registers. */ + ret =cdnsp_reset (pdev); +if (ret) + goto unlock; + + val =readl (&pdev->port3x_regs->mode_2); + val &= ~CFG_3XPORT_U1_PIPE_CLK_GATE_EN ; +writel (val, &pdev->port3x_regs->mode_2); + +cdnsp_clear_cmd_ring (pdev); + +memset (pdev->event_ring->first_seg->trbs,0 , +sizeof (union cdnsp_trb ) * (TRBS_PER_SEGMENT )); + +cdnsp_init (pdev); + } + max_speed = pdev->gadget_driver->max_speed;/* Limit speed if necessary. */
@@ -2043,9 +2144,10 @@ static int cdnsp_gadget_resume(struct cd ret =cdnsp_run (pdev, max_speed); -if (pdev->link_state ==XDEV_U3 ) +if (!context_lost && pdev->link_state ==XDEV_U3 )__cdnsp_gadget_wakeup (pdev); +unlock:spin_unlock_irqrestore (&pdev->lock, flags);return ret;
drivers/usb/cdns3/cdnsp-gadget.h +1 -0
@@ -1509,6 +1509,7 @@ int cdnsp_endpoint_init(struct cdnsp_devint cdnsp_ring_expansion (struct cdnsp_device *pdev,struct cdnsp_ring *ring,unsigned int num_trbs,gfp_t flags); +void cdnsp_ring_init (struct cdnsp_device *pdev,struct cdnsp_ring *ring);struct cdnsp_ring *cdnsp_dma_to_transfer_ring (struct cdnsp_ep *ep,u64 address); int cdnsp_alloc_stream_info(struct cdnsp_device *pdev, struct cdnsp_ep *pep,
drivers/usb/cdns3/cdnsp-mem.c +35 -63
166 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 621/877 usb: storage: realtek_cr: fix use-after-free on disconnect
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 4ffee1aebb0c0ffcda9faffd17834ea9b00d42cc ]
realtek_cr_destructor() calls timer_delete() before the chip containing the timer is freed. The timer callback may still be running and can rearm itself, resulting in a use-after-free.
Use timer_shutdown_sync() to wait for the callback and prevent further rearming. Do this unconditionally because ss_en may be changed after the timer is armed.
Move timer_setup() into init_realtek_cr() so the timer is initialized before any failure path can invoke the destructor.
Found by static analysis.
--- drivers/usb/storage/realtek_cr.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/usb/storage/realtek_cr.c +4 -5
@@ -915,7 +915,6 @@ static int realtek_cr_autosuspend_setup( us->proto_handler = rts51x_invoke_transport; chip->timer_expires =0 ; -timer_setup (&chip->rts51x_suspend_timer, rts51x_suspend_timer_fn,0 );fw5895_init (us);/* enable autosuspend function of the usb device */
@@ -933,10 +932,7 @@ static void realtek_cr_destructor(void *return ;#ifdef CONFIG_REALTEK_AUTOPM -if (ss_en) { -del_timer (&chip->rts51x_suspend_timer); - chip->timer_expires =0 ; - } +timer_shutdown_sync (&chip->rts51x_suspend_timer);#endif kfree (chip->status); }
@@ -981,6 +977,9 @@ static int init_realtek_cr(struct us_dat us->extra = chip; us->extra_destructor = realtek_cr_destructor; +#ifdef CONFIG_REALTEK_AUTOPM +timer_setup (&chip->rts51x_suspend_timer, rts51x_suspend_timer_fn,0 ); +#endif us->max_lun = chip->max_lun =rts51x_get_max_lun (us); chip->us = us;
Greg Kroah-Hartman
maintainerPATCH 622/877 usb: gadget: f_mass_storage: fix null pointer dereference in fsg_common_set_num_buffers()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jeffin Philip <[email protected]>
[ Upstream commit 2c0f5ca48674a5b5f9fa4a9c3325aa48053af0bc ]
Previously fsg_num_buffers_validate() was removed as it was not necessary due to Kconfig setting the limits for n from 2 to 256 with default as 2. However, setting the page content in such a way that kstrtou8() reflects n value as either 0 or 1 bypasses these restrictions leading to a null pointer dereference if n is 0. Fix this by adding a check for n < 2 and returning -EINVAL if n is either 0 or 1 consistent with Kconfig logic.
--- drivers/usb/gadget/function/f_mass_storage.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/usb/gadget/function/f_mass_storage.c +3 -0
@@ -2748,6 +2748,9 @@ int fsg_common_set_num_buffers(struct fsstruct fsg_buffhd *bh, *buffhds;int i; +if (n <2 ) +return -EINVAL ; + buffhds =kcalloc (n,sizeof (*buffhds),GFP_KERNEL );if (!buffhds)return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 623/877 staging: rtl8723bs: fix spacing around operators
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vivek BalachandharTN <[email protected]>
[ Upstream commit 2038fe84b8bdf894b634f777096685e78e8f3774 ]
Fix several instances where operators lacked spaces around them. This improves readability and brings the driver closer to kernel coding-style guidelines. No functional change.
For this stable dependency, retain only the spacing change to the IE advance in rtw_restruct_wmm_ie(). This supplies the exact context needed by target commit 28a289beaf226 ("staging: rtl8723bs: fix OOB read in rtw_restruct_wmm_ie()"). Drop the unrelated operator-spacing hunks.
Keep the existing bounds-first WMM match condition from stable commit 4dd2d9cf563c5 (upstream a75281626fc8f); applying the older condition would undo its out-of-bounds-read fix. No functional change.
Stable-dep-of: 28a289beaf22 ("staging: rtl8723bs: fix OOB read in rtw_restruct_wmm_ie()")
--- drivers/staging/rtl8723bs/core/rtw_mlme.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/staging/rtl8723bs/core/rtw_mlme.c +1 -1
@@ -1950,7 +1950,7 @@ int rtw_restruct_wmm_ie(struct adapter *break ; } - i += (in_ie[i+1 ]+2 );/* to the next IE element */ + i += (in_ie[i +1 ] +2 );/* to the next IE element */ }return ielength;
Greg Kroah-Hartman
maintainerPATCH 624/877 staging: rtl8723bs: fix OOB read in rtw_restruct_wmm_ie()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Muhammad Bilal <[email protected]>
[ Upstream commit 28a289beaf226b30b1e6e7d7b1a2946fe2d6e852 ]
rtw_restruct_wmm_ie() scans in_ie for a WMM IE with:
while (i < in_len) {
...
if (i + 5 < in_len && in_ie[i] == 0xDD && ...) {
...
break;
}
i += (in_ie[i + 1] + 2); /* to the next IE element */
}When the "i + 5 < in_len" match check fails simply because i is within 5 bytes of the end of the buffer (i.e. no WMM IE was found near the tail of in_ie), execution falls through to
"i += (in_ie[i + 1] + 2)", which reads in_ie[i + 1]. If i == in_len
- 1 at that point, this is a 1-byte out-of-bounds read of an attacker-influenced IE buffer built from association/scan data.
Commit a75281626fc8f ("staging: rtl8723bs: fix potential out-of-bounds read in rtw_restruct_wmm_ie") added the "i + 5 < in_len" guard to the match condition itself, but did not add an equivalent guard before the fallthrough advance, so the same class of OOB read remained reachable through the non-matching path.
Add an explicit bounds check before advancing to the next IE.
--- drivers/staging/rtl8723bs/core/rtw_mlme.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/staging/rtl8723bs/core/rtw_mlme.c +3 -0
@@ -1950,6 +1950,9 @@ int rtw_restruct_wmm_ie(struct adapter *break ; } +if (i +1 >= in_len) +break ; + i += (in_ie[i +1 ] +2 );/* to the next IE element */ }
Greg Kroah-Hartman
maintainerPATCH 625/877 staging: sm750fb: fix mono image source stride mismatch in lynxfb_ops_imageblit()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Muhammad Bilal <[email protected]>
[ Upstream commit cc7cd2a9228175c975f62ad56ed7c767701cb4fa ]
sm750_hw_imageblit() advances its monochrome source pointer by src_delta per scanline, and computes the correct rounded-up stride internally as:
bytes_per_scan = (width + start_bit + 7) / 8;
Its only caller, lynxfb_ops_imageblit(), instead passed src_delta as image->width >> 3. For widths not a multiple of 8 this under-counted the stride, so the source pointer fell further behind the real per-scanline layout on every line, corrupting the rendered image.
Rather than just fixing the caller's calculation, remove src_delta as a parameter entirely and have sm750_hw_imageblit() advance by the bytes_per_scan it already computes for itself. There has only ever been one caller, and that caller was passing an out-of-sync derivative of the same width/start_bit values sm750_hw_imageblit() already has, so keeping stride as a separate parameter served no purpose beyond letting the two calculations drift apart, which is exactly what happened here.
Rounding up, rather than down, is the direction consistent with the rest of the fbdev core: struct fb_image mono bitmap data (the same image->data this driver receives) is walked elsewhere with byte strides derived from a ceiling division of width by 8. The generic mono bit iterator in drivers/video/fbdev/core/fb_imageblit.h advances scanlines with "iter->data += BITS_TO_BYTES(iter->width)", and BITS_TO_BYTES() (include/linux/bitops.h) is a ceiling division. sm750_hw_imageblit()'s own "(width + start_bit + 7) / 8" is that same ceiling division with an added start_bit offset, so the caller's ">> 3" (floor) was the one calculation out of step with how this data layout is handled everywhere else.
Found by code review of sm750_hw_imageblit()'s internal stride calculation against what its only caller was passing in, and confirmed with a clean -Werror build. I do not have this hardware, so this has not been exercised at runtime on real sm750 silicon.
--- drivers/staging/sm750fb/sm750.c | 2 +- drivers/staging/sm750fb/sm750.h | 2 +- drivers/staging/sm750fb/sm750_accel.c | 6 ++---- drivers/staging/sm750fb/sm750_accel.h | 4 +--- 4 files changed, 5 insertions(+), 9 deletions(-)
drivers/staging/sm750fb/sm750.c +1 -1
@@ -275,7 +275,7 @@ static void lynxfb_ops_imageblit(structspin_lock (&sm750_dev->slock); sm750_dev->accel.de_imageblit(&sm750_dev->accel, - image->data, image->width >> 3, 0, + image->data, 0, base, pitch, Bpp, image->dx, image->dy, image->width, image->height,
drivers/staging/sm750fb/sm750.h +1 -1
@@ -73,7 +73,7 @@ struct lynx_accel { u32 rop2);int (*de_imageblit)(struct lynx_accel *accel,const char *p_srcbuf, -u32 src_delta,u32 start_bit,u32 d_base,u32 d_pitch, +u32 start_bit,u32 d_base,u32 d_pitch,u32 byte_per_pixel,u32 dx,u32 dy,u32 width,u32 height,u32 f_color,u32 b_color,u32 rop2);
drivers/staging/sm750fb/sm750_accel.c +2 -4
@@ -300,8 +300,6 @@ static unsigned int deGetTransparency(st* sm750_hw_imageblit * @accel: Acceleration device data * @pSrcbuf: pointer to start of source buffer in system memory -* @srcDelta: Pitch value (in bytes) of the source buffer, +ive means top down -* and -ive mean button up * @startBit: Mono data can start at any bit in a byte, this value should be * 0 to 7 * @dBase: Address of destination: offset in frame buffer
@@ -316,7 +314,7 @@ static unsigned int deGetTransparency(st* @rop2: ROP value */ int sm750_hw_imageblit (struct lynx_accel *accel,const char *pSrcbuf, -u32 srcDelta,u32 startBit,u32 dBase,u32 dPitch, +u32 startBit,u32 dBase,u32 dPitch,u32 bytePerPixel,u32 dx,u32 dy,u32 width,u32 height,u32 fColor,u32 bColor,u32 rop2) {
@@ -405,7 +403,7 @@ int sm750_hw_imageblit(struct lynx_accelwrite_dpPort (accel, *(unsigned int *)ajRemain); } - pSrcbuf += srcDelta; + pSrcbuf += ulBytesPerScan; }return 0 ;
drivers/staging/sm750fb/sm750_accel.h +1 -3
@@ -220,8 +220,6 @@ int sm750_hw_copyarea(struct lynx_accel/** * sm750_hw_imageblit * @pSrcbuf: pointer to start of source buffer in system memory -* @srcDelta: Pitch value (in bytes) of the source buffer, +ive means top down -*>----- and -ive mean button up * @startBit: Mono data can start at any bit in a byte, this value should be *>----- 0 to 7 * @dBase: Address of destination: offset in frame buffer
@@ -236,7 +234,7 @@ int sm750_hw_copyarea(struct lynx_accel* @rop2: ROP value */ int sm750_hw_imageblit (struct lynx_accel *accel,const char *pSrcbuf, -u32 srcDelta,u32 startBit,u32 dBase,u32 dPitch, +u32 startBit,u32 dBase,u32 dPitch,u32 bytePerPixel,u32 dx,u32 dy,u32 width,u32 height,u32 fColor,u32 bColor,u32 rop2);
Greg Kroah-Hartman
maintainerPATCH 626/877 tracing/probes: Fix anon_stack check for unnamed bitfields in btf_find_struct_member
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: "Masami Hiramatsu (Google)" <[email protected]>
[ Upstream commit f36d94a20ca185bcadef3a10b980cd2cfd72d53a ]
btf_find_struct_member() traverses into nested anonymous structures and unions by pushing members with !member->name_off onto anon_stack. However, it does not consider the unnamed bitfields (e.g. int : 5 or unsigned int : 0) which also have member->name_off == 0.
If such an unnamed bitfield is pushed to anon_stack, the btf_find_struct_member() return an error even if there are other valid entries in anon_stack.
To fix this, only push unnamed struct/union members to anon_stack. Also move the btf_type_is_struct() check to the entry of this function because now it is sure only struct/union are pushed to anon_stack.
--- kernel/trace/trace_btf.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-)
kernel/trace/trace_btf.c +6 -6
@@ -74,24 +74,24 @@ const struct btf_member *btf_find_struct {struct btf_anon_stack *anon_stack;const struct btf_member *member; +const struct btf_type *mtype;u32 tid, cur_offset =0 ;const char *name;int i, top =0 ; +if (!btf_type_is_struct (type)) +return ERR_PTR (-EINVAL ); + anon_stack =kcalloc (BTF_ANON_STACK_MAX ,sizeof (*anon_stack),GFP_KERNEL );if (!anon_stack)return ERR_PTR (-ENOMEM ); retry: -if (!btf_type_is_struct (type)) { - member =ERR_PTR (-EINVAL ); - goto out; - } -for_each_member (i, type, member) {if (!member->name_off) {/* Anonymous union/struct: push it for later use */ -if (btf_type_skip_modifiers (btf, member->type, &tid) && + mtype =btf_type_skip_modifiers (btf, member->type, &tid); +if (mtype &&btf_type_is_struct (mtype) && top <BTF_ANON_STACK_MAX ) { anon_stack[top].tid = tid; anon_stack[top++].offset =
Greg Kroah-Hartman
maintainerPATCH 627/877 Documentation: tracing: Add documentation about eprobes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steven Rostedt <[email protected]>
[ Upstream commit 623526ba8984cafdffa0eba7ee424f2e40c8a219 ]
Eprobes was added back in 5.15, but was never documented. It became a "secret" interface even though it has been a topic of several presentations. For some reason, when eprobes was added, documenting it never became a priority, until now.
Stable-dep-of: 47e93045a2db ("tracing/probes: Fix BTF kflag check for anonymous struct member access")
--- Documentation/trace/eprobetrace.rst | 269 ++++++++++++++++++++++++++++++++++++ Documentation/trace/index.rst | 1 2 files changed, 270 insertions(+) create mode 100644 Documentation/trace/eprobetrace.rst
Documentation/trace/eprobetrace.rst new file +269 -0
@@ -0,0 +1,269 @@ +.. SPDX-License-Identifier: GPL-2.0 + +================================== +Eprobe - Event-based Probe Tracing +================================== + +:Author: Steven Rostedt <[email protected]> + +- Written for v6.17 + +Overview +======== + +Eprobes are dynamic events that are placed on existing events to either +dereference a field that is a pointer, or simply to limit what fields are +recorded in the trace event. + +Eprobes depend on kprobe events so to enable this feature, build your kernel +with CONFIG_EPROBE_EVENTS=y. + +Eprobes are created via the /sys/kernel/tracing/dynamic_events file. + +Synopsis of eprobe_events +------------------------- +:: + + e[:[EGRP/][EEVENT]] GRP.EVENT [FETCHARGS] : Set a probe + -:[EGRP/][EEVENT] : Clear a probe + + EGRP : Group name of the new event. If omitted, use "eprobes" for it. + EEVENT : Event name. If omitted, the event name is generated and will + be the same event name as the event it attached to. + GRP : Group name of the event to attach to. + EVENT : Event name of the event to attach to. + + FETCHARGS : Arguments. Each probe can have up to 128 args. + $FIELD : Fetch the value of the event field called FIELD. + @ADDR : Fetch memory at ADDR (ADDR should be in kernel) + @SYM[+|-offs] : Fetch memory at SYM +|- offs (SYM should be a data symbol) + $comm : Fetch current task comm. + +|-[u]OFFS(FETCHARG) : Fetch memory at FETCHARG +|- OFFS address.(\*3)(\*4) + \IMM : Store an immediate value to the argument. + NAME=FETCHARG : Set NAME as the argument name of FETCHARG. + FETCHARG:TYPE : Set TYPE as the type of FETCHARG. Currently, basic types + (u8/u16/u32/u64/s8/s16/s32/s64), hexadecimal types + (x8/x16/x32/x64), VFS layer common type(%pd/%pD), "char", + "string", "ustring", "symbol", "symstr" and "bitfield" are + supported. + +Types +----- +The FETCHARGS above is very similar to the kprobe events as described in +Documentation/trace/kprobetrace.rst. + +The difference between eprobes and kprobes FETCHARGS is that eprobes has a +$FIELD command that returns the content of the event field of the event +that is attached. Eprobes do not have access to registers, stacks and function +arguments that kprobes has. + +If a field argument is a pointer, it may be dereferenced just like a memory +address using the FETCHARGS syntax. + + +Attaching to dynamic events +--------------------------- + +Eprobes may attach to dynamic events as well as to normal events. It may +attach to a kprobe event, a synthetic event or a fprobe event. This is useful +if the type of a field needs to be changed. See Example 2 below. + +Usage examples +============== + +Example 1 +--------- + +The basic usage of eprobes is to limit the data that is being recorded into +the tracing buffer. For example, a common event to trace is the sched_switch +trace event. That has a format of:: + + field:unsigned short common_type; offset:0; size:2; signed:0; + field:unsigned char common_flags; offset:2; size:1; signed:0; + field:unsigned char common_preempt_count; offset:3; size:1; signed:0; + field:int common_pid; offset:4; size:4; signed:1; + + field:char prev_comm[16]; offset:8; size:16; signed:0; + field:pid_t prev_pid; offset:24; size:4; signed:1; + field:int prev_prio; offset:28; size:4; signed:1; + field:long prev_state; offset:32; size:8; signed:1; + field:char next_comm[16]; offset:40; size:16; signed:0; + field:pid_t next_pid; offset:56; size:4; signed:1; + field:int next_prio; offset:60; size:4; signed:1; + +The first four fields are common to all events and can not be limited. But the +rest of the event has 60 bytes of information. It records the names of the +previous and next tasks being scheduled out and in, as well as their pids and +priorities. It also records the state of the previous task. If only the pids +of the tasks are of interest, why waste the ring buffer with all the other +fields? + +An eprobe can limit what gets recorded. Note, it does not help in performance, +as all the fields are recorded in a temporary buffer to process the eprobe. +:: + + # echo 'e:sched/switch sched.sched_switch prev=$prev_pid:u32 next=$next_pid:u32' >> /sys/kernel/tracing/dynamic_events + # echo 1 > /sys/kernel/tracing/events/sched/switch/enable + # cat /sys/kernel/tracing/trace + + # tracer: nop + # + # entries-in-buffer/entries-written: 2721/2721 #P:8 + # + # _-----=> irqs-off/BH-disabled + # / _----=> need-resched + # | / _---=> hardirq/softirq + # || / _--=> preempt-depth + # ||| / _-=> migrate-disable + # |||| / delay + # TASK-PID CPU# ||||| TIMESTAMP FUNCTION + # | | | ||||| | | + sshd-session-1082 [004] d..4. 5041.239906: switch: (sched.sched_switch) prev=1082 next=0 + bash-1085 [001] d..4. 5041.240198: switch: (sched.sched_switch) prev=1085 next=141 + kworker/u34:5-141 [001] d..4. 5041.240259: switch: (sched.sched_switch) prev=141 next=1085 + <idle>-0 [004] d..4. 5041.240354: switch: (sched.sched_switch) prev=0 next=1082 + bash-1085 [001] d..4. 5041.240385: switch: (sched.sched_switch) prev=1085 next=141 + kworker/u34:5-141 [001] d..4. 5041.240410: switch: (sched.sched_switch) prev=141 next=1085 + bash-1085 [001] d..4. 5041.240478: switch: (sched.sched_switch) prev=1085 next=0 + sshd-session-1082 [004] d..4. 5041.240526: switch: (sched.sched_switch) prev=1082 next=0 + <idle>-0 [001] d..4. 5041.247524: switch: (sched.sched_switch) prev=0 next=90 + <idle>-0 [002] d..4. 5041.247545: switch: (sched.sched_switch) prev=0 next=16 + kworker/1:1-90 [001] d..4. 5041.247580: switch: (sched.sched_switch) prev=90 next=0 + rcu_sched-16 [002] d..4. 5041.247591: switch: (sched.sched_switch) prev=16 next=0 + <idle>-0 [002] d..4. 5041.257536: switch: (sched.sched_switch) prev=0 next=16 + rcu_sched-16 [002] d..4. 5041.257573: switch: (sched.sched_switch) prev=16 next=0 + +Note, without adding the "u32" after the prev_pid and next_pid, the values +would default showing in hexadecimal. + +Example 2 +--------- + +If a specific system call is to be recorded but the syscalls events are not +enabled, the raw_syscalls can still be used (syscalls are system call +events are not normal events, but are created from the raw_syscalls events +within the kernel). In order to trace the openat system call, one can create +an event probe on top of the raw_syscalls event: +:: + + # cd /sys/kernel/tracing + # cat events/raw_syscalls/sys_enter/format + name: sys_enter + ID: 395 + format: + field:unsigned short common_type; offset:0; size:2; signed:0; + field:unsigned char common_flags; offset:2; size:1; signed:0; + field:unsigned char common_preempt_count; offset:3; size:1; signed:0; + field:int common_pid; offset:4; size:4; signed:1; + + field:long id; offset:8; size:8; signed:1; + field:unsigned long args[6]; offset:16; size:48; signed:0; + + print fmt: "NR %ld (%lx, %lx, %lx, %lx, %lx, %lx)", REC->id, REC->args[0], REC->args[1], REC->args[2], REC->args[3], REC->args[4], REC->args[5] + +From the source code, the sys_openat() has: +:: + + int sys_openat(int dirfd, const char *path, int flags, mode_t mode) + { + return my_syscall4(__NR_openat, dirfd, path, flags, mode); + } + +The path is the second parameter, and that is what is wanted. +:: + + # echo 'e:openat raw_syscalls.sys_enter nr=$id filename=+8($args):ustring' >> dynamic_events + +This is being run on x86_64 where the word size is 8 bytes and the openat +system call __NR_openat is set at 257. +:: + + # echo 'nr == 257' > events/eprobes/openat/filter + +Now enable the event and look at the trace. +:: + + # echo 1 > events/eprobes/openat/enable + # cat trace + + # tracer: nop + # + # entries-in-buffer/entries-written: 4/4 #P:8 + # + # _-----=> irqs-off/BH-disabled + # / _----=> need-resched + # | / _---=> hardirq/softirq + # || / _--=> preempt-depth + # ||| / _-=> migrate-disable + # |||| / delay + # TASK-PID CPU# ||||| TIMESTAMP FUNCTION + # | | | ||||| | | + cat-1298 [003] ...2. 2060.875970: openat: (raw_syscalls.sys_enter) nr=0x101 filename=(fault) + cat-1298 [003] ...2. 2060.876197: openat: (raw_syscalls.sys_enter) nr=0x101 filename=(fault) + cat-1298 [003] ...2. 2060.879126: openat: (raw_syscalls.sys_enter) nr=0x101 filename=(fault) + cat-1298 [003] ...2. 2060.879639: openat: (raw_syscalls.sys_enter) nr=0x101 filename=(fault) + +The filename shows "(fault)". This is likely because the filename has not been +pulled into memory yet and currently trace events cannot fault in memory that +is not present. When an eprobe tries to read memory that has not been faulted +in yet, it will show the "(fault)" text. + +To get around this, as the kernel will likely pull in this filename and make +it present, attaching it to a synthetic event that can pass the address of the +filename from the entry of the event to the end of the event, this can be used +to show the filename when the system call returns. + +Remove the old eprobe:: + + # echo 1 > events/eprobes/openat/enable + # echo '-:openat' >> dynamic_events + +This time make an eprobe where the address of the filename is saved:: + + # echo 'e:openat_start raw_syscalls.sys_enter nr=$id filename=+8($args):x64' >> dynamic_events + +Create a synthetic event that passes the address of the filename to the +end of the event:: + + # echo 's:filename u64 file' >> dynamic_events + # echo 'hist:keys=common_pid:f=filename if nr == 257' > events/eprobes/openat_start/trigger + # echo 'hist:keys=common_pid:file=$f:onmatch(eprobes.openat_start).trace(filename,$file) if id == 257' > events/raw_syscalls/sys_exit/trigger + +Now that the address of the filename has been passed to the end of the +system call, create another eprobe to attach to the exit event to show the +string:: + + # echo 'e:openat synthetic.filename filename=+0($file):ustring' >> dynamic_events + # echo 1 > events/eprobes/openat/enable + # cat trace + + # tracer: nop + # + # entries-in-buffer/entries-written: 4/4 #P:8 + # + # _-----=> irqs-off/BH-disabled + # / _----=> need-resched + # | / _---=> hardirq/softirq + # || / _--=> preempt-depth + # ||| / _-=> migrate-disable + # |||| / delay + # TASK-PID CPU# ||||| TIMESTAMP FUNCTION + # | | | ||||| | | + cat-1331 [001] ...5. 2944.787977: openat: (synthetic.filename) filename="/etc/ld.so.cache" + cat-1331 [001] ...5. 2944.788480: openat: (synthetic.filename) filename="/lib/x86_64-linux-gnu/libc.so.6" + cat-1331 [001] ...5. 2944.793426: openat: (synthetic.filename) filename="/usr/lib/locale/locale-archive" + cat-1331 [001] ...5. 2944.831362: openat: (synthetic.filename) filename="trace" + +Example 3 +--------- + +If syscall trace events are available, the above would not need the first +eprobe, but it would still need the last one:: + + # echo 's:filename u64 file' >> dynamic_events + # echo 'hist:keys=common_pid:f=filename' > events/syscalls/sys_enter_openat/trigger + # echo 'hist:keys=common_pid:file=$f:onmatch(syscalls.sys_enter_openat).trace(filename,$file)' > events/syscalls/sys_exit_openat/trigger + # echo 'e:openat synthetic.filename filename=+0($file):ustring' >> dynamic_events + # echo 1 > events/eprobes/openat/enable + +And this would produce the same result as Example 2.
Documentation/trace/index.rst +1 -0
@@ -36,6 +36,7 @@ the Linux kernel. kprobes kprobetrace fprobetrace + eprobetrace fprobe ring-buffer-design
Greg Kroah-Hartman
maintainerPATCH 628/877 tracing/probes: Fix BTF kflag check for anonymous struct member access
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: "Masami Hiramatsu (Google)" <[email protected]>
[ Upstream commit 47e93045a2db80d24f5fef65adecc6b2b32efa23 ]
btf_find_struct_member() traverses into nested anonymous structures and unions to find a struct member. However, get_bitoffset_of_field() in trace_probe.c checked btf_type_kflag(type) using the outer parent type instead of the actual anonymous structure/union that directly contains the found member.
If the parent structure and anonymous structure have mismatched kflags (e.g., the parent has kflag=0 while the anonymous structure has kflag=1 because it contains bitfields), the bitfield size encoded in the upper 8 bits of member->offset is erroneously treated as part of the byte/bit offset, corrupting the resolved offset and failing to set last_bitsize. Similarly, btf_find_struct_member() pushed anonymous member offsets onto anon_stack without masking BTF_MEMBER_BIT_OFFSET() when kflag is set.
To fix this problem, update btf_find_struct_member() to return actual containing structure/union type via member_type, use appropriate __btf_member_bit_offset() to get bit offset, and use member_type for btf_type_kflag() in get_bitoffset_of_field().
--- kernel/trace/trace_btf.c | 19 +++++++++++-------- kernel/trace/trace_btf.h | 3 ++- kernel/trace/trace_probe.c | 5 +++-- 3 files changed, 16 insertions(+), 11 deletions(-)
kernel/trace/trace_btf.c +11 -8
@@ -61,16 +61,17 @@ struct btf_anon_stack {/* * Find a member of data structure/union by name and return it. -* Return NULL if not found, or -EINVAL if parameter is invalid. -* If the member is an member of anonymous union/structure, the offset -* of that anonymous union/structure is stored into @anon_offset. Caller -* can calculate the correct offset from the root data structure by -* adding anon_offset to the member's offset. +* Return NULL if not found, or ERR_PTR(-EINVAL) if parameter is invalid. +* If the member is a member of an anonymous union/structure, the bit offset +* of that anonymous union/structure is stored into @anon_offset. +* If @member_type is non-NULL, the actual containing structure/union type +* of the found member is stored into @member_type. */ const struct btf_member *btf_find_struct_member (struct btf *btf,const struct btf_type *type,const char *member_name, -u32 *anon_offset) +u32 *anon_offset, +const struct btf_type **member_type) {struct btf_anon_stack *anon_stack;const struct btf_member *member;
@@ -94,14 +95,16 @@ retry:if (mtype &&btf_type_is_struct (mtype) && top <BTF_ANON_STACK_MAX ) { anon_stack[top].tid = tid; - anon_stack[top++].offset = - cur_offset + member->offset; + anon_stack[top++].offset = cur_offset + +__btf_member_bit_offset (type, member); } }else { name =btf_name_by_offset (btf, member->name_off);if (name && !strcmp (member_name, name)) {if (anon_offset) *anon_offset = cur_offset; +if (member_type) + *member_type = type; goto out; } }
kernel/trace/trace_btf.h +2 -1
@@ -8,4 +8,5 @@ const struct btf_param *btf_get_func_parconst struct btf_member *btf_find_struct_member (struct btf *btf,const struct btf_type *type,const char *member_name, -u32 *anon_offset); +u32 *anon_offset, +const struct btf_type **member_type);
kernel/trace/trace_probe.c +3 -2
@@ -534,6 +534,7 @@ static int parse_btf_field(char *fieldna {struct fetch_insn *code = *pcode;const struct btf_member *field; +const struct btf_type *mtype;u32 bitoffs, anon_offs;char *next;int is_ptr;
@@ -562,7 +563,7 @@ static int parse_btf_field(char *fieldna anon_offs =0 ; field =btf_find_struct_member (ctx->btf, type, fieldname, - &anon_offs); + &anon_offs, &mtype);if (IS_ERR (field)) {trace_probe_log_err (ctx->offset,BAD_BTF_TID );return PTR_ERR (field);
@@ -575,7 +576,7 @@ static int parse_btf_field(char *fieldna bitoffs += anon_offs;/* Accumulate the bit-offsets of the dot-connected fields */ -if (btf_type_kflag (type)) { +if (btf_type_kflag (mtype)) { bitoffs +=BTF_MEMBER_BIT_OFFSET (field->offset); ctx->last_bitsize =BTF_MEMBER_BITFIELD_SIZE (field->offset); }else {
Greg Kroah-Hartman
maintainerPATCH 629/877 mm/secretmem: properly account locked pages
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 97d34aa65c29cca85e3e9050f4c936389b38a054 ]
secretmem accounts folios by treating memory as if it were mlock()'d and thus limited by the RLIMIT_MEMLOCK limit.
However the folios are unevictable and remain so until the inode is evicted, eliminating usual mlock() semantics - mapping folios then unmapping them does not clear their unevictable state, since it depends on AS_UNEVICTABLE, not PG_mlocked.
A user can therefore easily work around the RLIMIT_MEMLOCK limit - simply map then unmap and VmLck no longer counts the secretmem range. Worse, folios are not accounted in the process's RSS, meaning the OOM killer won't know to kill the process.
Repeatedly mapping/unmapping (or forking) can then result in the consumption of all available system memory with unevictable folios and cause system instability.
A secretmem fd can be passed between processes and over fork so a per-process limit simply does not make sense, so follow the precedent set by io_uring, perf, skbuff, iommufd and xdp by tracking the number of locked pages in user_struct->locked_vm.
Since the scope tracked is actually inode lifetime, the RLIMIT_MEMLOCK applies per-user not per-process, so it doesn't make sense to bypass for users with CAP_IPC_LOCK, therefore remove this bypass.
There is simply no reason to carry on marking the mapping as mlock()'d since it's misleading and the lifecycle is now correctly handled, so remove this too.
Note that secretmem does not support any form of truncation (including hole punching) and the folios are unreclaimable, so the folios need only be accounted on fault and unaccounted on inode destruction.
__secretmem_account_pages() is more or less a duplicate of the code that io_uring etc. use, but since this is a bug fix that needs backporting, defer any de-duplication efforts to a follow-up.
test_mlock_limit() asserts mlock_future_ok() on mmap(), however this has been removed, so remove the test altogether for the fix. A new test will be sent separately for upstream.
--- include/linux/sched/user.h | 3 mm/secretmem.c | 117 +++++++++++++++++++++++++++--- tools/testing/selftests/mm/memfd_secret.c | 30 ------- 3 files changed, 110 insertions(+), 40 deletions(-)
include/linux/sched/user.h +2 -1
@@ -25,7 +25,8 @@ struct user_struct {#if defined(CONFIG_PERF_EVENTS ) || defined(CONFIG_BPF_SYSCALL ) || \ defined(CONFIG_NET ) || defined(CONFIG_IO_URING ) || \ - defined(CONFIG_VFIO_PCI_ZDEV_KVM ) ||IS_ENABLED (CONFIG_IOMMUFD ) + defined(CONFIG_VFIO_PCI_ZDEV_KVM ) ||IS_ENABLED (CONFIG_IOMMUFD ) || \ + defined(CONFIG_SECRETMEM )atomic_long_t locked_vm;#endif #ifdef CONFIG_WATCH_QUEUE
mm/secretmem.c +107 -10
191 lines not on this page · raw message
tools/testing/selftests/mm/memfd_secret.c +1 -29
@@ -57,33 +57,6 @@ static void test_file_apis(int fd)pass ("file IO is blocked as expected\n" ); } -static void test_mlock_limit (int fd) -{ -size_t len; -char *mem; - - len = mlock_limit_cur; -if (len % page_size !=0 ) - len = (len/page_size) * page_size; - - mem =mmap (NULL , len, prot, mode, fd,0 ); -if (mem ==MAP_FAILED ) { -fail ("unable to mmap secret memory\n" ); -return ; - } -munmap (mem, len); - - len = mlock_limit_max *2 ; - mem =mmap (NULL , len, prot, mode, fd,0 ); -if (mem !=MAP_FAILED ) { -fail ("unexpected mlock limit violation\n" ); -munmap (mem, len); -return ; - } - -pass ("mlock limit is respected\n" ); -} -static void test_vmsplice (int fd,const char *desc) {ssize_t transferred;
@@ -297,7 +270,7 @@ static void prepare(void) strerror(errno)); } -#define NUM_TESTS 6 +#define NUM_TESTS 5int main (int argc,char *argv[]) {
@@ -319,7 +292,6 @@ int main(int argc, char *argv[])if (ftruncate (fd, page_size))ksft_exit_fail_msg ("ftruncate failed: %s\n" ,strerror (errno)); -test_mlock_limit (fd);test_file_apis (fd);/* * We have to run the first vmsplice test before any secretmem page was
Greg Kroah-Hartman
maintainerPATCH 630/877 tracing: Clean up use of trace_create_maxlat_file()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steven Rostedt <[email protected]>
[ Upstream commit ba73713da50e5c24499ca8941171593466ea34f7 ]
In trace.c, the function trace_create_maxlat_file() is defined behind the
#ifdef CONFIG_TRACER_MAX_TRACE block. The #else part defines it as:
#define trace_create_maxlat_file(tr, d_tracer) \
trace_create_file("tracing_max_latency", TRACE_MODE_WRITE, \
d_tracer, tr, &tracing_max_lat_fops)But the one place that it it used has:
#ifdef CONFIG_TRACER_MAX_TRACE trace_create_maxlat_file(tr, d_tracer);
#endif
Which is pointless and also wrong!
It only gets created when both CONFIG_TRACE_MAX_TRACE and CONFIG_FS_NOTIFY is defined, but the file itself should not be dependent on CONFIG_FS_NOTIFY. Always create that file when TRACE_MAX_TRACE is defined regardless if FS_NOTIFY is or is not.
Stable-dep-of: f2951ebd15c3 ("tracing: Take trace_array reference when opening options file")
--- kernel/trace/trace.c | 38 ++++++++++++++++---------------------- 1 file changed, 16 insertions(+), 22 deletions(-)
kernel/trace/trace.c +16 -22
@@ -1830,10 +1830,7 @@ static ssize_t trace_seq_to_buffer(strucunsigned long __read_mostly tracing_thresh;#ifdef CONFIG_TRACER_MAX_TRACE -static const struct file_operations tracing_max_lat_fops; -#ifdef LATENCY_FS_NOTIFY -static struct workqueue_struct *fsnotify_wq;static void latency_fsnotify_workfn (struct work_struct *work)
@@ -1850,17 +1847,6 @@ static void latency_fsnotify_workfn_irq(queue_work (fsnotify_wq, &tr->fsnotify_work); } -static void trace_create_maxlat_file (struct trace_array *tr, -struct dentry *d_tracer) -{ -INIT_WORK (&tr->fsnotify_work, latency_fsnotify_workfn); -init_irq_work (&tr->fsnotify_irqwork, latency_fsnotify_workfn_irq); - tr->d_max_latency =trace_create_file ("tracing_max_latency" , -TRACE_MODE_WRITE , - d_tracer, tr, - &tracing_max_lat_fops); -} -__init static int latency_fsnotify_init (void ) { fsnotify_wq = alloc_workqueue("tr_max_lat_wq",
@@ -1885,14 +1871,22 @@ void latency_fsnotify(struct trace_array*/ irq_work_queue(&tr->fsnotify_irqwork); } +#endif /* !LATENCY_FS_NOTIFY */ -#else /* !LATENCY_FS_NOTIFY */ - -#define trace_create_maxlat_file (tr, d_tracer) \ - trace_create_file("tracing_max_latency", TRACE_MODE_WRITE, \ - d_tracer, tr, &tracing_max_lat_fops) +static const struct file_operations tracing_max_lat_fops; +static void trace_create_maxlat_file (struct trace_array *tr, +struct dentry *d_tracer) +{ +#ifdef LATENCY_FS_NOTIFY +INIT_WORK (&tr->fsnotify_work, latency_fsnotify_workfn); +init_irq_work (&tr->fsnotify_irqwork, latency_fsnotify_workfn_irq);#endif + tr->d_max_latency =trace_create_file ("tracing_max_latency" , +TRACE_MODE_WRITE , + d_tracer, tr, + &tracing_max_lat_fops); +}/* * Copy the new maximum trace into the separate maximum-trace
@@ -2027,7 +2021,9 @@ update_max_tr_single(struct trace_array__update_max_tr (tr, tsk, cpu);arch_spin_unlock (&tr->max_lock); } - +#else /* !CONFIG_TRACER_MAX_TRACE */ +static inline void trace_create_maxlat_file (struct trace_array *tr, +struct dentry *d_tracer) { }#endif /* CONFIG_TRACER_MAX_TRACE */ struct pipe_wait {
@@ -9720,9 +9716,7 @@ init_tracer_tracefs(struct trace_array *create_trace_options_dir (tr); -#ifdef CONFIG_TRACER_MAX_TRACE trace_create_maxlat_file (tr, d_tracer); -#endif if (ftrace_create_function_files (tr, d_tracer))MEM_FAIL (1 ,"Could not allocate function filter files" );
Greg Kroah-Hartman
maintainerPATCH 631/877 tracing: Take trace_array reference when opening options file
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steven Rostedt <[email protected]>
[ Upstream commit f2951ebd15c36a1ea4820a7f0cbb0b5f1c028b73 ]
The options files do not take the trace_array reference for the options they represent. This could cause a use-after-free kernel crash if one of these files is opened by one task and another task removes the instance that the option is for. Because it doesn't take a reference upon opening, it will not stop the removal which will free the options descriptor that is being used.
As the options are somewhat dynamic in their creation at boot up, each file represents a flag in the trace_array. The trace_array has an array of indexes to represent each of these flags that is stored in the trace_flags_index array. The address of the index array element is used to pass to the inode->i_private pointer. Then that element is read which holds the index (which represents the flag) and then the index is used to calculate the trace_array descriptor from its trace_flags_index array.
One issue is that the index element can not be referenced until the trace_array's reference is taken. To handle this, create a new helper function called: trace_array_options_get() that will iterate all the existing trace_arrays in the ftrace_trace_arrays list (under the trace_types_lock), and compare the passed in address of the index element with the entire array of the trace_array's trace_flags_index array. If it matches, then up the corresponding trace_array's reference and return.
--- kernel/trace/trace.c | 69 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 4 deletions(-)
kernel/trace/trace.c +65 -4
@@ -8851,11 +8851,72 @@ trace_options_core_write(struct file *fireturn cnt; } +/* +* The tr_index is the address of a trace_array->trace_flags_index[] +* element that holds the index of the trace flag. But since the +* trace_array reference has not been taken yet, it cannot be referenced +* as it could have been freed by a rmdir of the instance the trace_array +* represents. +* +* Search the list of trace_arrays and compare the tr_index to the +* address of the entire trace_array trace_flags_index array for each +* trace_array in the list. If one is matched, then take the reference +* and return it. If not, the trace_array no longer exits. +*/ +static int trace_array_options_get (void *tr_index) +{ +struct trace_array *tr; +int ret; + + ret =security_locked_down (LOCKDOWN_TRACEFS ); +if (ret) +return ret; + +if (tracing_disabled) +return -ENODEV ; + +guard (mutex)(&trace_types_lock); +list_for_each_entry (tr, &ftrace_trace_arrays, list) { +if (tr_index >= (void *)&tr->trace_flags_index[0 ] && + tr_index < (void *)&tr->trace_flags_index[TRACE_FLAGS_MAX_SIZE ]) { + tr->ref++; +return 0 ; + } + } +return -ENODEV ; +} + +static int trace_options_open (struct inode *inode,struct file *filp) +{ +void *tr_index = inode->i_private; + +if (trace_array_options_get (tr_index) <0 ) +return -ENODEV ; + + filp->private_data = tr_index; + +return 0 ; +} + +static int trace_options_release (struct inode *inode,struct file *filp) +{ +void *tr_index = filp->private_data; +struct trace_array *tr; +unsigned int index; + +get_tr_index (tr_index, &tr, &index); + +trace_array_put (tr); + +return 0 ; +} +static const struct file_operations trace_options_core_fops = { - .open = tracing_open_generic, - .read = trace_options_core_read, - .write = trace_options_core_write, - .llseek = generic_file_llseek, + .open = trace_options_open, + .read = trace_options_core_read, + .write = trace_options_core_write, + .llseek = generic_file_llseek, + .release = trace_options_release, }; struct dentry *trace_create_file(const char *name,
Greg Kroah-Hartman
maintainerPATCH 632/877 ftrace: Take trace_array reference before accessing its ftrace_ops
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steven Rostedt <[email protected]>
[ Upstream commit 9100191e5acb2e5ea2313f436667bb5fce129f47 ]
The trace instance files set_ftrace_filter and set_ftrace_notrace was updated to work with specific trace instances (trace_arrays). The issue is that when these files are opened, there is a small race window where it will use the ftrace_ops from the inode->private pointer to get a reference to the trace_array and then take its reference. The problem is that the ftrace_ops itself could be freed. If the rmdir on the instance happens at the same time the set_ftrace_filter file is opened, the rmdir could have also freed the ftrace_ops and referencing it will cause a use-after-free bug and crash the kernel.
Instead, pass in the trace_array as the file private data (NULL for the top level instance), and then pass both the trace_array and the ftrace_ops to the ftrace_regex_open() function. If the trace_array is NULL, then it just uses the ftrace_ops without the need to take its reference (like normal). If the ftrace_ops is NULL, that is only the case for the top level instance and the global_ops can be used.
This allows the trace_array to have its reference incremented before touching the ftrace_ops that could also be freed when the instance is.
--- include/linux/ftrace.h | 5 ++- kernel/trace/ftrace.c | 57 ++++++++++++++++++++++++++--------------- kernel/trace/trace.h | 4 +- kernel/trace/trace_functions.c | 2 - kernel/trace/trace_stack.c | 2 - 5 files changed, 44 insertions(+), 26 deletions(-)
include/linux/ftrace.h +3 -2
@@ -759,8 +759,9 @@ unsigned long ftrace_get_addr_new(structunsigned long ftrace_get_addr_curr (struct dyn_ftrace *rec);extern ftrace_func_t ftrace_trace_function; +struct trace_array ; -int ftrace_regex_open (struct ftrace_ops *ops,int flag, +int ftrace_regex_open (struct trace_array *tr,struct ftrace_ops *ops,int flag,struct inode *inode,struct file *file);ssize_t ftrace_filter_write (struct file *file,const char __user *ubuf,size_t cnt,loff_t *ppos);
@@ -970,7 +971,7 @@ static inline unsigned long ftrace_locat* have them defined when ftrace is not enabled, but these * functions may still be called. Use a macro instead of inline. */ -#define ftrace_regex_open (ops, flag, inod, file) ({ -ENODEV; }) +#define ftrace_regex_open (tr, ops, flag, inode, file) ({ -ENODEV; })#define ftrace_set_early_filter (ops, buf, enable) do { } while (0)#define ftrace_set_filter_ip (ops, ip, remove, reset) ({ -ENODEV; })#define ftrace_set_filter_ips (ops, ips, cnt, remove, reset) ({ -ENODEV; })
kernel/trace/ftrace.c +37 -20
120 lines not on this page · raw message
kernel/trace/trace.h +2 -2
@@ -1191,7 +1191,7 @@ extern void clear_ftrace_function_probesint register_ftrace_command (struct ftrace_func_command *cmd);int unregister_ftrace_command (struct ftrace_func_command *cmd); -void ftrace_create_filter_files (struct ftrace_ops *ops, +void ftrace_create_filter_files (struct trace_array *tr,struct dentry *parent);void ftrace_destroy_filter_files (struct ftrace_ops *ops);
@@ -1214,11 +1214,11 @@ static inline void clear_ftrace_function { } +#define ftrace_create_filter_files (tr, parent) do { } while (0)/* * The ops parameter passed in is usually undefined. * This must be a macro. */ -#define ftrace_create_filter_files (ops, parent) do { } while (0)#define ftrace_destroy_filter_files (ops) do { } while (0)#endif /* CONFIG_FUNCTION_TRACER && CONFIG_DYNAMIC_FTRACE */
kernel/trace/trace_functions.c +1 -1
@@ -97,7 +97,7 @@ int ftrace_create_function_files(structreturn ret; } -ftrace_create_filter_files (tr->ops, parent); +ftrace_create_filter_files (tr, parent);return 0 ; }
kernel/trace/trace_stack.c +1 -1
@@ -499,7 +499,7 @@ stack_trace_filter_open(struct inode *instruct ftrace_ops *ops = inode->i_private;/* Checks for tracefs lockdown */ -return ftrace_regex_open (ops,FTRACE_ITER_FILTER , +return ftrace_regex_open (NULL , ops,FTRACE_ITER_FILTER , inode, file); }
Greg Kroah-Hartman
maintainerPATCH 633/877 dma-buf: dma-heap: dont publish fd before copy_to_user() succeeds
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baineng Shou <[email protected]>
[ Upstream commit 30d0aff2c65a277135cfd8ea28fa1ee75e0ea4e0 ]
DMA_HEAP_IOCTL_ALLOC allocates a dma-buf and installs an fd into the caller's fd table via dma_buf_fd() -> fd_install() before dma_heap_ioctl() copies the result back to userspace. If the trailing copy_to_user() fails, userspace never learns the fd number, but the fd (and the underlying dma-buf reference) are already visible to other threads in the same process and are leaked for the lifetime of the process.
The obvious "close it on the failure path" fix is unsafe: once fd_install() has run, another thread can already dup() the fd, send it via SCM_RIGHTS, or close() it and let its number be reused, so a subsequent close_fd() from the ioctl path can operate on an unrelated file. This was pointed out by Christian König on v1 [1].
Restructure the allocation path so that fd_install() is the last, unfailable step of a successful ioctl:
1. heap->ops->allocate() creates the dma_buf.
2. get_unused_fd_flags() reserves an fd number in the caller's
fd table without publishing it, so no other thread can observe it.
3. copy_to_user() delivers the fd number to userspace;
on failure the fd is returned with put_unused_fd() and the dma_buf reference is dropped with dma_buf_put(), leaving no user- visible state behind.
4. dma_buf_fd_install() publishes the fd and emits the
trace_dma_buf_fd tracepoint -- from here on the ioctl cannot fail.
A new dma_buf_fd_install() helper is introduced in dma-buf.c to wrap fd_install() together with the DMA_BUF_TRACE() call, preserving the export tracing that dma_buf_fd() provides. dma_heap_ioctl_allocate() is refactored to return the struct dma_buf * directly (returning ERR_PTR on failure) so the caller holds the dmabuf reference across steps 3 and 4.
The failure at step 3 is easily reachable from userspace: pass a struct dma_heap_allocation_data that lives in a page whose protection is flipped to PROT_READ between copy_from_user() and copy_to_user() (e.g. via mprotect()). Before this change each such ioctl leaks one dmabuf fd; after it, the fd table is unchanged on failure and only /dev/dma_heap/<name> remains open.
No UAPI or heap-driver interface change.
[1] https://lore.kernel.org/dri-devel/[email protected]/
--- drivers/dma-buf/dma-heap.c | 80 ++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 40 deletions(-)
drivers/dma-buf/dma-heap.c +40 -40
@@ -48,33 +48,6 @@ static dev_t dma_heap_devt;static struct class *dma_heap_class;static DEFINE_XARRAY_ALLOC (dma_heap_minors); -static int dma_heap_buffer_alloc (struct dma_heap *heap,size_t len, -u32 fd_flags, -u64 heap_flags) -{ -struct dma_buf *dmabuf; -int fd; - -/* -* Allocations from all heaps have to begin -* and end on page boundaries. -*/ - len =PAGE_ALIGN (len); -if (!len) -return -EINVAL ; - - dmabuf = heap->ops->allocate (heap, len, fd_flags, heap_flags); -if (IS_ERR (dmabuf)) -return PTR_ERR (dmabuf); - - fd =dma_buf_fd (dmabuf, fd_flags); -if (fd <0 ) { -dma_buf_put (dmabuf); -/* just return, as put will call release and that will free */ - } -return fd; -} -static int dma_heap_open (struct inode *inode,struct file *file) {struct dma_heap *heap;
@@ -92,30 +65,42 @@ static int dma_heap_open(struct inode *ireturn 0 ; } -static long dma_heap_ioctl_allocate (struct file *file,void *data) +static struct dma_buf *dma_heap_ioctl_allocate (struct file *file,void *data) {struct dma_heap_allocation_data *heap_allocation = data;struct dma_heap *heap = file->private_data; +struct dma_buf *dmabuf;int fd; +size_t len;if (heap_allocation->fd) -return -EINVAL ; +return ERR_PTR (-EINVAL );if (heap_allocation->fd_flags & ~DMA_HEAP_VALID_FD_FLAGS ) -return -EINVAL ; +return ERR_PTR (-EINVAL );if (heap_allocation->heap_flags & ~DMA_HEAP_VALID_HEAP_FLAGS ) -return -EINVAL ; +return ERR_PTR (-EINVAL ); + + len =PAGE_ALIGN (heap_allocation->len); +if (!len) +return ERR_PTR (-EINVAL ); - fd =dma_heap_buffer_alloc (heap, heap_allocation->len, - heap_allocation->fd_flags, - heap_allocation->heap_flags); -if (fd <0 ) -return fd; + dmabuf = heap->ops->allocate (heap, len, heap_allocation->fd_flags, + heap_allocation->heap_flags); + +if (IS_ERR (dmabuf)) +return dmabuf; + + fd =get_unused_fd_flags (heap_allocation->fd_flags); +if (fd <0 ) { +dma_buf_put (dmabuf); +return ERR_PTR (fd); + } heap_allocation->fd = fd; -return 0 ; +return dmabuf; }static unsigned int dma_heap_ioctl_cmds[] = {
@@ -131,6 +116,8 @@ static long dma_heap_ioctl(struct file *unsigned int in_size, out_size, drv_size, ksize;int nr =_IOC_NR (ucmd);int ret =0 ; +int fd; +struct dma_buf *dmabuf;if (nr >=ARRAY_SIZE (dma_heap_ioctl_cmds))return -EINVAL ;
@@ -167,15 +154,28 @@ static long dma_heap_ioctl(struct file *switch (kcmd) {case DMA_HEAP_IOCTL_ALLOC : - ret =dma_heap_ioctl_allocate (file, kdata); + dmabuf =dma_heap_ioctl_allocate (file, kdata); + +if (IS_ERR (dmabuf)) { + ret =PTR_ERR (dmabuf); +break ; + } + + fd = ((struct dma_heap_allocation_data *)kdata)->fd; +if (copy_to_user ((void __user *)arg, kdata, out_size) !=0 ) { +put_unused_fd (fd); +dma_buf_put (dmabuf); + ret = -EFAULT ; + }else { +fd_install (fd, dmabuf->file); + } +break ;default : ret = -ENOTTY ; goto err; } -if (copy_to_user ((void __user *)arg, kdata, out_size) !=0 ) - ret = -EFAULT ; err:if (kdata != stack_kdata)kfree (kdata);
Greg Kroah-Hartman
maintainerPATCH 634/877 compiler_types: Move lock checking attributes to compiler-context-analysis.h
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marco Elver <[email protected]>
[ Upstream commit de15fecae44df8254fa597bad7eb3680a8b1c10c ]
The conditional definition of lock checking macros and attributes is about to become more complex. Factor them out into their own header for better readability, and to make it obvious which features are supported by which mode (currently only Sparse). This is the first step towards generalizing towards "context analysis".
No functional change intended.
Stable-dep-of: 912edebe8501 ("futex: Provide rt_mutex_.*_schedule() equivalents for futex scheduling")
--- include/linux/compiler-context-analysis.h | 32 ++++++++++++++++++++++++++++++ include/linux/compiler_types.h | 18 +--------------- 2 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 include/linux/compiler-context-analysis.h
include/linux/compiler-context-analysis.h new file +32 -0
@@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* +* Macros and attributes for compiler-based static context analysis. +*/ + +#ifndef _LINUX_COMPILER_CONTEXT_ANALYSIS_H +#define _LINUX_COMPILER_CONTEXT_ANALYSIS_H + +#ifdef __CHECKER__ + +/* Sparse context/lock checking support. */ +# define __must_hold (x) __attribute__((context(x,1,1))) +# define __acquires (x) __attribute__((context(x,0,1))) +# define __cond_acquires (x) __attribute__((context(x,0,-1))) +# define __releases (x) __attribute__((context(x,1,0))) +# define __acquire (x) __context__(x,1) +# define __release (x) __context__(x,-1) +# define __cond_lock (x, c) ((c) ? ({ __acquire(x); 1; }) : 0) + +#else /* !__CHECKER__ */ + +# define __must_hold (x) +# define __acquires (x) +# define __cond_acquires (x) +# define __releases (x) +# define __acquire (x) (void)0 +# define __release (x) (void)0 +# define __cond_lock (x, c) (c) + +#endif /* __CHECKER__ */ + +#endif /* _LINUX_COMPILER_CONTEXT_ANALYSIS_H */
include/linux/compiler_types.h +2 -16
@@ -37,6 +37,8 @@# define BTF_TYPE_TAG (value)/* nothing */ #endif +#include <linux/compiler-context-analysis.h> +/* sparse defines __CHECKER__; see Documentation/dev-tools/sparse.rst */ #ifdef __CHECKER__/* address spaces */
@@ -47,14 +49,6 @@# define __rcu __attribute__((noderef, address_space(__rcu)))static inline void __chk_user_ptr (const volatile void __user *ptr) { }static inline void __chk_io_ptr (const volatile void __iomem *ptr) { } -/* context/locking */ -# define __must_hold (x) __attribute__((context(x,1,1))) -# define __acquires (x) __attribute__((context(x,0,1))) -# define __cond_acquires (x) __attribute__((context(x,0,-1))) -# define __releases (x) __attribute__((context(x,1,0))) -# define __acquire (x) __context__(x,1) -# define __release (x) __context__(x,-1) -# define __cond_lock (x,c) ((c) ? ({ __acquire(x); 1; }) : 0)/* other */ # define __force __attribute__((force))# define __nocast __attribute__((nocast))
@@ -75,14 +69,6 @@ static inline void __chk_io_ptr(const vo# define __chk_user_ptr (x) (void)0# define __chk_io_ptr (x) (void)0 -/* context/locking */ -# define __must_hold (x) -# define __acquires (x) -# define __cond_acquires (x) -# define __releases (x) -# define __acquire (x) (void)0 -# define __release (x) (void)0 -# define __cond_lock (x,c) (c)/* other */ # define __force# define __nocast
Greg Kroah-Hartman
maintainerPATCH 635/877 futex: Provide rt_mutex_.*_schedule() equivalents for futex scheduling
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sebastian Andrzej Siewior <[email protected]>
[ Upstream commit 912edebe8501a36c6bedcef03bd238ab90a7e060 ]
There is rt_mutex_{pre|post}_schedule() around rt_mutex_wait_proxy_lock() to ensure that sched_submit_work()/ sched_update_worker() is invoked before we schedule out and block on rt_mutex while waiting for it become available.
The reason is that blocking on rt_mutex assigns a pi_waiter for the PI chain and sched_submit_work() will also assign a pi_waiter if it blocks on lock but a this point we already have a waiter assigned. We can't skip sched_submit_work() entirely because I/O relies on the fact that I/O queue is flushed while it blocks on a sleeping lock. Therefore sched_submit_work() is moved before we block on the lock.
Sleeping lock in this context means mutex or rw_semaphore not spinlock_t on PREEMPT_RT. Because the mutex abstraction on PREEMPT_RT uses the same abstraction as the futex proxy lock, the futex code ended up using rt_mutex_{pre|post}_schedule(), too.
Using it is/ was just to keep the task_struct::sched_rt_mutex assertion happy. Futex proxy lock is used only in the syscall context of a task. At this point it never got any I/O that needs to be flushed and it can't be a workqueue that needs to notify that it will be scheduled out. Therefore sched_submit_work() does nothing here.
By mistake futex_wait_requeue_pi() -> rt_mutex_wait_proxy_lock() did not get the rt_mutex_{pre|post}_schedule() annotation. This was not noticed because in this callchain the lock is (usually) not contended and so rt_mutex_slowlock_block() does not schedule, triggering the assert.
Adding rt_mutex_pre_schedule() here looks wrong (as noted by PeterZ) because at this point there is a pi_waiter recorded and invoking sched_submit_work() with a possible lock contention would be wrong.
Add rt_mutex_futex_{pre|post}_schedule() which toggles the sched_rt_mutex assert and does not involve sched_submit_work(). Add asserts here to ensure that sched_submit_work() would do nothing. Use it only in futex proxy lock case which is rt_mutex_wait_proxy_lock(). Remove it from futex_lock_pi().
--- include/linux/sched/rt.h | 2 ++ kernel/futex/pi.c | 10 ---------- kernel/locking/rtmutex_api.c | 2 ++ kernel/sched/core.c | 16 ++++++++++++++++ 4 files changed, 20 insertions(+), 10 deletions(-)
include/linux/sched/rt.h +2 -0
@@ -52,8 +52,10 @@ static inline bool rt_or_dl_task_policy(#ifdef CONFIG_RT_MUTEXES extern void rt_mutex_pre_schedule (void ); +extern void rt_mutex_futex_pre_schedule (void );extern void rt_mutex_schedule (void );extern void rt_mutex_post_schedule (void ); +extern void rt_mutex_futex_post_schedule (void );/* * Must hold either p->pi_lock or task_rq(p)->lock.
kernel/futex/pi.c +0 -10
@@ -992,12 +992,6 @@ retry_private: goto no_block; } -/* -* Must be done before we enqueue the waiter, here is unfortunately -* under the hb lock, but that *should* work because it does nothing. -*/ -rt_mutex_pre_schedule (); -rt_mutex_init_waiter (&rt_waiter);/*
@@ -1065,10 +1059,6 @@ cleanup:* the */ spin_lock (q.lock_ptr); -/* -* Waiter is unqueued. -*/ -rt_mutex_post_schedule (); no_block:/* * Fixup the pi_state owner and possibly acquire the lock if we
kernel/locking/rtmutex_api.c +2 -0
@@ -380,6 +380,7 @@ int __sched rt_mutex_wait_proxy_lock(str {int ret; +rt_mutex_futex_pre_schedule ();raw_spin_lock_irq (&lock->wait_lock);/* sleep on the mutex */ set_current_state (TASK_INTERRUPTIBLE );
@@ -390,6 +391,7 @@ int __sched rt_mutex_wait_proxy_lock(str*/ fixup_rt_mutex_waiters (lock, true);raw_spin_unlock_irq (&lock->wait_lock); +rt_mutex_futex_post_schedule ();return ret; }
kernel/sched/core.c +16 -0
@@ -7117,6 +7117,17 @@ void rt_mutex_pre_schedule(void)sched_submit_work (current); } +/* +* Used within the futex syscall context, skips sched_submit_work() because none +* its work will be done. Asserts ensure that it is indeed the case. +*/ +void rt_mutex_futex_pre_schedule (void ) +{ +lockdep_assert (!(current->flags & (PF_WQ_WORKER |PF_IO_WORKER ))); +lockdep_assert (!current->plug); +lockdep_assert (!fetch_and_set (current->sched_rt_mutex,1 )); +} +void rt_mutex_schedule (void ) {lockdep_assert (current->sched_rt_mutex);
@@ -7129,6 +7140,11 @@ void rt_mutex_post_schedule(void)lockdep_assert (fetch_and_set (current->sched_rt_mutex,0 )); } +void rt_mutex_futex_post_schedule (void ) +{ +lockdep_assert (fetch_and_set (current->sched_rt_mutex,0 )); +} +/* * rt_mutex_setprio - set the current priority of a task * @p: task to boost
Greg Kroah-Hartman
maintainerPATCH 636/877 rtc: rzn1: Handle unset alarm weekday in rzn1_rtc_read_alarm
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lad Prabhakar <[email protected]>
[ Upstream commit 457b5dbce31209e65e1184716ed3af59cb1c0372 ]
RZN1_RTC_ALW is a weekday bitmask where bit N represents weekday N. When no alarm has been configured, the register has its power-on-reset value of zero.
rzn1_rtc_read_alarm() uses fls() to convert the weekday bitmask into a weekday number. When RZN1_RTC_ALW is zero, fls(0) returns zero and fls(wday) - 1 evaluates to -1. This invalid weekday is then used to calculate the alarm date and can either leave tm_wday set to -1 or produce a fabricated alarm date.
Treat a zero RZN1_RTC_ALW value as an unset alarm weekday and return without calculating the alarm date. Move reading RZN1_RTC_CTL1 before this check so that alrm->enabled is updated for both configured and unconfigured alarms.
--- drivers/rtc/rtc-rzn1.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
drivers/rtc/rtc-rzn1.c +12 -4
@@ -193,13 +193,24 @@ static int rzn1_rtc_read_alarm(struct deif (ret)return ret; + ctl1 =readl (rtc->base +RZN1_RTC_CTL1 ); + alrm->enabled = !!(ctl1 &RZN1_RTC_CTL1_ALME ); + min =readl (rtc->base +RZN1_RTC_ALM ); hour =readl (rtc->base +RZN1_RTC_ALH ); - wday =readl (rtc->base +RZN1_RTC_ALW ); tm->tm_sec =0 ; tm->tm_min =bcd2bin (min); tm->tm_hour =bcd2bin (hour); + +/* +* If wday is zero, no bit is set in RZN1_RTC_ALW. This is the +* register's power-on reset value. +*/ + wday =readl (rtc->base +RZN1_RTC_ALW ); +if (!wday) +return 0 ; + delta_days = ((fls (wday) -1 ) - tm->tm_wday +7 ) %7 ; tm->tm_wday =fls (wday) -1 ;
@@ -208,9 +219,6 @@ static int rzn1_rtc_read_alarm(struct dertc_time64_to_tm (alarm, tm); } - ctl1 =readl (rtc->base +RZN1_RTC_CTL1 ); - alrm->enabled = !!(ctl1 &RZN1_RTC_CTL1_ALME ); -return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 637/877 perf/aux: Allocate non-contiguous AUX pages by default
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yabin Cui <[email protected]>
[ Upstream commit 18049c8cff9cc89daadc4df6975f7d9069638926 ]
perf always allocates contiguous AUX pages based on aux_watermark. However, this contiguous allocation doesn't benefit all PMUs. For instance, ARM SPE and TRBE operate with virtual pages, and Coresight ETR allocates a separate buffer. For these PMUs, allocating contiguous AUX pages unnecessarily exacerbates memory fragmentation. This fragmentation can prevent their use on long-running devices.
This patch modifies the perf driver to be memory-friendly by default, by allocating non-contiguous AUX pages. For PMUs requiring contiguous pages (Intel BTS and some Intel PT), the existing PERF_PMU_CAP_AUX_NO_SG capability can be used. For PMUs that don't require but can benefit from contiguous pages (some Intel PT), a new capability, PERF_PMU_CAP_AUX_PREFER_LARGE, is added to maintain their existing behavior.
Stable-dep-of: 8767b4d73018 ("perf/x86/intel: Remove anythread_deprecated bit from perf_capabilities")
--- arch/x86/events/intel/pt.c | 2 ++ include/linux/perf_event.h | 1 + kernel/events/ring_buffer.c | 29 ++++++++++++++++++++--------- 3 files changed, 23 insertions(+), 9 deletions(-)
arch/x86/events/intel/pt.c +2 -0
@@ -1896,6 +1896,8 @@ static __init int pt_init(void)if (!intel_pt_validate_hw_cap (PT_CAP_topa_multiple_entries)) pt_pmu.pmu.capabilities =PERF_PMU_CAP_AUX_NO_SG ; +else + pt_pmu.pmu.capabilities =PERF_PMU_CAP_AUX_PREFER_LARGE ; pt_pmu.pmu.capabilities |=PERF_PMU_CAP_EXCLUSIVE | PERF_PMU_CAP_ITRACE |
include/linux/perf_event.h +1 -0
@@ -301,6 +301,7 @@ struct perf_event_pmu_context;#define PERF_PMU_CAP_AUX_OUTPUT 0x0080#define PERF_PMU_CAP_EXTENDED_HW_TYPE 0x0100#define PERF_PMU_CAP_AUX_PAUSE 0x0200 +#define PERF_PMU_CAP_AUX_PREFER_LARGE 0x0400/** * pmu::scope
kernel/events/ring_buffer.c +20 -9
@@ -685,7 +685,15 @@ int rb_alloc_aux(struct perf_buffer *rb, {bool overwrite = !(flags &RING_BUFFER_WRITABLE );int node = (event->cpu ==-1 ) ?-1 :cpu_to_node (event->cpu); -int ret = -ENOMEM , max_order; +bool use_contiguous_pages = event->pmu->capabilities & ( +PERF_PMU_CAP_AUX_NO_SG |PERF_PMU_CAP_AUX_PREFER_LARGE ); +/* +* Initialize max_order to 0 for page allocation. This allocates single +* pages to minimize memory fragmentation. This is overridden if the +* PMU needs or prefers contiguous pages (use_contiguous_pages = true). +*/ +int max_order =0 ; +int ret = -ENOMEM ;if (!has_aux (event))return -EOPNOTSUPP ;
@@ -695,8 +703,8 @@ int rb_alloc_aux(struct perf_buffer *rb,if (!overwrite) {/* -* Watermark defaults to half the buffer, and so does the -* max_order, to aid PMU drivers in double buffering. +* Watermark defaults to half the buffer, to aid PMU drivers +* in double buffering. */ if (!watermark) watermark = min_t(unsigned long,
@@ -704,16 +712,19 @@ int rb_alloc_aux(struct perf_buffer *rb, (unsigned long)nr_pages << (PAGE_SHIFT - 1));/* -* Use aux_watermark as the basis for chunking to -* help PMU drivers honor the watermark. +* If using contiguous pages, use aux_watermark as the basis +* for chunking to help PMU drivers honor the watermark. */ - max_order =get_order (watermark); +if (use_contiguous_pages) + max_order =get_order (watermark); }else {/* -* We need to start with the max_order that fits in nr_pages, -* not the other way around, hence ilog2() and not get_order. +* If using contiguous pages, we need to start with the +* max_order that fits in nr_pages, not the other way around, +* hence ilog2() and not get_order. */ - max_order =ilog2 (nr_pages); +if (use_contiguous_pages) + max_order =ilog2 (nr_pages); watermark =0 ; }
Greg Kroah-Hartman
maintainerPATCH 638/877 perf/x86/intel: Remove anythread_deprecated bit from perf_capabilities
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dapeng Mi <[email protected]>
[ Upstream commit 8767b4d73018bd3143f4c55b672064fad292f11b ]
AnyThread mode deprecation is enumerated by CPUID.0AH:EDX[15] instead of PERF_CAPABILITIES MSR. It's not a good practice to define a bit to represent "anythread deprecation" in perf_capabilities. It leads to the anythread_deprecated bit could be overwritten by the real value of PERF_CAPABILITIES MSR, just like the below code in update_pmu_cap() does.
if (!intel_pmu_broken_perf_cap()) {
/* Perf Metric (Bit 15) and PEBS via PT (Bit 16) are hybrid enumeration */
rdmsrq(MSR_IA32_PERF_CAPABILITIES, hybrid(pmu, intel_cap).capabilities);
}It leads to the anythread_deprecated bit is cleared to 0 and the "any" attribute is incorrectly shown in the /sys/devices/cpu/format/ folder on these support Perfmon v6 platforms, like Clearwater Forest.
$ grep . /sys/devices/cpu/format/* /sys/devices/cpu/format/acr_mask:config2:0-63 /sys/devices/cpu/format/any:config:21 /sys/devices/cpu/format/cmask:config:24-31
So remove the anythread_deprecated bit from perf_capabilities structure and directly depends on CPUID.0AH:EDX[15] to judge if anythread is deprecated.
--- arch/x86/events/intel/core.c | 10 +++------- arch/x86/events/perf_event.h | 2 +- 2 files changed, 4 insertions(+), 8 deletions(-)
arch/x86/events/intel/core.c +3 -7
@@ -6568,12 +6568,6 @@ __init int intel_pmu_init(void)x86_add_quirk (intel_arch_events_quirk);/* Install first, so it runs last */ -if (version >=5 ) { - x86_pmu.intel_cap.anythread_deprecated = edx.split.anythread_deprecated; -if (x86_pmu.intel_cap.anythread_deprecated) -pr_cont (" AnyThread deprecated, " ); - } -/* * Install the hw-cache-events table: */
@@ -7301,8 +7295,10 @@ __init int intel_pmu_init(void) &x86_pmu.intel_ctrl);/* AnyThread may be deprecated on arch perfmon v5 or later */ -if (x86_pmu.intel_cap.anythread_deprecated) +if (version >=5 && edx.split.anythread_deprecated) { x86_pmu.format_attrs = intel_arch_formats_attr; +pr_cont ("AnyThread deprecated, " ); + } intel_pmu_check_event_constraints(x86_pmu.event_constraints, x86_pmu.cntr_mask64,
arch/x86/events/perf_event.h +1 -1
@@ -630,7 +630,7 @@ union perf_capabilities { u64 perf_metrics:1; u64 pebs_output_pt_available:1; u64 pebs_timing_info:1; - u64 anythread_deprecated:1; + u64 __reserved:1; };u64 capabilities; };
Greg Kroah-Hartman
maintainerPATCH 639/877 ring-buffer: Show persistent buffer dropped events in trace_pipe file
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Steven Rostedt <[email protected]>
[ Upstream commit 8928e4a3be34bf053f9ef1cad67263604bf4f05e ]
When the persistent ring buffer is validated on boot up, if a subbuffer is deemed invalid, it resets the buffer and continues. Have the code preserve the RB_MISSED_EVENTS flag in the commit portion of the subbuffer header and pass that back so that the trace_pipe file can show the missed events like the trace file does.
For example:
<...>-1242 [005] d.... 4429.120116: page_fault_user: address=0x7ffaebb6e728 ip=0x7ffaeb9d4960 error_code=0x7 <...>-1242 [005] ..... 4429.120124: mm_page_alloc: page=00000000055254f3 pfn=0x1373bd order=0 migratetype=1 gfp_flags=GFP_HIGHUSER_MOVABLE|__GFP_COMP <...>-1242 [005] d..2. 4429.120132: tlb_flush: pages:1 reason:local MM shootdown (3) CPU:5 [LOST EVENTS] <...>-1242 [005] d.... 4429.120661: page_fault_user: address=0x55ba7c2d0944 ip=0x55ba7c20cd02 error_code=0x7 <...>-1242 [005] ..... 4429.120669: mm_page_alloc: page=0000000005a02500 pfn=0x12b6e4 order=0 migratetype=1 gfp_flags=GFP_HIGHUSER_MOVABLE|__GFP_COMP <...>-1242 [005] d..2. 4429.120680: tlb_flush: pages:1 reason:local MM shootdown (3)
Backport notes for 6.18:
Keep the ring_buffer_read_page() changes needed as context for 6365c44a824f ("ring-buffer: Allow splice reads on static buffers"). Separate the raw commit flags from the page byte count and preserve the lost-events flag when copying page contents. Keep the existing bpage name, rb_page_capacity(reader) bounds and unsigned lost-event count. Read and mask bpage->commit directly instead of adding the newer data-page helpers.
Drop the reader-page unknown-loss propagation: this tree lacks the persistent invalid-subbuffer recovery and signed-loss reporting changes that make that path meaningful.
Keep the copy loop bounded by the page size, not event_size, avoiding the one-event-per-read regression subsequently fixed by af05b4e06279. Preserve the loss flag when trimming a swapped page to real_end, and combine output flags with bitwise OR so an already-set flag is not added a second time.
Stable-dep-of: 6365c44a824f ("ring-buffer: Allow splice reads on static buffers")
--- kernel/trace/ring_buffer.c | 56 +++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 24 deletions(-)
kernel/trace/ring_buffer.c +32 -24
@@ -6534,6 +6534,7 @@ int ring_buffer_read_page(struct trace_bstruct buffer_page *reader;unsigned long missed_events;unsigned int commit; +unsigned int size;unsigned int read;u64 save_timestamp;
@@ -6568,7 +6569,8 @@ int ring_buffer_read_page(struct trace_b event =rb_reader_event (cpu_buffer); read = reader->read; - commit =rb_page_size (reader); + commit =rb_page_commit (reader); + size =rb_page_size (reader);/* Check if any events were dropped */ missed_events = cpu_buffer->lost_events;
@@ -6580,13 +6582,14 @@ int ring_buffer_read_page(struct trace_b* we must copy the data from the page to the buffer. * Otherwise, we can simply swap the page with the one passed in. */ -if (read || (len < (commit - read)) || +if (read || (len < (size - read)) || cpu_buffer->reader_page == cpu_buffer->commit_page || cpu_buffer->mapped) {struct buffer_data_page *rpage = cpu_buffer->reader_page->page;unsigned int rpos = read;unsigned int pos =0 ; -unsigned int size; +unsigned int event_size; +unsigned int flags =0 ;/* * If a full page is expected, this can still be returned
@@ -6595,19 +6598,22 @@ int ring_buffer_read_page(struct trace_b* the reader page. */ if (full && - (!read || (len < (commit - read)) || + (!read || (len < (size - read)) || cpu_buffer->reader_page == cpu_buffer->commit_page))return -1 ; -if (len > (commit - read)) - len = (commit - read); +if (len > (size - read)) + len = (size - read);/* Always keep the time extend and data together */ - size =rb_event_ts_length (event); + event_size =rb_event_ts_length (event); -if (len < size) +if (len < event_size)return -1 ; +if (commit &RB_MISSED_EVENTS ) + flags =RB_MISSED_EVENTS ; +/* save the current timestamp, since the user will need it */ save_timestamp = cpu_buffer->read_stamp;
@@ -6619,25 +6625,25 @@ int ring_buffer_read_page(struct trace_b* one or two events. * We have already ensured there's enough space if this * is a time extend. */ - size =rb_event_length (event); -memcpy (bpage->data + pos, rpage->data + rpos, size); + event_size =rb_event_length (event); +memcpy (bpage->data + pos, rpage->data + rpos, event_size); - len -= size; + len -= event_size;rb_advance_reader (cpu_buffer); rpos = reader->read; - pos += size; + pos += event_size; -if (rpos >= commit) +if (rpos >= size)break ; event =rb_reader_event (cpu_buffer);/* Always keep the time extend and data together */ - size =rb_event_ts_length (event); - }while (len >= size); + event_size =rb_event_ts_length (event); + }while (len >= event_size);/* update bpage */ -local_set (&bpage->commit, pos); +local_set (&bpage->commit, pos | flags); bpage->time_stamp = save_timestamp;/* we copied everything to the beginning */
@@ -6662,12 +6668,14 @@ int ring_buffer_read_page(struct trace_b* on the page. */ if (reader->real_end) -local_set (&bpage->commit, reader->real_end); +local_set (&bpage->commit, reader->real_end | + (commit &RB_MISSED_EVENTS )); } cpu_buffer->lost_events =0 ; commit =local_read (&bpage->commit); + size = commit & ~RB_MISSED_MASK ;/* * Set a flag in the commit field if we lost events */
@@ -6675,20 +6683,20 @@ int ring_buffer_read_page(struct trace_b/* If there is room at the end of the page to save the * missed events, then record it there. */ -if (rb_page_capacity (reader) - commit >=sizeof (missed_events)) { -memcpy (&bpage->data[commit], &missed_events, +if (rb_page_capacity (reader) - size >=sizeof (missed_events)) { +memcpy (&bpage->data[size], &missed_events,sizeof (missed_events)); -local_add (RB_MISSED_STORED , &bpage->commit); - commit +=sizeof (missed_events); + commit |=RB_MISSED_STORED ; + size +=sizeof (missed_events); } -local_add (RB_MISSED_EVENTS , &bpage->commit); +local_set (&bpage->commit, commit |RB_MISSED_EVENTS ); }/* * This page may be off to user land. Zero it out here. */ -if (commit <rb_page_capacity (reader)) -memset (&bpage->data[commit],0 ,rb_page_capacity (reader) - commit); +if (size <rb_page_capacity (reader)) +memset (&bpage->data[size],0 ,rb_page_capacity (reader) - size);return read; }
Greg Kroah-Hartman
maintainerPATCH 640/877 ring-buffer: Allow splice reads on static buffers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vincent Donnefort <[email protected]>
[ Upstream commit 6365c44a824ff138e7926413932bb5c2e28a4c8c ]
ring_buffer_read_page() rejects splice (full=1) reads on static buffers (that is user-mapped, persistent or remote) because !read check assumes unread pages must be swapped. However for those buffers we have no other choice than memcpy the data.
For the memcpy case, only return an error when the writer is still on the reader page for the splice interface to wait.
--- kernel/trace/ring_buffer.c | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-)
kernel/trace/ring_buffer.c +2 -9
@@ -6591,15 +6591,8 @@ int ring_buffer_read_page(struct trace_bunsigned int event_size;unsigned int flags =0 ; -/* -* If a full page is expected, this can still be returned -* if there's been a previous partial read and the -* rest of the page can be read and the commit page is off -* the reader page. -*/ -if (full && - (!read || (len < (size - read)) || - cpu_buffer->reader_page == cpu_buffer->commit_page)) +/* If a full page is requested, it cannot be the commit page */ +if (full && cpu_buffer->reader_page == cpu_buffer->commit_page)return -1 ;if (len > (size - read))
Greg Kroah-Hartman
maintainerPATCH 641/877 nvme: add missing SRCU grace period in error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tristan Madani <[email protected]>
[ Upstream commit ef248d5de4469fb6bbaf8dbe0c4c47800080d648 ]
nvme_alloc_ns() error path at out_unlink_ns removes ns from the namespace head siblings list with list_del_rcu(&ns->siblings) but does not wait for SRCU readers before freeing the namespace struct. Multipath code iterates the head->list under srcu_read_lock() in nvme_find_path() and nvme_mpath_revalidate_paths(), so a concurrent reader can still hold a reference to ns when kfree(ns) runs.
The normal removal path in nvme_ns_remove() correctly calls synchronize_srcu(&ns->head->srcu) after list_del_rcu() to wait for in-progress readers. Add the same grace period in the error path.
--- drivers/nvme/host/core.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/nvme/host/core.c +3 -0
@@ -3974,6 +3974,9 @@ static void nvme_alloc_ns(struct nvme_ctif (list_empty (&ns->head->list))list_del_init (&ns->head->entry);mutex_unlock (&ctrl->subsys->lock); + +/* guarantee not available in head->list */ +synchronize_srcu (&ns->head->srcu);nvme_put_ns_head (ns->head); out_cleanup_disk:put_disk (disk);
Greg Kroah-Hartman
maintainerPATCH 642/877 nvme: all namespaces in a subsystem must adhere to a common atomic write size
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alan Adamson <[email protected]>
[ Upstream commit 8695f060a02953b33ac6240895dcb9c7ce16c91c ]
The first namespace configured in a subsystem sets the subsystem's atomic write size based on its AWUPF or NAWUPF. Subsequent namespaces must have an atomic write size (per their AWUPF or NAWUPF) less than or equal to the subsystem's atomic write size, or their probing will be rejected.
Stable-dep-of: 3838e80fcfb3 ("nvme: skip the zoned limits update if the zone info query failed")
--- drivers/nvme/host/core.c | 30 +++++++++++++++++++++++++++--- drivers/nvme/host/nvme.h | 3 ++- 2 files changed, 29 insertions(+), 4 deletions(-)
drivers/nvme/host/core.c +27 -3
@@ -2054,7 +2054,21 @@ static bool nvme_update_disk_info(structif (id->nsfeat &NVME_NS_FEAT_ATOMICS && id->nawupf) atomic_bs = (1 +le16_to_cpu (id->nawupf)) * bs;else - atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs; + atomic_bs = (1 + ns->ctrl->awupf) * bs; + +/* +* Set subsystem atomic bs. +*/ +if (ns->ctrl->subsys->atomic_bs) { +if (atomic_bs != ns->ctrl->subsys->atomic_bs) { +dev_err_ratelimited (ns->ctrl->device, +"%s: Inconsistent Atomic Write Size, Namespace will not be added: Subsystem=%d bytes, Controller/Namespace=%d bytes\n" , + ns->disk ? ns->disk->disk_name :"?" , + ns->ctrl->subsys->atomic_bs, + atomic_bs); + } + }else + ns->ctrl->subsys->atomic_bs = atomic_bs;nvme_update_atomic_write_disk_info (ns, id, lim, bs, atomic_bs); }
@@ -2193,6 +2207,17 @@ static int nvme_update_ns_info_block(strnvme_set_chunk_sectors (ns, id, &lim);if (!nvme_update_disk_info (ns, id, &lim)) capacity =0 ; + +/* +* Validate the max atomic write size fits within the subsystem's +* atomic write capabilities. +*/ +if (lim.atomic_write_hw_max > ns->ctrl->subsys->atomic_bs) { +blk_mq_unfreeze_queue (ns->disk->queue, memflags); + ret = -ENXIO ; + goto out; + } +nvme_config_discard (ns, &lim);if (IS_ENABLED (CONFIG_BLK_DEV_ZONED ) && ns->head->ids.csi ==NVME_CSI_ZNS )
@@ -3029,7 +3054,6 @@ static int nvme_init_subsystem(struct nvkfree (subsys);return -EINVAL ; } - subsys->awupf =le16_to_cpu (id->awupf);nvme_mpath_default_iopolicy (subsys); subsys->dev.class = &nvme_subsys_class;
@@ -3439,7 +3463,7 @@ static int nvme_init_identify(struct nvmdev_pm_qos_expose_latency_tolerance (ctrl->device); else if (!ctrl->apst_enabled && prev_apst_enabled)dev_pm_qos_hide_latency_tolerance (ctrl->device); - + ctrl->awupf =le16_to_cpu (id->awupf); out_free:kfree (id);return ret;
drivers/nvme/host/nvme.h +2 -1
@@ -410,6 +410,7 @@ struct nvme_ctrl {enum nvme_ctrl_type cntrltype;enum nvme_dctype dctype; +u16 awupf;/* 0's based value. */ };static inline enum nvme_ctrl_state nvme_ctrl_state (struct nvme_ctrl *ctrl)
@@ -442,11 +443,11 @@ struct nvme_subsystem {u8 cmic;enum nvme_subsys_type subtype;u16 vendor_id; -u16 awupf;/* 0's based awupf value. */ struct ida ns_ida;#ifdef CONFIG_NVME_MULTIPATH enum nvme_iopolicy iopolicy;#endif +u32 atomic_bs; };/*
Greg Kroah-Hartman
maintainerPATCH 643/877 nvme: refactor the atomic write unit detection
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christoph Hellwig <[email protected]>
[ Upstream commit b2e607fecac15e07f50269c080e2e71b5049dfa2 ]
Move all the code out of nvme_update_disk_info into the helper, and rename the helper to have a somewhat less clumsy name.
Stable adaptation for 6.12:
- Keep the existing atomic write helper refactor, but omit
BLK_FEAT_ATOMIC_WRITES: this tree enables atomic writes through the hardware limits and does not define that feature flag.
- Call the existing discard setup helper from nvme_update_disk_info() after setting logical_block_size. Save the disk-info validity result and defer clearing capacity until after atomic-size validation. This preserves the result while leaving the zoned update insertion point clear for 3838e80fcfb32e62baffb63c6dc0a60153665a4d.
- Adapt the preceding dependency's atomic-size error path to the single-argument blk_mq_unfreeze_queue() API and cancel the pending limits update before unfreezing, releasing limits_lock on rejection.
No additional functions are introduced.
Stable-dep-of: 3838e80fcfb3 ("nvme: skip the zoned limits update if the zone info query failed")
--- drivers/nvme/host/core.c | 84 +++++++++++++++++++++++++---------------------- 1 file changed, 46 insertions(+), 38 deletions(-)
drivers/nvme/host/core.c +46 -38
@@ -1993,20 +1993,50 @@ static void nvme_configure_metadata(stru } -static void nvme_update_atomic_write_disk_info (struct nvme_ns *ns, -struct nvme_id_ns *id,struct queue_limits *lim, -u32 bs,u32 atomic_bs) +static u32 nvme_configure_atomic_write (struct nvme_ns *ns, +struct nvme_id_ns *id,struct queue_limits *lim,u32 bs) { -unsigned int boundary =0 ; +u32 atomic_bs, boundary =0 ; -if (id->nsfeat &NVME_NS_FEAT_ATOMICS && id->nawupf) { -if (le16_to_cpu (id->nabspf)) +/* +* We do not support an offset for the atomic boundaries. +*/ +if (id->nabo) +return bs; + +if ((id->nsfeat &NVME_NS_FEAT_ATOMICS ) && id->nawupf) { +/* +* Use the per-namespace atomic write unit when available. +*/ + atomic_bs = (1 +le16_to_cpu (id->nawupf)) * bs; +if (id->nabspf) boundary = (le16_to_cpu (id->nabspf) +1 ) * bs; + }else { +/* +* Use the controller wide atomic write unit. This sucks +* because the limit is defined in terms of logical blocks while +* namespaces can have different formats, and because there is +* no clear language in the specification prohibiting different +* values for different controllers in the subsystem. +*/ + atomic_bs = (1 + ns->ctrl->awupf) * bs; } + +if (!ns->ctrl->subsys->atomic_bs) { + ns->ctrl->subsys->atomic_bs = atomic_bs; + }else if (ns->ctrl->subsys->atomic_bs != atomic_bs) { +dev_err_ratelimited (ns->ctrl->device, +"%s: Inconsistent Atomic Write Size, Namespace will not be added: Subsystem=%d bytes, Controller/Namespace=%d bytes\n" , + ns->disk ? ns->disk->disk_name :"?" , + ns->ctrl->subsys->atomic_bs, + atomic_bs); + } + lim->atomic_write_hw_max = atomic_bs; lim->atomic_write_hw_boundary = boundary; lim->atomic_write_hw_unit_min = bs; lim->atomic_write_hw_unit_max =rounddown_pow_of_two (atomic_bs); +return atomic_bs; }static u32 nvme_max_drv_segments (struct nvme_ctrl *ctrl)
@@ -2044,34 +2074,8 @@ static bool nvme_update_disk_info(struct valid = false; } - atomic_bs = phys_bs = bs; -if (id->nabo ==0 ) { -/* -* Bit 1 indicates whether NAWUPF is defined for this namespace -* and whether it should be used instead of AWUPF. If NAWUPF == -* 0 then AWUPF must be used instead. -*/ -if (id->nsfeat &NVME_NS_FEAT_ATOMICS && id->nawupf) - atomic_bs = (1 +le16_to_cpu (id->nawupf)) * bs; -else - atomic_bs = (1 + ns->ctrl->awupf) * bs; - -/* -* Set subsystem atomic bs. -*/ -if (ns->ctrl->subsys->atomic_bs) { -if (atomic_bs != ns->ctrl->subsys->atomic_bs) { -dev_err_ratelimited (ns->ctrl->device, -"%s: Inconsistent Atomic Write Size, Namespace will not be added: Subsystem=%d bytes, Controller/Namespace=%d bytes\n" , - ns->disk ? ns->disk->disk_name :"?" , - ns->ctrl->subsys->atomic_bs, - atomic_bs); - } - }else - ns->ctrl->subsys->atomic_bs = atomic_bs; - -nvme_update_atomic_write_disk_info (ns, id, lim, bs, atomic_bs); - } + phys_bs = bs; + atomic_bs =nvme_configure_atomic_write (ns, id, lim, bs);if (id->nsfeat &NVME_NS_FEAT_IO_OPT ) {/* NPWG = Namespace Preferred Write Granularity */
@@ -2095,6 +2099,7 @@ static bool nvme_update_disk_info(struct lim->max_write_zeroes_sectors =UINT_MAX ; else lim->max_write_zeroes_sectors = ns->ctrl->max_zeroes_sectors; +nvme_config_discard (ns, lim);return valid; }
@@ -2169,6 +2174,7 @@ static int nvme_update_ns_info_block(strstruct nvme_id_ns *id;sector_t capacity;unsigned lbaf; +bool valid;int ret; ret =nvme_identify_ns (ns->ctrl, info->nsid, &id);
@@ -2205,20 +2211,22 @@ static int nvme_update_ns_info_block(strnvme_set_ctrl_limits (ns->ctrl, &lim);nvme_configure_metadata (ns->ctrl, ns->head, id, nvm, info);nvme_set_chunk_sectors (ns, id, &lim); -if (!nvme_update_disk_info (ns, id, &lim)) - capacity =0 ; + valid =nvme_update_disk_info (ns, id, &lim);/* * Validate the max atomic write size fits within the subsystem's * atomic write capabilities. */ if (lim.atomic_write_hw_max > ns->ctrl->subsys->atomic_bs) { -blk_mq_unfreeze_queue (ns->disk->queue, memflags); +queue_limits_cancel_update (ns->disk->queue); +blk_mq_unfreeze_queue (ns->disk->queue); ret = -ENXIO ; goto out; } -nvme_config_discard (ns, &lim); +if (!valid) + capacity =0 ; +if (IS_ENABLED (CONFIG_BLK_DEV_ZONED ) && ns->head->ids.csi ==NVME_CSI_ZNS )nvme_update_zone_info (ns, &lim, &zi);
Greg Kroah-Hartman
maintainerPATCH 644/877 nvme: fix atomic write size validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christoph Hellwig <[email protected]>
[ Upstream commit f46d273449ba65afd53f3dd8fe0182c9df877e08 ]
Don't mix the namespace and controller values, and validate the per-controller limit when probing the controller. This avoid spurious failures for controllers with namespaces that have different namespaces with different logical block sizes, or report the per-namespace values only for some namespaces.
It also fixes a missing queue_limits_cancel_update in an error path by removing that error path.
Stable adaptation for 6.12:
- Remove the atomic-size rejection together with its locally adapted queue_limits_cancel_update() and one-argument queue unfreeze calls. Validation now happens during controller identification, as upstream.
- Keep nvme_config_discard() in nvme_update_disk_info(), where the preceding dependency moved it. Do not restore a duplicate call here.
- Preserve the saved disk-info validity result and capacity handling, leaving the zoned update insertion point available for target 3838e80fcfb32e62baffb63c6dc0a60153665a4d.
No additional functions are introduced.
Stable-dep-of: 3838e80fcfb3 ("nvme: skip the zoned limits update if the zone info query failed")
--- drivers/nvme/host/core.c | 34 +++++++++++----------------------- drivers/nvme/host/nvme.h | 3 +-- 2 files changed, 12 insertions(+), 25 deletions(-)
drivers/nvme/host/core.c +11 -23
@@ -2019,17 +2019,7 @@ static u32 nvme_configure_atomic_write(s* no clear language in the specification prohibiting different * values for different controllers in the subsystem. */ - atomic_bs = (1 + ns->ctrl->awupf) * bs; - } - -if (!ns->ctrl->subsys->atomic_bs) { - ns->ctrl->subsys->atomic_bs = atomic_bs; - }else if (ns->ctrl->subsys->atomic_bs != atomic_bs) { -dev_err_ratelimited (ns->ctrl->device, -"%s: Inconsistent Atomic Write Size, Namespace will not be added: Subsystem=%d bytes, Controller/Namespace=%d bytes\n" , - ns->disk ? ns->disk->disk_name :"?" , - ns->ctrl->subsys->atomic_bs, - atomic_bs); + atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs; } lim->atomic_write_hw_max = atomic_bs;
@@ -2213,17 +2203,6 @@ static int nvme_update_ns_info_block(strnvme_set_chunk_sectors (ns, id, &lim); valid =nvme_update_disk_info (ns, id, &lim); -/* -* Validate the max atomic write size fits within the subsystem's -* atomic write capabilities. -*/ -if (lim.atomic_write_hw_max > ns->ctrl->subsys->atomic_bs) { -queue_limits_cancel_update (ns->disk->queue); -blk_mq_unfreeze_queue (ns->disk->queue); - ret = -ENXIO ; - goto out; - } -if (!valid) capacity =0 ;
@@ -3047,6 +3026,7 @@ static int nvme_init_subsystem(struct nvmemcpy (subsys->model, id->mn,sizeof (subsys->model)); subsys->vendor_id =le16_to_cpu (id->vid); subsys->cmic = id->cmic; + subsys->awupf =le16_to_cpu (id->awupf);/* Versions prior to 1.4 don't necessarily report a valid type */ if (id->cntrltype == NVME_CTRL_DISC ||
@@ -3376,6 +3356,15 @@ static int nvme_init_identify(struct nvmif (ret) goto out_free; } + +if (le16_to_cpu (id->awupf) != ctrl->subsys->awupf) { +dev_err_ratelimited (ctrl->device, +"inconsistent AWUPF, controller not added (%u/%u).\n" , +le16_to_cpu (id->awupf), ctrl->subsys->awupf); + ret = -EINVAL ; + goto out_free; + } +memcpy (ctrl->subsys->firmware_rev, id->fr,sizeof (ctrl->subsys->firmware_rev));
@@ -3471,7 +3460,6 @@ static int nvme_init_identify(struct nvmdev_pm_qos_expose_latency_tolerance (ctrl->device); else if (!ctrl->apst_enabled && prev_apst_enabled)dev_pm_qos_hide_latency_tolerance (ctrl->device); - ctrl->awupf =le16_to_cpu (id->awupf); out_free:kfree (id);return ret;
drivers/nvme/host/nvme.h +1 -2
@@ -410,7 +410,6 @@ struct nvme_ctrl {enum nvme_ctrl_type cntrltype;enum nvme_dctype dctype; -u16 awupf;/* 0's based value. */ };static inline enum nvme_ctrl_state nvme_ctrl_state (struct nvme_ctrl *ctrl)
@@ -443,11 +442,11 @@ struct nvme_subsystem {u8 cmic;enum nvme_subsys_type subtype;u16 vendor_id; +u16 awupf;/* 0's based value. */ struct ida ns_ida;#ifdef CONFIG_NVME_MULTIPATH enum nvme_iopolicy iopolicy;#endif -u32 atomic_bs; };/*
Greg Kroah-Hartman
maintainerPATCH 645/877 nvme: skip the zoned limits update if the zone info query failed
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chao Shi <[email protected]>
[ Upstream commit 3838e80fcfb32e62baffb63c6dc0a60153665a4d ]
nvme_query_zone_info() returns either a negative errno or a positive NVMe status code, but nvme_update_ns_info_block() only tests for the negative case:
ret = nvme_query_zone_info(ns, lbaf, &zi); if (ret < 0) goto out;
If the device fails the Identify Namespace (I/O Command Set specific) command, or the Identify Controller command issued by nvme_set_max_append(), the positive status falls through and setup continues with the zero-initialized zone info. nvme_update_zone_info() then marks the queue zoned with chunk_sectors and ns->head->zsze set to zero.
blk_validate_zoned_limits() does not check chunk_sectors, so the limits commit succeeds. blk_revalidate_disk_zones() does reject the zero zone size, but by then the limits are live and nothing rolls them back, so I/O keeps being submitted to a zoned queue with a zero zone size and disk_zone_no() shifts by ilog2(0):
nvme0n1: Invalid non power of two zone size (0)
UBSAN: shift-out-of-bounds in include/linux/blkdev.h:747:16 shift exponent -1 is negative disk_zone_no include/linux/blkdev.h:747 [inline] bio_straddles_zones include/linux/blkdev.h:1058 [inline] blk_zone_wplug_handle_write block/blk-zoned.c:1423 [inline] blk_zone_plug_bio.cold+0x25/0x1c8 block/blk-zoned.c:1605 blk_mq_submit_bio+0x18fb/0x2870 block/blk-mq.c:3196 submit_bh_wbc+0x575/0x740 fs/buffer.c:2824 __block_write_full_folio+0x728/0xdd0 fs/buffer.c:1933
Any device, firmware or NVMe-oF target that fails this one command reaches this.
Skip the zoned limits update in that case, and log which of the two things happened: during a revalidation the queue keeps the zone geometry it was last validated with, and on a first scan the namespace is registered without zoned limits, so that it is still available as a handle for admin commands. Neither of the paths in nvme_query_zone_info() that return a positive status logs anything, so the failure would otherwise be silent.
zi.zone_size is an exact indicator: every path that returns a positive status returns before it is assigned, and after that the only failure left is -ENODEV, which the caller already handles.
Found by FuzzNvme.
--- drivers/nvme/host/core.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-)
drivers/nvme/host/core.c +19 -2
@@ -2206,9 +2206,26 @@ static int nvme_update_ns_info_block(strif (!valid) capacity =0 ; +/* +* A failed zone info query leaves zi zero-initialized, so skip the +* zoned limits update instead of configuring the queue from it. +* During a revalidation that keeps the zone geometry the queue was +* last validated with; on a first scan the namespace is registered +* without zoned limits, so that it is still available as a handle +* for admin commands. +*/ if (IS_ENABLED (CONFIG_BLK_DEV_ZONED ) && - ns->head->ids.csi ==NVME_CSI_ZNS ) -nvme_update_zone_info (ns, &lim, &zi); + ns->head->ids.csi ==NVME_CSI_ZNS ) { +if (zi.zone_size) +nvme_update_zone_info (ns, &lim, &zi); +else +dev_warn (ns->ctrl->device, +"zone info query failed for nsid %u, %s\n" , + ns->head->ns_id, +blk_queue_is_zoned (ns->disk->queue) ? +"keeping the previous zone limits" : +"not enabling zoned mode" ); + }if (ns->ctrl->vwc &NVME_CTRL_VWC_PRESENT ) lim.features |=BLK_FEAT_WRITE_CACHE |BLK_FEAT_FUA ;
Greg Kroah-Hartman
maintainerPATCH 646/877 s390/vfio-ap: Fix missing lock required to access list of ap_matrix_mdev objects
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Anthony Krowiak <[email protected]>
[ Upstream commit 7fa61c29850d05e40ca9ed41bfdf57673023f581 ]
In order to traverse or add/remove ap_matrix_mdev objects in the matrix_dev->mdev_list, the matrix_dev->guests_lock mutex must be held. There are two functions that access the list without holding the mutex:
vfio_ap_mdev_probe function
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The vfio_ap_mdev_probe function uses the matrix_dev->mdevs_lock mutex to guard the add of a newly created ap_matrix_mdev object to the matrix_dev->mdev_list. This mutex does not protect list access; its purpose is to guard against concurrent access to fields contained in an ap_matrix_mdev object. This could lead to kernel memory corruption or use-after-free if another mdev is created or removed concurrently.
The adding of an ap_matrix_mdev object to matrix_dev->mdev_list is now guarded by the matrix_dev->guests_lock which is the correct way to protect against concurrent mdev_list access.
Also removed the following two lines of code because the matrix_mdev is allocated via vfio_alloc_device macro which uses kzalloc, so req_trigger and cfg_chg_trigger are already zero-initialised when the struct is allocated before the call to vfio_register_emulated_iommu_dev. This prevents a window whereby these triggers are set to NULL after the device is exposed to userspace.
matrix_mdev->req_trigger = NULL;matrix_mdev->cfg_chg_trigger = NULL;
vfio_ap_mdev_for_queue function
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The status_show function that supports display of the status attribute of the devices in /sys/bus/ap/devices calls the vfio_ap_mdev_for_queue function which iterates the matrix_dev->mdev_list to find the object representing the queue device whose status is to be displayed. In order to traverse this list, the matrix_dev->guests_lock mutex must be held.
To fix this, the guests_lock mutex is taken prior to taking the matrix_dev->mdevs_lock mutex in the status_show function. It is taken there rather than the vfio_ap_mdev_for_queue function - where it is needed - because it must be taken prior to the mdevs_lock mutex in order to adhere to the proper locking order and prevent a lockdep splat; also because the mdevs_lock is needed there to access fields within the matrix_mdev object in that function.
See the vfio-ap-locking.rst in the linux kernel tree.
--- drivers/s390/crypto/vfio_ap_ops.c | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-)
drivers/s390/crypto/vfio_ap_ops.c +23 -3
@@ -786,11 +786,17 @@ static int vfio_ap_mdev_probe(struct mde ret =vfio_register_emulated_iommu_dev (&matrix_mdev->vdev);if (ret) goto err_put_vdev; - matrix_mdev->req_trigger =NULL ; + +/* +* Take the matrix_dev->guests_lock mutex before adding the matrix_mdev +* to the mdev_list. All functions that traverse the list must also hold +* this lock to guard against additions to or removals from the list +* while it is being traversed. +*/ +mutex_lock (&matrix_dev->guests_lock);dev_set_drvdata (&mdev->dev, matrix_mdev); -mutex_lock (&matrix_dev->mdevs_lock);list_add (&matrix_mdev->node, &matrix_dev->mdev_list); -mutex_unlock (&matrix_dev->mdevs_lock); +mutex_unlock (&matrix_dev->guests_lock);return 0 ; err_put_vdev:
@@ -2247,6 +2253,8 @@ static struct ap_matrix_mdev *vfio_ap_mdunsigned long apid =AP_QID_CARD (q->apqn);unsigned long apqi =AP_QID_QUEUE (q->apqn); +lockdep_assert_held (&matrix_dev->guests_lock); +list_for_each_entry (matrix_mdev, &matrix_dev->mdev_list, node) {if (test_bit_inv (apid, matrix_mdev->matrix.apm) &&test_bit_inv (apqi, matrix_mdev->matrix.aqm))
@@ -2266,6 +2274,7 @@ static ssize_t status_show(struct devicestruct ap_matrix_mdev *matrix_mdev;struct ap_device *apdev =to_ap_dev (dev); +mutex_lock (&matrix_dev->guests_lock);mutex_lock (&matrix_dev->mdevs_lock); q =dev_get_drvdata (&apdev->device);
@@ -2314,6 +2323,7 @@ static ssize_t status_show(struct device done:mutex_unlock (&matrix_dev->mdevs_lock); +mutex_unlock (&matrix_dev->guests_lock);return nchars; }
@@ -2746,6 +2756,12 @@ static void vfio_ap_mdev_cfg_add(unsignevfio_ap_filter_apid_by_qtype (apm_add, aqm_add); +/* +* It is safe to traverse this list here because the +* required guard - matrix_dev->guests_lock - is taken in the +* vfio_ap_on_cfg_changed function prior to this function getting +* called. +*/ list_for_each_entry (matrix_mdev, &matrix_dev->mdev_list, node) {/* * The mdevs_lock must be held in order to access fields
@@ -2813,6 +2829,10 @@ void vfio_ap_on_cfg_changed(struct ap_coif (!cur_cfg_info || !prev_cfg_info)return ; +/* +* Take the guests_lock mutex here to guard access to the +* matrix_dev->mdev_list in the two functions called below. +*/ mutex_lock (&matrix_dev->guests_lock);vfio_ap_mdev_on_cfg_remove (cur_cfg_info, prev_cfg_info);
Greg Kroah-Hartman
maintainerPATCH 647/877 mm: fix incorrect vm_flags usage when checking allowable orders for tmpfs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Baolin Wang <[email protected]>
[ Upstream commit 2fd4e7693674b17807a6d082feb01a3fbf86f5f8 ]
Lance reported that when nothing else causes the mm to be considered for khugepaged collapse, an MADV_HUGEPAGE-advised tmpfs VMA alone does not trigger scanning.
After commit 6beeab870e70 ("mm: shmem: move shmem_huge_global_enabled() into shmem_allowable_huge_orders()"), the shmem/tmpfs allowable order check reads vma->flags directly. However, when MADV_HUGEPAGE is handled, khugepaged_enter_vma() is called before the VMA's flags have been updated, so the check uses stale flags and incorrectly rejects the VMA for collapse. As a result, khugepaged does not collapse the tmpfs file into PMD order in time.
Fix this by calling khugepaged_enter_vma() with the new VMA flags in madvise_update_vma(). Meanwhile we can remove the khugepaged_enter_vma() in hugepage_madvise().
--- mm/khugepaged.c | 6 ------ mm/madvise.c | 8 ++++++++ 2 files changed, 8 insertions(+), 6 deletions(-)
mm/khugepaged.c +0 -6
@@ -369,12 +369,6 @@ int hugepage_madvise(struct vm_area_stru#endif *vm_flags &= ~VM_NOHUGEPAGE ; *vm_flags |=VM_HUGEPAGE ; -/* -* If the vma become good for khugepaged to scan, -* register it here without waiting a page fault that -* may not happen any time soon. -*/ -khugepaged_enter_vma (vma, *vm_flags);break ;case MADV_NOHUGEPAGE : *vm_flags &= ~VM_HUGEPAGE ;
mm/madvise.c +8 -0
@@ -158,6 +158,14 @@ static int madvise_update_vma(struct vm_/* vm_flags is protected by the mmap_lock held in write mode. */ vma_start_write (vma);vm_flags_reset (vma, new_flags); +/* +* If the vma become good for khugepaged to scan, +* register it here without waiting a page fault that +* may not happen any time soon. +*/ +if (new_flags &VM_HUGEPAGE ) +khugepaged_enter_vma (vma, new_flags); +if (!vma->vm_file ||vma_is_anon_shmem (vma)) { error =replace_anon_vma_name (vma, anon_name);if (error)
Greg Kroah-Hartman
maintainerPATCH 648/877 nvdimm: preserve flush callback -ENOMEM
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit 6b7108712a4b1c37cac69815aede1dde202b3187 ]
nvdimm_flush() maps provider flush failures to -EIO. Keep that default because provider callbacks can report host-side or backend failures that should remain generic I/O errors to the guest.
Guest-side allocation failures should not be reported as I/O errors. In the virtio-pmem path, the flush request allocation can fail with -ENOMEM before any request is submitted to the host. Mapping that to -EIO makes resource pressure look like media failure.
Preserve -ENOMEM from provider callbacks and continue to map other non-zero provider failures to -EIO. The generic flush path still returns 0, and pmem_submit_bio() already converts errno values to block status for bio completion.
Message-ID: <[email protected]>
Stable-dep-of: e57140944b5a ("nvdimm: virtio_pmem: refcount requests for token lifetime")
--- drivers/nvdimm/region_devs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/nvdimm/region_devs.c +2 -1
@@ -1112,7 +1112,8 @@ int nvdimm_flush(struct nd_region *nd_reif (!nd_region->flush) rc =generic_nvdimm_flush (nd_region);else { -if (nd_region->flush (nd_region, bio)) + rc = nd_region->flush (nd_region, bio); +if (rc && rc != -ENOMEM ) rc = -EIO ; }
Greg Kroah-Hartman
maintainerPATCH 649/877 nvdimm: pmem: keep PREFLUSH before data writes
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit c644a2f8fef5618fcf453c591177700fd07dd024 ]
pmem_submit_bio() records a REQ_PREFLUSH error, but continues to copy the bio data and can later overwrite the error with a successful REQ_FUA flush. That lets data writes run after a failed preflush and can complete the bio successfully despite the failed ordering barrier.
Run the REQ_PREFLUSH flush synchronously before touching the bio data and complete the bio with the flush error if it fails. Keep asynchronous flush chaining for REQ_FUA. At that point, data copy has completed and the parent bio can wait for the chained flush bio.
Message-ID: <[email protected]>
Stable-dep-of: e57140944b5a ("nvdimm: virtio_pmem: refcount requests for token lifetime")
--- drivers/nvdimm/pmem.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
drivers/nvdimm/pmem.c +9 -3
@@ -209,8 +209,14 @@ static void pmem_submit_bio(struct bio *struct pmem_device *pmem = bio->bi_bdev->bd_disk->private_data;struct nd_region *nd_region =to_region (pmem); -if (bio->bi_opf &REQ_PREFLUSH ) - ret =nvdimm_flush (nd_region, bio); +if (bio->bi_opf &REQ_PREFLUSH ) { + ret =nvdimm_flush (nd_region,NULL ); +if (ret) { + bio->bi_status =errno_to_blk_status (ret); +bio_endio (bio); +return ; + } + } do_acct =blk_queue_io_stat (bio->bi_bdev->bd_disk->queue);if (do_acct)
@@ -230,7 +236,7 @@ static void pmem_submit_bio(struct bio *if (do_acct)bio_end_io_acct (bio, start); -if (bio->bi_opf &REQ_FUA ) +if ((bio->bi_opf &REQ_FUA ) && !bio->bi_status) ret =nvdimm_flush (nd_region, bio);if (ret)
Greg Kroah-Hartman
maintainerPATCH 650/877 nvdimm: virtio_pmem: stop allocating child flush bio
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit 40f356e610df95728074b1fc2e2ccb54ca1b5659 ]
pmem_submit_bio() passes the parent bio to nvdimm_flush() for REQ_FUA. For virtio-pmem this makes async_pmem_flush() allocate and submit a child PREFLUSH bio chained to the parent.
That child allocation is in the block submit path. Making it blocking with GFP_NOIO can consume the same global bio mempool that submit_bio() uses, while making it GFP_ATOMIC can fail under pressure. A forced failure of the child allocation produced:
virtio_pmem: forcing child bio allocation failure for test Buffer I/O error on dev pmem0, logical block 0, lost sync page write EXT4-fs (pmem0): I/O error while writing superblock EXT4-fs (pmem0): mount failed
Avoid the child bio without turning REQ_FUA into a synchronous submit-path wait. Let provider flush callbacks return NVDIMM_FLUSH_ASYNC after taking ownership of parent bio completion. pmem_submit_bio() returns in that case, and virtio-pmem queues an ordered WQ_MEM_RECLAIM work item that runs the existing host flush path and completes the parent bio.
This keeps the asynchronous completion model of the child-bio path while removing the child bio allocation from the submit path.
Message-ID: <[email protected]>
Backport notes for 6.12:
Drop the freeze callback hunk: this tree does not have the upstream virtio-pmem freeze/restore callbacks. Keep the workqueue allocation, probe error cleanup, and removal drain without adding those callbacks.
Use the available kmalloc_obj() helper for the existing request allocation, matching upstream without changing its GFP_KERNEL behavior. This keeps the following GFP_NOIO dependency applicable. Correct the existing "repsonse" comment typo to match the context of the wait-flag dependency. The remaining request-wakeup and wait-flag dependencies are still needed before the refcount target.
Stable-dep-of: e57140944b5a ("nvdimm: virtio_pmem: refcount requests for token lifetime")
--- drivers/nvdimm/nd_virtio.c | 58 +++++++++++++++++++++++++++++-------------- drivers/nvdimm/pmem.c | 5 ++- drivers/nvdimm/region_devs.c | 2 + drivers/nvdimm/virtio_pmem.c | 14 +++++++++- drivers/nvdimm/virtio_pmem.h | 4 ++ include/linux/libnvdimm.h | 9 ++++++ 6 files changed, 72 insertions(+), 20 deletions(-)
drivers/nvdimm/nd_virtio.c +40 -18
@@ -9,6 +9,12 @@#include "virtio_pmem.h" #include "nd.h" +struct virtio_pmem_flush_work { +struct work_struct work; +struct nd_region *nd_region; +struct bio *bio; +}; +/* The interrupt handler */ void virtio_pmem_host_ack (struct virtqueue *vq) {
@@ -55,7 +61,7 @@ static int virtio_pmem_flush(struct nd_rreturn -EIO ; } - req_data =kmalloc (sizeof (*req_data),GFP_KERNEL ); + req_data =kmalloc_obj (*req_data);if (!req_data)return -ENOMEM ;
@@ -98,7 +104,7 @@ static int virtio_pmem_flush(struct nd_rdev_info (&vdev->dev,"failed to send command to virtio pmem device\n" ); err = -EIO ; }else { -/* A host repsonse results in "host_ack" getting called */ +/* A host response results in "host_ack" getting called */ wait_event (req_data->host_acked, req_data->done); err =le32_to_cpu (req_data->resp.ret); }
@@ -107,30 +113,46 @@ static int virtio_pmem_flush(struct nd_rreturn err; }; +static void virtio_pmem_flush_work (struct work_struct *work) +{ +struct virtio_pmem_flush_work *flush; +int err; + + flush = container_of(work, struct virtio_pmem_flush_work, work); + err =virtio_pmem_flush (flush->nd_region); +if (err >0 ) + err = -EIO ; +if (err) + flush->bio->bi_status =errno_to_blk_status (err); +bio_endio (flush->bio); +kfree (flush); +} +/* The asynchronous flush callback function */ int async_pmem_flush (struct nd_region *nd_region,struct bio *bio) { -/* -* Create child bio for asynchronous flush and chain with -* parent bio. Otherwise directly call nd_region flush. -*/ -if (bio && bio->bi_iter.bi_sector !=-1 ) { -struct bio *child =bio_alloc (bio->bi_bdev,0 , -REQ_OP_WRITE |REQ_PREFLUSH , -GFP_ATOMIC ); +struct virtio_device *vdev = nd_region->provider_data; +struct virtio_pmem *vpmem = vdev->priv; +struct virtio_pmem_flush_work *flush; +int err; -if (!child) +if (bio && bio->bi_iter.bi_sector !=-1 ) { + flush =kmalloc_obj (*flush,GFP_NOIO ); +if (!flush)return -ENOMEM ; -bio_clone_blkg_association (child, bio); - child->bi_iter.bi_sector =-1 ; -bio_chain (child, bio); -submit_bio (child); -return 0 ; + +INIT_WORK (&flush->work, virtio_pmem_flush_work); + flush->nd_region = nd_region; + flush->bio = bio; +queue_work (vpmem->flush_wq, &flush->work); +return NVDIMM_FLUSH_ASYNC ; } -if (virtio_pmem_flush (nd_region)) + + err =virtio_pmem_flush (nd_region); +if (err >0 )return -EIO ; -return 0 ; +return err; };EXPORT_SYMBOL_GPL (async_pmem_flush);MODULE_DESCRIPTION ("Virtio Persistent Memory Driver" );
drivers/nvdimm/pmem.c +4 -1
@@ -236,8 +236,11 @@ static void pmem_submit_bio(struct bio *if (do_acct)bio_end_io_acct (bio, start); -if ((bio->bi_opf &REQ_FUA ) && !bio->bi_status) +if ((bio->bi_opf &REQ_FUA ) && !bio->bi_status) { ret =nvdimm_flush (nd_region, bio); +if (ret ==NVDIMM_FLUSH_ASYNC ) +return ; + }if (ret) bio->bi_status =errno_to_blk_status (ret);
drivers/nvdimm/region_devs.c +2 -0
@@ -1113,6 +1113,8 @@ int nvdimm_flush(struct nd_region *nd_re rc =generic_nvdimm_flush (nd_region); else { rc = nd_region->flush (nd_region, bio); +if (rc >0 ) +return rc;if (rc && rc != -ENOMEM ) rc = -EIO ; }
drivers/nvdimm/virtio_pmem.c +13 -1
@@ -67,10 +67,17 @@ static int virtio_pmem_probe(struct virtmutex_init (&vpmem->flush_lock); vpmem->vdev = vdev; vdev->priv = vpmem; + vpmem->flush_wq =alloc_ordered_workqueue ("virtio-pmem-flush" , +WQ_MEM_RECLAIM ); +if (!vpmem->flush_wq) { + err = -ENOMEM ; + goto out_err; + } + err =init_vq (vpmem);if (err) {dev_err (&vdev->dev,"failed to initialize virtio pmem vq's\n" ); - goto out_err; + goto out_wq; }if (virtio_has_feature (vdev,VIRTIO_PMEM_F_SHMEM_REGION )) {
@@ -131,6 +138,8 @@ out_nd:nvdimm_bus_unregister (vpmem->nvdimm_bus); out_vq: vdev->config->del_vqs (vdev); +out_wq: +destroy_workqueue (vpmem->flush_wq); out_err:return err; }
@@ -138,10 +147,13 @@ out_err:static void virtio_pmem_remove (struct virtio_device *vdev) {struct nvdimm_bus *nvdimm_bus =dev_get_drvdata (&vdev->dev); +struct virtio_pmem *vpmem = vdev->priv;nvdimm_bus_unregister (nvdimm_bus); +drain_workqueue (vpmem->flush_wq); vdev->config->del_vqs (vdev);virtio_reset_device (vdev); +destroy_workqueue (vpmem->flush_wq); }static unsigned int features[] = {
drivers/nvdimm/virtio_pmem.h +4 -0
@@ -15,6 +15,7 @@#include <linux/libnvdimm.h> #include <linux/mutex.h> #include <linux/spinlock.h> +#include <linux/workqueue.h> struct virtio_pmem_request {struct virtio_pmem_req req;
@@ -39,6 +40,9 @@ struct virtio_pmem {/* Serialize flush requests to the device. */ struct mutex flush_lock; +/* Complete asynchronous FUA flushes outside the submit path. */ +struct workqueue_struct *flush_wq; +/* nvdimm bus registers virtio pmem device */ struct nvdimm_bus *nvdimm_bus;struct nvdimm_bus_descriptor nd_desc;
include/linux/libnvdimm.h +9 -0
@@ -122,6 +122,15 @@ struct nd_mapping_desc { };struct nd_region ; + +/* +* Provider flush callback return values: +* 0: flush completed synchronously +* <0: flush failed +* >0: flush completion was queued and @bio will be completed later +*/ +#define NVDIMM_FLUSH_ASYNC 1 +struct nd_region_desc {struct resource *res;struct nd_mapping_desc *mapping;
Greg Kroah-Hartman
maintainerPATCH 651/877 nvdimm: virtio_pmem: always wake -ENOSPC waiters
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit 811808761e19fdea1c25b7c76734b8945f758f27 ]
virtio_pmem_host_ack() reclaims virtqueue descriptors with virtqueue_get_buf(). The -ENOSPC waiter wakeup is tied to completing the returned token. If token completion is skipped for any reason, reclaimed descriptors may not wake a waiter and the submitter may sleep forever waiting for a free slot. Always wake one -ENOSPC waiter for each virtqueue completion before touching the returned token.
Message-ID: <[email protected]>
Stable-dep-of: e57140944b5a ("nvdimm: virtio_pmem: refcount requests for token lifetime")
--- drivers/nvdimm/nd_virtio.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-)
drivers/nvdimm/nd_virtio.c +16 -9
@@ -15,26 +15,33 @@ struct virtio_pmem_flush_work {struct bio *bio; }; +static void virtio_pmem_wake_one_waiter (struct virtio_pmem *vpmem) +{ +struct virtio_pmem_request *req_buf; + +if (list_empty (&vpmem->req_list)) +return ; + + req_buf =list_first_entry (&vpmem->req_list, + struct virtio_pmem_request, list); + req_buf->wq_buf_avail = true; +wake_up (&req_buf->wq_buf); +list_del (&req_buf->list); +} +/* The interrupt handler */ void virtio_pmem_host_ack (struct virtqueue *vq) {struct virtio_pmem *vpmem = vq->vdev->priv; -struct virtio_pmem_request *req_data, *req_buf; +struct virtio_pmem_request *req_data;unsigned long flags;unsigned int len;spin_lock_irqsave (&vpmem->pmem_lock, flags);while ((req_data =virtqueue_get_buf (vq, &len)) !=NULL ) { +virtio_pmem_wake_one_waiter (vpmem); req_data->done = true;wake_up (&req_data->host_acked); - -if (!list_empty (&vpmem->req_list)) { - req_buf =list_first_entry (&vpmem->req_list, - struct virtio_pmem_request, list); - req_buf->wq_buf_avail = true; -wake_up (&req_buf->wq_buf); -list_del (&req_buf->list); - } }spin_unlock_irqrestore (&vpmem->pmem_lock, flags); }
Greg Kroah-Hartman
maintainerPATCH 652/877 nvdimm: virtio_pmem: use READ_ONCE()/WRITE_ONCE() for wait flags
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit 08e72a5ba1ab9dc0adf993ff0f4d606a1e3445a8 ]
Use READ_ONCE()/WRITE_ONCE() for the wait_event() flags (done and wq_buf_avail). They are observed by waiters without pmem_lock, so make the accesses explicit single loads/stores and avoid compiler reordering/caching across the wait/wake paths.
Message-ID: <[email protected]>
Stable-dep-of: e57140944b5a ("nvdimm: virtio_pmem: refcount requests for token lifetime")
--- drivers/nvdimm/nd_virtio.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
drivers/nvdimm/nd_virtio.c +7 -7
@@ -24,9 +24,9 @@ static void virtio_pmem_wake_one_waiter( req_buf =list_first_entry (&vpmem->req_list, struct virtio_pmem_request, list); - req_buf->wq_buf_avail = true; +list_del_init (&req_buf->list); +WRITE_ONCE (req_buf->wq_buf_avail, true);wake_up (&req_buf->wq_buf); -list_del (&req_buf->list); }/* The interrupt handler */
@@ -40,7 +40,7 @@ void virtio_pmem_host_ack(struct virtquespin_lock_irqsave (&vpmem->pmem_lock, flags);while ((req_data =virtqueue_get_buf (vq, &len)) !=NULL ) {virtio_pmem_wake_one_waiter (vpmem); - req_data->done = true; +WRITE_ONCE (req_data->done, true);wake_up (&req_data->host_acked); }spin_unlock_irqrestore (&vpmem->pmem_lock, flags);
@@ -72,7 +72,7 @@ static int virtio_pmem_flush(struct nd_rif (!req_data)return -ENOMEM ; - req_data->done = false; +WRITE_ONCE (req_data->done, false);init_waitqueue_head (&req_data->host_acked);init_waitqueue_head (&req_data->wq_buf);INIT_LIST_HEAD (&req_data->list);
@@ -93,12 +93,12 @@ static int virtio_pmem_flush(struct nd_r GFP_ATOMIC)) == -ENOSPC) {dev_info (&vdev->dev,"failed to send command to virtio pmem device, no free slots in the virtqueue\n" ); - req_data->wq_buf_avail = false; +WRITE_ONCE (req_data->wq_buf_avail, false);list_add_tail (&req_data->list, &vpmem->req_list);spin_unlock_irqrestore (&vpmem->pmem_lock, flags);/* A host response results in "host_ack" getting called */ -wait_event (req_data->wq_buf, req_data->wq_buf_avail); +wait_event (req_data->wq_buf,READ_ONCE (req_data->wq_buf_avail));spin_lock_irqsave (&vpmem->pmem_lock, flags); } err1 =virtqueue_kick (vpmem->req_vq);
@@ -112,7 +112,7 @@ static int virtio_pmem_flush(struct nd_r err = -EIO ; }else {/* A host response results in "host_ack" getting called */ -wait_event (req_data->host_acked, req_data->done); +wait_event (req_data->host_acked,READ_ONCE (req_data->done)); err =le32_to_cpu (req_data->resp.ret); }
Greg Kroah-Hartman
maintainerPATCH 653/877 nvdimm: virtio_pmem: refcount requests for token lifetime
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Li Chen <[email protected]>
[ Upstream commit e57140944b5a47a7fd5a142faab29a02af040bc8 ]
KASAN reports slab-use-after-free in __wake_up_common():
BUG: KASAN: slab-use-after-free in __wake_up_common+0x114/0x160 Read of size 8 at addr ffff88810fdcb710 by task swapper/0/0 CPU: 0 UID: 0 PID: 0 Comm: swapper/0 Not tainted 6.19.0-next-20260220-00006-g1eae5f204ec3 #4 PREEMPT(full) Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Arch Linux 1.17.0-2-2 04/01/2014 Call Trace: <IRQ> dump_stack_lvl+0x6d/0xb0 print_report+0x170/0x4e2 ? __pfx__raw_spin_lock_irqsave+0x10/0x10 ? __virt_addr_valid+0x1dc/0x380 kasan_report+0xbc/0xf0 ? __wake_up_common+0x114/0x160 ? __wake_up_common+0x114/0x160 __wake_up_common+0x114/0x160 ? __pfx__raw_spin_lock_irqsave+0x10/0x10 __wake_up+0x36/0x60 virtio_pmem_host_ack+0x11d/0x3b0 ? sched_balance_domains+0x29f/0xb00 ? __pfx_virtio_pmem_host_ack+0x10/0x10 ? _raw_spin_lock_irqsave+0x98/0x100 ? __pfx__raw_spin_lock_irqsave+0x10/0x10 vring_interrupt+0x1c9/0x5e0 ? __pfx_vp_interrupt+0x10/0x10 vp_vring_interrupt+0x87/0x100 ? __pfx_vp_interrupt+0x10/0x10 __handle_irq_event_percpu+0x17f/0x550 ? __pfx__raw_spin_lock+0x10/0x10 handle_irq_event+0xab/0x1c0 handle_fasteoi_irq+0x276/0xae0 __common_interrupt+0x65/0x130 common_interrupt+0x78/0xa0 </IRQ>
virtio_pmem_host_ack() wakes a request that has already been freed by the submitter.
This happens when the request token is still reachable via the virtqueue, but virtio_pmem_flush() returns and frees it.
Fix the token lifetime by refcounting struct virtio_pmem_request. virtio_pmem_flush() holds a submitter reference, and the virtqueue holds an extra reference once the request is queued. The completion path drops the virtqueue reference, and the submitter drops its reference before returning.
Message-ID: <[email protected]>
--- drivers/nvdimm/nd_virtio.c | 32 ++++++++++++++++++++++++++++---- drivers/nvdimm/virtio_pmem.h | 2 ++ 2 files changed, 30 insertions(+), 4 deletions(-)
drivers/nvdimm/nd_virtio.c +28 -4
@@ -15,6 +15,14 @@ struct virtio_pmem_flush_work {struct bio *bio; }; +static void virtio_pmem_req_release (struct kref *kref) +{ +struct virtio_pmem_request *req; + + req = container_of(kref, struct virtio_pmem_request, kref); +kfree (req); +} +static void virtio_pmem_wake_one_waiter (struct virtio_pmem *vpmem) {struct virtio_pmem_request *req_buf;
@@ -42,6 +50,7 @@ void virtio_pmem_host_ack(struct virtquevirtio_pmem_wake_one_waiter (vpmem);WRITE_ONCE (req_data->done, true);wake_up (&req_data->host_acked); +kref_put (&req_data->kref, virtio_pmem_req_release); }spin_unlock_irqrestore (&vpmem->pmem_lock, flags); }
@@ -72,6 +81,7 @@ static int virtio_pmem_flush(struct nd_rif (!req_data)return -ENOMEM ; +kref_init (&req_data->kref);WRITE_ONCE (req_data->done, false);init_waitqueue_head (&req_data->host_acked);init_waitqueue_head (&req_data->wq_buf);
@@ -89,10 +99,23 @@ static int virtio_pmem_flush(struct nd_r* to req_list and wait for host_ack to wake us up when free * slots are available. */ -while ((err =virtqueue_add_sgs (vpmem->req_vq, sgs,1 ,1 , req_data, -GFP_ATOMIC )) == -ENOSPC ) { +for (;;) { + err =virtqueue_add_sgs (vpmem->req_vq, sgs,1 ,1 , req_data, +GFP_ATOMIC ); +if (!err) { +/* +* Take the virtqueue reference while @pmem_lock is +* held so completion cannot run concurrently. +*/ +kref_get (&req_data->kref); +break ; + } + +if (err != -ENOSPC ) +break ; -dev_info (&vdev->dev,"failed to send command to virtio pmem device, no free slots in the virtqueue\n" ); +dev_info_ratelimited (&vdev->dev, +"failed to send command to virtio pmem device, no free slots in the virtqueue\n" );WRITE_ONCE (req_data->wq_buf_avail, false);list_add_tail (&req_data->list, &vpmem->req_list);spin_unlock_irqrestore (&vpmem->pmem_lock, flags);
@@ -101,6 +124,7 @@ static int virtio_pmem_flush(struct nd_rwait_event (req_data->wq_buf,READ_ONCE (req_data->wq_buf_avail));spin_lock_irqsave (&vpmem->pmem_lock, flags); } + err1 =virtqueue_kick (vpmem->req_vq);spin_unlock_irqrestore (&vpmem->pmem_lock, flags);/*
@@ -116,7 +140,7 @@ static int virtio_pmem_flush(struct nd_r err =le32_to_cpu (req_data->resp.ret); } -kfree (req_data); +kref_put (&req_data->kref, virtio_pmem_req_release);return err; };
drivers/nvdimm/virtio_pmem.h +2 -0
@@ -12,12 +12,14 @@#include <linux/module.h> #include <uapi/linux/virtio_pmem.h> +#include <linux/kref.h> #include <linux/libnvdimm.h> #include <linux/mutex.h> #include <linux/spinlock.h> #include <linux/workqueue.h> struct virtio_pmem_request { +struct kref kref;struct virtio_pmem_req req;struct virtio_pmem_resp resp;
Greg Kroah-Hartman
maintainerPATCH 654/877 mtd: rawnand: pl353: Add message about ECC mode
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Andrea Scian <[email protected]>
[ Upstream commit 1e06dbfdfb851170b243d6498e442b449324c664 ]
This just add some information on kernel log about the selected ECC
Stable-dep-of: 80ecacd054ff ("mtd: rawnand: pl353: Make sure we use the monolithic helpers for raw accesses")
--- drivers/mtd/nand/raw/pl35x-nand-controller.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/mtd/nand/raw/pl35x-nand-controller.c +3 -0
@@ -973,15 +973,18 @@ static int pl35x_nand_attach_chip(structswitch (chip->ecc.engine_type) {case NAND_ECC_ENGINE_TYPE_ON_DIE : +dev_dbg (nfc->dev,"Using on-die ECC\n" );/* Keep these legacy BBT descriptors for ON_DIE situations */ chip->bbt_td = &bbt_main_descr; chip->bbt_md = &bbt_mirror_descr; fallthrough;case NAND_ECC_ENGINE_TYPE_NONE :case NAND_ECC_ENGINE_TYPE_SOFT : +dev_dbg (nfc->dev,"Using software ECC (Hamming 1-bit/512B)\n" ); chip->ecc.write_page_raw = nand_monolithic_write_page_raw;break ;case NAND_ECC_ENGINE_TYPE_ON_HOST : +dev_dbg (nfc->dev,"Using hardware ECC\n" ); ret =pl35x_nand_init_hw_ecc_controller (nfc, chip);if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 655/877 mtd: rawnand: pl353: Make sure we use the monolithic helpers for raw accesses
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: "Miquel Raynal (DAVE)" <[email protected]>
[ Upstream commit 80ecacd054ffeb60cd28e46ed5cd6bd0d2de318b ]
Any access not using the hardware ECC engine should be monolithic because the controller has its very own way of handling the end of a transaction during operation configuration, so we cannot easily make repeated reads.
This has the side effect of fixing support for software ECC engines.
--- drivers/mtd/nand/raw/pl35x-nand-controller.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/mtd/nand/raw/pl35x-nand-controller.c +3 -2
@@ -914,7 +914,6 @@ static int pl35x_nand_init_hw_ecc_contro chip->ecc.steps = mtd->writesize / chip->ecc.size; chip->ecc.read_page = pl35x_nand_read_page_hwecc; chip->ecc.write_page = pl35x_nand_write_page_hwecc; - chip->ecc.write_page_raw = nand_monolithic_write_page_raw;pl35x_smc_set_ecc_pg_size (nfc, chip, mtd->writesize); nfc->ecc_buf = devm_kmalloc(nfc->dev, chip->ecc.bytes * chip->ecc.steps,
@@ -981,7 +980,6 @@ static int pl35x_nand_attach_chip(structcase NAND_ECC_ENGINE_TYPE_NONE :case NAND_ECC_ENGINE_TYPE_SOFT :dev_dbg (nfc->dev,"Using software ECC (Hamming 1-bit/512B)\n" ); - chip->ecc.write_page_raw = nand_monolithic_write_page_raw;break ;case NAND_ECC_ENGINE_TYPE_ON_HOST :dev_dbg (nfc->dev,"Using hardware ECC\n" );
@@ -995,6 +993,9 @@ static int pl35x_nand_attach_chip(structreturn -EINVAL ; } + chip->ecc.read_page_raw = nand_monolithic_read_page_raw; + chip->ecc.write_page_raw = nand_monolithic_write_page_raw; +return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 656/877 clk: qcom: Fix test_ctl_hi field for DEFAULT_EVO PLLs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Imran Shaik <[email protected]>
[ Upstream commit 830ead322c39c99bf972425b3c35323ec56c29de ]
CLK_ALPHA_PLL_TYPE_DEFAULT_EVO type PLLs do not have the PLL_TEST_CTL_U1 register, so clk_alpha_pll_configure() does not program test_ctl_hi1_val for this PLL type.
The GCC PLL configurations for QCM2290, Shikra and SM6115 wrongly use test_ctl_hi1_val instead of test_ctl_hi_val, deviating from the hardware recommended settings. Fix them to use test_ctl_hi_val.
--- drivers/clk/qcom/gcc-qcm2290.c | 6 +++--- drivers/clk/qcom/gcc-sm6115.c | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-)
drivers/clk/qcom/gcc-qcm2290.c +3 -3
@@ -116,7 +116,7 @@ static const struct alpha_pll_config gpl .vco_mask = GENMASK(21, 20), .main_output_mask = BIT(0), .config_ctl_val = 0x4001055B, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, };static struct clk_alpha_pll gpll10 = {
@@ -148,7 +148,7 @@ static const struct alpha_pll_config gpl .vco_mask = GENMASK(21, 20), .main_output_mask = BIT(0), .config_ctl_val = 0x4001055B, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, };static struct clk_alpha_pll gpll11 = {
@@ -309,7 +309,7 @@ static const struct alpha_pll_config gpl .post_div_val = 0x1 << 8, .post_div_mask = GENMASK(11, 8), .config_ctl_val = 0x4001055B, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, };static struct clk_alpha_pll gpll8 = {
drivers/clk/qcom/gcc-sm6115.c +3 -3
@@ -120,7 +120,7 @@ static const struct alpha_pll_config gpl .vco_mask = GENMASK(21, 20), .main_output_mask = BIT(0), .config_ctl_val = 0x4001055b, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, .test_ctl_hi_mask = 0x1, };
@@ -173,7 +173,7 @@ static const struct alpha_pll_config gpl .vco_val = 0x2 << 20, .vco_mask = GENMASK(21, 20), .config_ctl_val = 0x4001055b, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, .test_ctl_hi_mask = 0x1, };
@@ -367,7 +367,7 @@ static const struct alpha_pll_config gpl .post_div_val = 0x1 << 8, .post_div_mask = GENMASK(11, 8), .config_ctl_val = 0x4001055b, - .test_ctl_hi1_val = 0x1, + .test_ctl_hi_val = 0x1, .test_ctl_hi_mask = 0x1, };
Greg Kroah-Hartman
maintainerPATCH 657/877 ASoC: tegra210_mixer: sort the register default table
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Peter Ujfalusi <[email protected]>
[ Upstream commit f70bc276fc7f712ff5c8e995d5050558a3198df2 ]
reg_defaults must be sorted by ascending register address, as regcache_lookup_reg() locates entries in it with bsearch(). See commit fd80df352ba1 ("regcache: Add support for sorting defaults arrays").
TEGRA210_MIXER_ENABLE (0x400) is the last entry of the table, after TEGRA210_MIXER_PEAKM_RAM_CTRL (0x434), which makes it unreachable. regcache_reg_needs_sync() then cannot compare it against its default and reports that a sync is needed, so it is written to the device on every regcache_sync() even when it was never touched.
Sort the table by register address.
Stable-dep-of: 5442b8093a2f ("ASoC: tegra: Fix the MIXER enable default value")
--- sound/soc/tegra/tegra210_mixer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
sound/soc/tegra/tegra210_mixer.c +1 -1
@@ -57,10 +57,10 @@ static const struct reg_default tegra210MIXER_TX_REG_DEFAULTS (3 ),MIXER_TX_REG_DEFAULTS (4 ), + { TEGRA210_MIXER_ENABLE, 0x1 }, { TEGRA210_MIXER_CG, 0x00000001}, { TEGRA210_MIXER_GAIN_CFG_RAM_CTRL, 0x00004000}, { TEGRA210_MIXER_PEAKM_RAM_CTRL, 0x00004000}, - { TEGRA210_MIXER_ENABLE, 0x1 }, };/* Default gain parameters */
Greg Kroah-Hartman
maintainerPATCH 658/877 ASoC: tegra: Fix the MIXER enable default value
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jon Hunter <[email protected]>
[ Upstream commit 5442b8093a2f94ecd4696b3875194be09e2676c5 ]
Commit 4b05ccb17f92 ("regcache: Sort the local copy of an unsorted reg_defaults array") exposed an issue in the Tegra MIXER driver where the register default for the TEGRA210_MIXER_ENABLE is specified as 1, but the hardware default is actually 0. After this commit was added the MIXER driver is no longer working and so fix this by correcting the default value for this register and explicitly configuring the MIXER_ENABLE register when runtime resuming the MIXER device.
--- sound/soc/tegra/tegra210_mixer.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
sound/soc/tegra/tegra210_mixer.c +7 -3
@@ -57,7 +57,7 @@ static const struct reg_default tegra210MIXER_TX_REG_DEFAULTS (3 ),MIXER_TX_REG_DEFAULTS (4 ), - { TEGRA210_MIXER_ENABLE, 0x1 }, + { TEGRA210_MIXER_ENABLE, 0x0 }, { TEGRA210_MIXER_CG, 0x00000001}, { TEGRA210_MIXER_GAIN_CFG_RAM_CTRL, 0x00004000}, { TEGRA210_MIXER_PEAKM_RAM_CTRL, 0x00004000},
@@ -86,11 +86,15 @@ static int __maybe_unused tegra210_mixerstatic int __maybe_unused tegra210_mixer_runtime_resume (struct device *dev) {struct tegra210_mixer *mixer =dev_get_drvdata (dev); +int err;regcache_cache_only (mixer->regmap, false); -regcache_sync (mixer->regmap); + err =regcache_sync (mixer->regmap); +if (err) +return err; -return 0 ; +return regmap_write (mixer->regmap,TEGRA210_MIXER_ENABLE , +TEGRA210_MIXER_EN ); } static int tegra210_mixer_write_ram(struct tegra210_mixer *mixer,
Greg Kroah-Hartman
maintainerPATCH 659/877 mm/mremap: reset unfaulted VMA page offset for MREMAP_DONTUNMAP
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 35b0fb391b0df57383bc15985bb769f4555c97ba ]
Uniquely an mremap() invocation using the MREMAP_DONTUNMAP flag can reset a faulted VMA into an unfaulted one.
It does so after the page tables have been moved to the copied VMA with MREMAP_DONTUNMAP leaving the old VMA in place which is naturally unfaulted as the page tables it had are no longer present.
However, in doing so, it violates the invariant that the anonymous page offset of an unfaulted VMA is vma->vm_start >> PAGE_SHIFT.
This is because a VMA may have been faulted in, mremap()'d (causing a delta between its page offset and vma->vm_start >> PAGE_SHIFT), and then mremap()'d again with MREMAP_DONTUNMAP resulting in the unfaulting.
This condition is a violation of a fundamental assumption in mm, but now also triggers an assert in assert_sane_pgoff() which explicitly checks for this condition.
Correct it by resetting the VMA's page offset at the point of completing the MREMAP_DONTUNMAP operation.
--- mm/mremap.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
mm/mremap.c +11 -1
@@ -811,8 +811,18 @@ static unsigned long move_vma(struct vm_* table has been moved. */ if (new_vma != vma && vma->vm_start == old_addr && - vma->vm_end == (old_addr + old_len)) + vma->vm_end == (old_addr + old_len)) { +const pgoff_t pgoff_unfaulted = vma->vm_start >>PAGE_SHIFT ; +unlink_anon_vmas (vma); +/* +* The VMA is now unfaulted and it is an invariant that +* unfaulted anonymous VMAs have page offset equal to +* vma->vm_start >> PAGE_SHIFT. +*/ +if (vma_is_anonymous (vma) && !vma->vm_file) + vma->vm_pgoff = pgoff_unfaulted; + }/* Because we won't unmap we don't need to touch locked_vm */ return new_addr;
Greg Kroah-Hartman
maintainerPATCH 660/877 KVM: x86/mmu: Dynamically allocate shadow MMUs hashed page list
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 039ef33e2f9346258fe2bd344f212c645942575e ]
Dynamically allocate the (massive) array of hashed lists used to track shadow pages, as the array itself is 32KiB, i.e. is an order-3 allocation all on its own, and is *exactly* an order-3 allocation. Dynamically allocating the array will allow allocating "struct kvm" using kvmalloc(), and will also allow deferring allocation of the array until it's actually needed, i.e. until the first shadow root is allocated.
Opportunistically use kvmalloc() for the hashed lists, as an order-3 allocation is (stating the obvious) less likely to fail than an order-4 allocation, and the overhead of vmalloc() is undesirable given that the size of the allocation is fixed.
Stable-dep-of: b27622c4eeb1 ("KVM: x86/mmu: Split kvm_mmu_zap_all_fast() into "front" and "back" halves")
--- arch/x86/include/asm/kvm_host.h | 4 ++-- arch/x86/kvm/mmu/mmu.c | 23 ++++++++++++++++++++++- arch/x86/kvm/x86.c | 5 ++++- 3 files changed, 28 insertions(+), 4 deletions(-)
arch/x86/include/asm/kvm_host.h +2 -2
@@ -1307,7 +1307,7 @@ struct kvm_arch {bool has_private_mem;bool has_protected_state;bool pre_fault_allowed; -struct hlist_head mmu_page_hash[KVM_NUM_MMU_PAGES ]; +struct hlist_head *mmu_page_hash;struct list_head active_mmu_pages;struct list_head zapped_obsolete_pages;/*
@@ -1954,7 +1954,7 @@ void kvm_mmu_vendor_module_exit(void);void kvm_mmu_destroy (struct kvm_vcpu *vcpu);int kvm_mmu_create (struct kvm_vcpu *vcpu); -void kvm_mmu_init_vm (struct kvm *kvm); +int kvm_mmu_init_vm (struct kvm *kvm);void kvm_mmu_uninit_vm (struct kvm *kvm); void kvm_mmu_init_memslot_memory_attributes(struct kvm *kvm,
arch/x86/kvm/mmu/mmu.c +22 -1
@@ -3772,6 +3772,18 @@ out_unlock:return r; } +static int kvm_mmu_alloc_page_hash (struct kvm *kvm) +{ +struct hlist_head *h; + + h =kvcalloc (KVM_NUM_MMU_PAGES ,sizeof (*h),GFP_KERNEL_ACCOUNT ); +if (!h) +return -ENOMEM ; + + kvm->arch.mmu_page_hash = h; +return 0 ; +} +static int mmu_first_shadow_root_alloc (struct kvm *kvm) {struct kvm_memslots *slots;
@@ -6542,14 +6554,20 @@ static bool kvm_has_zapped_obsolete_pagereturn unlikely (!list_empty_careful (&kvm->arch.zapped_obsolete_pages)); } -void kvm_mmu_init_vm (struct kvm *kvm) +int kvm_mmu_init_vm (struct kvm *kvm) { +int r; + kvm->arch.shadow_mmio_value = shadow_mmio_value;INIT_LIST_HEAD (&kvm->arch.active_mmu_pages);INIT_LIST_HEAD (&kvm->arch.zapped_obsolete_pages);INIT_LIST_HEAD (&kvm->arch.possible_nx_huge_pages);spin_lock_init (&kvm->arch.mmu_unsync_pages_lock); + r =kvm_mmu_alloc_page_hash (kvm); +if (r) +return r; +if (tdp_mmu_enabled)kvm_mmu_init_tdp_mmu (kvm);
@@ -6560,6 +6578,7 @@ void kvm_mmu_init_vm(struct kvm *kvm) kvm->arch.split_desc_cache.kmem_cache = pte_list_desc_cache; kvm->arch.split_desc_cache.gfp_zero = __GFP_ZERO; +return 0 ; }static void mmu_free_vm_memory_caches (struct kvm *kvm)
@@ -6571,6 +6590,8 @@ static void mmu_free_vm_memory_caches(stvoid kvm_mmu_uninit_vm (struct kvm *kvm) { +kvfree (kvm->arch.mmu_page_hash); +if (tdp_mmu_enabled)kvm_mmu_uninit_tdp_mmu (kvm);
arch/x86/kvm/x86.c +4 -1
@@ -12827,7 +12827,9 @@ int kvm_arch_init_vm(struct kvm *kvm, unif (ret) goto out; -kvm_mmu_init_vm (kvm); + ret =kvm_mmu_init_vm (kvm); +if (ret) + goto out_cleanup_page_track; ret =kvm_x86_call (vm_init)(kvm);if (ret)
@@ -12872,6 +12874,7 @@ int kvm_arch_init_vm(struct kvm *kvm, un out_uninit_mmu:kvm_mmu_uninit_vm (kvm); +out_cleanup_page_track:kvm_page_track_cleanup (kvm); out:return ret;
Greg Kroah-Hartman
maintainerPATCH 661/877 KVM: x86/mmu: Split kvm_mmu_zap_all_fast() into "front" and "back" halves
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit b27622c4eeb125814081baaefe9175191be5b94d ]
Split kvm_mmu_zap_all_fast() into a "front half" and a "back half", where the front half is everything that runs with mmu_lock held for write, and the back half is the code that runs outside of mmu_lock. This will allow putting more code inside kvm_arch_flush_shadow_memslot()'s critical section without having to take mmu_lock twice in quick succession.
No functional change intended.
--- arch/x86/kvm/mmu/mmu.c | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-)
arch/x86/kvm/mmu/mmu.c +25 -12
@@ -6489,20 +6489,11 @@ restart:kvm_mmu_commit_zap_page (kvm, &kvm->arch.zapped_obsolete_pages); } -/* -* Fast invalidate all shadow pages and use lock-break technique -* to zap obsolete pages. -* -* It's required when memslot is being deleted or VM is being -* destroyed, in these cases, we should ensure that KVM MMU does -* not use any resource of the being-deleted slot or all slots -* after calling the function. -*/ -static void kvm_mmu_zap_all_fast (struct kvm *kvm) +static void __kvm_mmu_zap_all_fast_front_half (struct kvm *kvm) {lockdep_assert_held (&kvm->slots_lock); +lockdep_assert_held_write (&kvm->mmu_lock); -write_lock (&kvm->mmu_lock);trace_kvm_mmu_zap_all_fast (kvm);/*
@@ -6534,8 +6525,12 @@ static void kvm_mmu_zap_all_fast(structkvm_make_all_cpus_request (kvm,KVM_REQ_MMU_FREE_OBSOLETE_ROOTS );kvm_zap_obsolete_pages (kvm); +} -write_unlock (&kvm->mmu_lock); +static void __kvm_mmu_zap_all_fast_back_half (struct kvm *kvm) +{ +lockdep_assert_held (&kvm->slots_lock); +lockdep_assert_not_held (&kvm->mmu_lock);/* * Zap the invalidated TDP MMU roots, all SPTEs must be dropped before
@@ -6554,6 +6549,24 @@ static bool kvm_has_zapped_obsolete_pagereturn unlikely (!list_empty_careful (&kvm->arch.zapped_obsolete_pages)); } +/* +* Fast invalidate all shadow pages and use lock-break technique +* to zap obsolete pages. +* +* It's required when memslot is being deleted or VM is being +* destroyed, in these cases, we should ensure that KVM MMU does +* not use any resource of the being-deleted slot or all slots +* after calling the function. +*/ +static void kvm_mmu_zap_all_fast (struct kvm *kvm) +{ +write_lock (&kvm->mmu_lock); +__kvm_mmu_zap_all_fast_front_half (kvm); +write_unlock (&kvm->mmu_lock); + +__kvm_mmu_zap_all_fast_back_half (kvm); +} +int kvm_mmu_init_vm (struct kvm *kvm) {int r;
Greg Kroah-Hartman
maintainerPATCH 662/877 KVM: x86: Extract REGS and SREGS runtime sync code to helpers
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 6a8a98aa9c147eb63f5a360f157f207bf46c05ee ]
Extract the REGS and SREGS portions of {store,sync}_regs() into separate helpers in anticipation of moving the register specific code out of x86.c and into regs.c.
No functional change intended.
Message-ID: <[email protected]>
Stable-dep-of: 184bd464bdb6 ("KVM: x86: Check EFER validity on KVM_SET_SREGS*")
--- arch/x86/kvm/x86.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +15 -2
@@ -12310,7 +12310,7 @@ int kvm_arch_vcpu_ioctl_set_fpu(struct kreturn 0 ; } -static void store_regs (struct kvm_vcpu *vcpu) +static void kvm_run_sync_regs_to_user (struct kvm_vcpu *vcpu) {BUILD_BUG_ON (sizeof (struct kvm_sync_regs ) >SYNC_REGS_SIZE_BYTES );
@@ -12319,13 +12319,18 @@ static void store_regs(struct kvm_vcpu *if (vcpu->run->kvm_valid_regs &KVM_SYNC_X86_SREGS )__get_sregs (vcpu, &vcpu->run->s.regs.sregs); +} + +static void store_regs (struct kvm_vcpu *vcpu) +{ +kvm_run_sync_regs_to_user (vcpu);if (vcpu->run->kvm_valid_regs &KVM_SYNC_X86_EVENTS )kvm_vcpu_ioctl_x86_get_vcpu_events ( vcpu, &vcpu->run->s.regs.events); } -static int sync_regs (struct kvm_vcpu *vcpu) +static int kvm_run_sync_regs_from_user (struct kvm_vcpu *vcpu) {if (vcpu->run->kvm_dirty_regs &KVM_SYNC_X86_REGS ) {__set_regs (vcpu, &vcpu->run->s.regs.regs);
@@ -12341,6 +12346,14 @@ static int sync_regs(struct kvm_vcpu *vc vcpu->run->kvm_dirty_regs &= ~KVM_SYNC_X86_SREGS ; } +return 0 ; +} + +static int sync_regs (struct kvm_vcpu *vcpu) +{ +if (kvm_run_sync_regs_from_user (vcpu)) +return -EINVAL ; +if (vcpu->run->kvm_dirty_regs &KVM_SYNC_X86_EVENTS ) {struct kvm_vcpu_events events = vcpu->run->s.regs.events;
Greg Kroah-Hartman
maintainerPATCH 663/877 KVM: x86: Rename __{g,s}et_sregs2() => kvm_vcpu_ioctl_x86_{g,s}et_sregs2()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit bd130c8d72a1c7dde5523b3f3fae9867eafaa1dc ]
Rename the KVM_{G,S}ET_SREGS2 helpers in anticipation of moving them out of x86.c (while leaving the ioctl dispatch behind). Having globally visible APIs named __{g,s}et_sregs2() would be "fine", but ugly, given that __{g,s}et_sregs() will NOT be globally visible. As a bonus, this makes it a bit more obvious that the helpers implement newer versions of kvm_arch_vcpu_ioctl_set_sregs().
No functional change intended.
Message-ID: <[email protected]>
Stable-dep-of: 184bd464bdb6 ("KVM: x86: Check EFER validity on KVM_SET_SREGS*")
--- arch/x86/kvm/x86.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
arch/x86/kvm/x86.c +10 -6
@@ -135,8 +135,10 @@ static void store_regs(struct kvm_vcpu *static int sync_regs (struct kvm_vcpu *vcpu);static int kvm_vcpu_do_singlestep (struct kvm_vcpu *vcpu); -static int __set_sregs2 (struct kvm_vcpu *vcpu,struct kvm_sregs2 *sregs2); -static void __get_sregs2 (struct kvm_vcpu *vcpu,struct kvm_sregs2 *sregs2); +static int kvm_vcpu_ioctl_x86_set_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2); +static void kvm_vcpu_ioctl_x86_get_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2);static DEFINE_MUTEX (vendor_module_lock);struct kvm_x86_ops kvm_x86_ops__read_mostly ;
@@ -6304,7 +6306,7 @@ long kvm_arch_vcpu_ioctl(struct file *fi r = -ENOMEM ;if (!u.sregs2) goto out; -__get_sregs2 (vcpu, u.sregs2); +kvm_vcpu_ioctl_x86_get_sregs2 (vcpu, u.sregs2); r = -EFAULT ;if (copy_to_user (argp, u.sregs2,sizeof (struct kvm_sregs2 ))) goto out;
@@ -6323,7 +6325,7 @@ long kvm_arch_vcpu_ioctl(struct file *fi u.sregs2 =NULL ; goto out; } - r =__set_sregs2 (vcpu, u.sregs2); + r =kvm_vcpu_ioctl_x86_set_sregs2 (vcpu, u.sregs2);break ; }case KVM_HAS_DEVICE_ATTR :
@@ -11845,7 +11847,8 @@ static void __get_sregs(struct kvm_vcpu (unsigned long *)sregs->interrupt_bitmap); } -static void __get_sregs2 (struct kvm_vcpu *vcpu,struct kvm_sregs2 *sregs2) +static void kvm_vcpu_ioctl_x86_get_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2) {int i;
@@ -12108,7 +12111,8 @@ static int __set_sregs(struct kvm_vcpu *return 0 ; } -static int __set_sregs2 (struct kvm_vcpu *vcpu,struct kvm_sregs2 *sregs2) +static int kvm_vcpu_ioctl_x86_set_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2) {int mmu_reset_needed =0 ;bool valid_pdptrs = sregs2->flags &KVM_SREGS2_FLAGS_PDPTRS_VALID ;
Greg Kroah-Hartman
maintainerPATCH 664/877 KVM: x86: Move the bulk of register specific code from x86.c to regs.c
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
[ Upstream commit 2f5bb3fe583510cf20f9d64aa73089577be3dc36 ]
Introduce regs.c, and move the vast majority of register specific code out of x86.c and into regs.c. Deliberately leave behind MSR code, as KVM's MSR support is complex enough to warrant its own compilation unit, and doesn't have much in common with the other register code.
Note, "struct kvm_sregs" has fields for EFER and MSR_IA32_APICBASE, and so the {G,S}ET_REGS flows technically contain a tiny amount of MSR code. MSR_IA32_APICBASE is already managed by lapic.c, and so doesn't require a "placement decision". As for EFER, leave all other EFER handling in x86.c (later to be moved to msrs.c). The primary interface to EFER, set_efer(), is very much MSR specific, even though EFER is arguably more of a Control Register than an MSR.
No functional change intended.
Message-ID: <[email protected]>
Backport to 6.12: move the existing stable register implementations instead of importing upstream versions that depend on newer MMU, APIC, register cache and symbol-export interfaces. Keep the stable Makefile objects and add regs.o. Use kvm_cache_regs.h and x86.h instead of introducing regs.h.
Move the existing kvm_pv_async_pf_enabled() and get_segment_base() helpers to x86.h for use by both compilation units, and expose the existing update_cr8_intercept() alongside the upstream cross-file declarations. Preserve all function bodies and exported symbols; no new functions are introduced. The resulting regs.c accepts the EFER validation fix in 184bd464bdb66daa9173670904f24c29c7b7f7d4 without changes.
[ sashal: Reduced backport -- upstream 2f5bb3fe58351 touches 5 file(s), this
backport carries 4. Not backported here:
arch/x86/kvm/regs.h
This note is generated from the file lists only; see the resolution record for the reasoning. ]
Stable-dep-of: 184bd464bdb6 ("KVM: x86: Check EFER validity on KVM_SET_SREGS*")
--- arch/x86/kvm/Makefile | 2 arch/x86/kvm/regs.c | 871 ++++++++++++++++++++++++++++++++++++++++++++++++ arch/x86/kvm/x86.c | 889 -------------------------------------------------- arch/x86/kvm/x86.h | 28 + 4 files changed, 903 insertions(+), 887 deletions(-) create mode 100644 arch/x86/kvm/regs.c
arch/x86/kvm/Makefile +1 -1
@@ -6,7 +6,7 @@ ccflags-$(CONFIG_KVM_WERROR) += -Werror include $(srctree)/virt/kvm/Makefile.kvm kvm-y += x86.o emulate.o i8259.o irq.o lapic.o \ - i8254.o ioapic.o irq_comm.o cpuid.o pmu.o mtrr.o \ + i8254.o ioapic.o irq_comm.o cpuid.o pmu.o regs.o mtrr.o \ debugfs.o mmu/mmu.o mmu/page_track.o \ mmu/spte.o
arch/x86/kvm/regs.c new file +871 -0
871 lines not on this page · raw message
arch/x86/kvm/x86.c +3 -886
972 lines not on this page · raw message
arch/x86/kvm/x86.h +28 -0
@@ -615,4 +615,32 @@ int kvm_sev_es_string_io(struct kvm_vcpu unsigned int port, void *data, unsigned int count, int in); +static inline bool kvm_pv_async_pf_enabled (struct kvm_vcpu *vcpu) +{ +u64 mask =KVM_ASYNC_PF_ENABLED |KVM_ASYNC_PF_DELIVERY_AS_INT ; + +return (vcpu->arch.apf.msr_en_val & mask) == mask; +} + +static inline unsigned long get_segment_base (struct kvm_vcpu *vcpu,int seg) +{ +return kvm_x86_call (get_segment_base)(vcpu, seg); +} + +void __kvm_set_rflags (struct kvm_vcpu *vcpu,unsigned long rflags); +void kvm_vcpu_ioctl_x86_get_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2); +int kvm_vcpu_ioctl_x86_set_sregs2 (struct kvm_vcpu *vcpu, +struct kvm_sregs2 *sregs2); +void kvm_run_sync_regs_to_user (struct kvm_vcpu *vcpu); +int kvm_run_sync_regs_from_user (struct kvm_vcpu *vcpu); +void kvm_update_dr0123 (struct kvm_vcpu *vcpu); +int kvm_vcpu_ioctl_x86_get_debugregs (struct kvm_vcpu *vcpu, +struct kvm_debugregs *dbgregs); +int kvm_vcpu_ioctl_x86_set_debugregs (struct kvm_vcpu *vcpu, +struct kvm_debugregs *dbgregs); +void kvm_invalidate_pcid (struct kvm_vcpu *vcpu,unsigned long pcid); +void kvm_handle_exception_payload_quirk (struct kvm_vcpu *vcpu); +void update_cr8_intercept (struct kvm_vcpu *vcpu); +#endif
Greg Kroah-Hartman
maintainerPATCH 665/877 KVM: x86: Check EFER validity on KVM_SET_SREGS*
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
[ Upstream commit 184bd464bdb66daa9173670904f24c29c7b7f7d4 ]
When handling userspace SREGS writes, check the validity of EFER (i.e. allowed bits) before writing the new value of EFER through the per-vendor set_efer callbacks. This prevents userspace from writing bogus values (e.g. EFER.SVME=1 with nested=0).
Note: on KVM_SET_MSRS, KVM only checks EFER validity in terms of KVM caps, not guest caps, so it is possible to set EFER bits that are supported by KVM but not by the guest CPUID. Potentially allowing userspace to set msrs before CPUID.
However, for KVM_SET_SREGS*, check the validity of the set bits against both KVM and guest caps. This is consistent with other validity checks (e.g. for CR4) that check validity against guest caps, which already imposes the need to set CPUID before SREGS.
--- arch/x86/kvm/regs.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/x86/kvm/regs.c +2 -1
@@ -556,7 +556,8 @@ static bool kvm_is_valid_sregs(struct kv }return kvm_is_valid_cr4 (vcpu, sregs->cr4) && -kvm_is_valid_cr0 (vcpu, sregs->cr0); +kvm_is_valid_cr0 (vcpu, sregs->cr0) && +kvm_valid_efer (vcpu, sregs->efer); } static int __set_sregs_common(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs,
Greg Kroah-Hartman
maintainerPATCH 666/877 media: i2c: imx355: Replace client->dev usage
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Laurent Pinchart <[email protected]>
[ Upstream commit 49c6ac166cf77cd53eeda69e8ccdcbe4a57a4fdf ]
The driver needs to access the struct device in many places, and retrieves it from the i2c_client itself retrieved with v4l2_get_subdevdata(). Store it as a pointer in struct imx355 and access it from there instead, to simplify the driver.
While at it, fix a mistake in the sort order of include statements.
Stable-dep-of: ee737bc3ccae ("media: imx355: Avoid calling imx355_power_off twice in error path")
--- drivers/media/i2c/imx355.c | 61 ++++++++++++++++++++++----------------------- 1 file changed, 30 insertions(+), 31 deletions(-)
drivers/media/i2c/imx355.c +30 -31
@@ -1,11 +1,12 @@// SPDX-License-Identifier: GPL-2.0 // Copyright (C) 2018 Intel Corporation -#include <linux/unaligned.h> #include <linux/acpi.h> #include <linux/i2c.h> #include <linux/module.h> #include <linux/pm_runtime.h> +#include <linux/unaligned.h> +#include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-event.h>
@@ -97,6 +98,8 @@ struct imx355_hwcfg { };struct imx355 { +struct device *dev; +struct v4l2_subdev sd;struct media_pad pad;
@@ -1136,14 +1139,13 @@ static int imx355_write_reg(struct imx35static int imx355_write_regs (struct imx355 *imx355,const struct imx355_reg *regs,u32 len) { -struct i2c_client *client =v4l2_get_subdevdata (&imx355->sd);int ret;u32 i;for (i =0 ; i < len; i++) { ret =imx355_write_reg (imx355, regs[i].address,1 , regs[i].val);if (ret) { -dev_err_ratelimited (&client->dev, +dev_err_ratelimited (imx355->dev,"write reg 0x%4.4x return err %d" , regs[i].address, ret);
@@ -1178,7 +1180,6 @@ static int imx355_set_ctrl(struct v4l2_c {struct imx355 *imx355 =container_of (ctrl->handler, struct imx355, ctrl_handler); -struct i2c_client *client =v4l2_get_subdevdata (&imx355->sd);s64 max;int ret;
@@ -1197,7 +1198,7 @@ static int imx355_set_ctrl(struct v4l2_c* Applying V4L2 control value only happens * when power is up for streaming */ -if (!pm_runtime_get_if_in_use (&client->dev)) +if (!pm_runtime_get_if_in_use (imx355->dev))return 0 ;switch (ctrl->id) {
@@ -1231,12 +1232,12 @@ static int imx355_set_ctrl(struct v4l2_cbreak ;default : ret = -EINVAL ; -dev_info (&client->dev,"ctrl(id:0x%x,val:0x%x) is not handled" , +dev_info (imx355->dev,"ctrl(id:0x%x,val:0x%x) is not handled" , ctrl->id, ctrl->val);break ; } -pm_runtime_put (&client->dev); +pm_runtime_put (imx355->dev);return ret; }
@@ -1385,7 +1386,6 @@ imx355_set_pad_format(struct v4l2_subdev/* Start streaming */ static int imx355_start_streaming (struct imx355 *imx355) { -struct i2c_client *client =v4l2_get_subdevdata (&imx355->sd);const struct imx355_reg_list *reg_list;int ret;
@@ -1393,7 +1393,7 @@ static int imx355_start_streaming(struct reg_list = &imx355_global_setting; ret =imx355_write_regs (imx355, reg_list->regs, reg_list->num_of_regs);if (ret) { -dev_err (&client->dev,"failed to set global settings" ); +dev_err (imx355->dev,"failed to set global settings" );return ret; }
@@ -1401,7 +1401,7 @@ static int imx355_start_streaming(struct reg_list = &imx355->cur_mode->reg_list; ret =imx355_write_regs (imx355, reg_list->regs, reg_list->num_of_regs);if (ret) { -dev_err (&client->dev,"failed to set mode" ); +dev_err (imx355->dev,"failed to set mode" );return ret; }
@@ -1429,13 +1429,12 @@ static int imx355_stop_streaming(structstatic int imx355_set_stream (struct v4l2_subdev *sd,int enable) {struct imx355 *imx355 =to_imx355 (sd); -struct i2c_client *client =v4l2_get_subdevdata (sd);int ret =0 ;mutex_lock (&imx355->mutex);if (enable) { - ret =pm_runtime_resume_and_get (&client->dev); + ret =pm_runtime_resume_and_get (imx355->dev);if (ret <0 ) goto err_unlock;
@@ -1448,7 +1447,7 @@ static int imx355_set_stream(struct v4l2 goto err_rpm_put; }else {imx355_stop_streaming (imx355); -pm_runtime_put (&client->dev); +pm_runtime_put (imx355->dev); }/* vflip and hflip cannot change during streaming */
@@ -1460,7 +1459,7 @@ static int imx355_set_stream(struct v4l2return ret; err_rpm_put: -pm_runtime_put (&client->dev); +pm_runtime_put (imx355->dev); err_unlock:mutex_unlock (&imx355->mutex);
@@ -1470,7 +1469,6 @@ err_unlock:/* Verify chip ID */ static int imx355_identify_module (struct imx355 *imx355) { -struct i2c_client *client =v4l2_get_subdevdata (&imx355->sd);int ret;u32 val;
@@ -1479,7 +1477,7 @@ static int imx355_identify_module(structreturn ret;if (val !=IMX355_CHIP_ID ) { -dev_err (&client->dev,"chip id mismatch: %x!=%x" , +dev_err (imx355->dev,"chip id mismatch: %x!=%x" ,IMX355_CHIP_ID , val);return -EIO ; }
@@ -1519,7 +1517,6 @@ static const struct v4l2_subdev_internal/* Initialize control handlers */ static int imx355_init_controls (struct imx355 *imx355) { -struct i2c_client *client =v4l2_get_subdevdata (&imx355->sd);struct v4l2_fwnode_device_properties props;struct v4l2_ctrl_handler *ctrl_hdlr;s64 exposure_max;
@@ -1600,11 +1597,11 @@ static int imx355_init_controls(struct i 0, 0, imx355_test_pattern_menu);if (ctrl_hdlr->error) { ret = ctrl_hdlr->error; -dev_err (&client->dev,"control init failed: %d" , ret); +dev_err (imx355->dev,"control init failed: %d" , ret); goto error; } - ret =v4l2_fwnode_device_parse (&client->dev, &props); + ret =v4l2_fwnode_device_parse (imx355->dev, &props);if (ret) goto error;
@@ -1689,6 +1686,8 @@ static int imx355_probe(struct i2c_clienif (!imx355)return -ENOMEM ; + imx355->dev = &client->dev; +mutex_init (&imx355->mutex);/* Initialize subdev */
@@ -1697,13 +1696,13 @@ static int imx355_probe(struct i2c_clien/* Check module identity */ ret =imx355_identify_module (imx355);if (ret) { -dev_err (&client->dev,"failed to find sensor: %d" , ret); +dev_err (imx355->dev,"failed to find sensor: %d" , ret); goto error_probe; } - imx355->hwcfg =imx355_get_hwcfg (&client->dev); + imx355->hwcfg =imx355_get_hwcfg (imx355->dev);if (!imx355->hwcfg) { -dev_err (&client->dev,"failed to get hwcfg" ); +dev_err (imx355->dev,"failed to get hwcfg" ); ret = -ENODEV ; goto error_probe; }
@@ -1713,7 +1712,7 @@ static int imx355_probe(struct i2c_clien ret =imx355_init_controls (imx355);if (ret) { -dev_err (&client->dev,"failed to init controls: %d" , ret); +dev_err (imx355->dev,"failed to init controls: %d" , ret); goto error_probe; }
@@ -1728,7 +1727,7 @@ static int imx355_probe(struct i2c_clien imx355->pad.flags =MEDIA_PAD_FL_SOURCE ; ret =media_entity_pads_init (&imx355->sd.entity,1 , &imx355->pad);if (ret) { -dev_err (&client->dev,"failed to init entity pads: %d" , ret); +dev_err (imx355->dev,"failed to init entity pads: %d" , ret); goto error_handler_free; }
@@ -1736,9 +1735,9 @@ static int imx355_probe(struct i2c_clien* Device is already turned on by i2c-core with ACPI domain PM. * Enable runtime PM and turn off the device. */ -pm_runtime_set_active (&client->dev); -pm_runtime_enable (&client->dev); -pm_runtime_idle (&client->dev); +pm_runtime_set_active (imx355->dev); +pm_runtime_enable (imx355->dev); +pm_runtime_idle (imx355->dev); ret =v4l2_async_register_subdev_sensor (&imx355->sd);if (ret <0 )
@@ -1747,8 +1746,8 @@ static int imx355_probe(struct i2c_clienreturn 0 ; error_media_entity_runtime_pm: -pm_runtime_disable (&client->dev); -pm_runtime_set_suspended (&client->dev); +pm_runtime_disable (imx355->dev); +pm_runtime_set_suspended (imx355->dev);media_entity_cleanup (&imx355->sd.entity); error_handler_free:
@@ -1769,8 +1768,8 @@ static void imx355_remove(struct i2c_climedia_entity_cleanup (&sd->entity);v4l2_ctrl_handler_free (sd->ctrl_handler); -pm_runtime_disable (&client->dev); -pm_runtime_set_suspended (&client->dev); +pm_runtime_disable (imx355->dev); +pm_runtime_set_suspended (imx355->dev);mutex_destroy (&imx355->mutex); }
Greg Kroah-Hartman
maintainerPATCH 667/877 media: imx355: Avoid calling imx355_power_off twice in error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Stevenson <[email protected]>
[ Upstream commit ee737bc3ccae7dc713ccaa83ffa46080c6031b3e ]
If v4l2_async_register_subdev_sensor failed, then the sensor had already been powered down by pm_runtime_idle, but the error path then also explicitly called imx355_power_off as well. That left an imbalance in the regulator and clock calls.
Call pm_runtime_idle only after v4l2_async_register_subdev_sensor succeeds to avoid this.
--- drivers/media/i2c/imx355.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/i2c/imx355.c +2 -1
@@ -1737,12 +1737,13 @@ static int imx355_probe(struct i2c_clien*/ pm_runtime_set_active (imx355->dev);pm_runtime_enable (imx355->dev); -pm_runtime_idle (imx355->dev); ret =v4l2_async_register_subdev_sensor (&imx355->sd);if (ret <0 ) goto error_media_entity_runtime_pm; +pm_runtime_idle (imx355->dev); +return 0 ; error_media_entity_runtime_pm:
Greg Kroah-Hartman
maintainerPATCH 668/877 media: rkvdec: Propagate platform_get_irq() errors
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Narasimharao Vadlamudi <[email protected]>
[ Upstream commit c37aca64206fafe938119e801a3fd10a537a051f ]
platform_get_irq() returns a positive IRQ number on success and a negative error code on failure. It no longer returns zero. The driver currently returns -ENXIO for all failures, which loses useful errors such as -EPROBE_DEFER.
Return the error from platform_get_irq() directly.
--- drivers/staging/media/rkvdec/rkvdec.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/staging/media/rkvdec/rkvdec.c +2 -2
@@ -1044,8 +1044,8 @@ static int rkvdec_probe(struct platform_vb2_dma_contig_set_max_seg_size (&pdev->dev,DMA_BIT_MASK (32 )); irq =platform_get_irq (pdev,0 ); -if (irq <=0 ) -return -ENXIO ; +if (irq <0 ) +return irq; ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, rkvdec_irq_handler, IRQF_ONESHOT,
Greg Kroah-Hartman
maintainerPATCH 669/877 KVM: s390: Zero initialize data structures for inject_pfault_token
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
[ Upstream commit 4e2c7f7cbc27418f9a290399b986c1b85ff93b90 ]
__kvm_inject_pfault_token() only sets .type and .u.ext.ext_params2 of the on-stack struct kvm_s390_irq but the full ext substructure is copied into the cpu local variable on inject. ext_params and pad contain stale stack values.
Interrupt delivery only uses ext_params2, so nothing leaks to the guest, but a host user can use the migration ioctls to get to the data.
Fix by zero-initializing the irq struct.
Do the same for the inti data structure.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/s390/kvm/kvm-s390.c +2 -2
@@ -4601,8 +4601,8 @@ long kvm_arch_fault_in_page(struct kvm_vstatic void __kvm_inject_pfault_token (struct kvm_vcpu *vcpu,bool start_token,unsigned long token) { -struct kvm_s390_interrupt inti; -struct kvm_s390_irq irq; +struct kvm_s390_interrupt inti = {}; +struct kvm_s390_irq irq = {};if (start_token) { irq.u.ext.ext_params2 = token;
Greg Kroah-Hartman
maintainerPATCH 670/877 KVM: x86: Disallow EFER.LME and EFER.LMA if long mode is not supported
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
[ Upstream commit e62392bf39ebfdf60d1d082799397fe1cbf8dfc5 ]
Remove EFER.LME and EFER.LMA from EFER reserved bits only if long mode is actually supported. KVM does check long-mode support before allowing the bits for guest writes and userspace writes through KVM_SET_SREGS* (in __kvm_valid_efer()), but userspace writes through KVM_SET_MSRS only check reserved bits.
In practice, this doesn't really matter. The true motiviation is getting rid of the #ifdeffery when initializing efer_reserved_bits.
--- arch/x86/kvm/x86.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-)
arch/x86/kvm/x86.c +4 -9
@@ -108,16 +108,8 @@ EXPORT_SYMBOL_GPL(kvm_host);#define emul_to_vcpu (ctxt) \ ((struct kvm_vcpu *)(ctxt)->vcpu) -/* EFER defaults: -* - enable syscall per default because its emulated by KVM -* - enable LME and LMA per default on 64 bit KVM -*/ -#ifdef CONFIG_X86_64 -static -u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE |EFER_LME |EFER_LMA )); -#else +/* Enable syscall by default because its emulated by KVM */ static u64 __read_mostly efer_reserved_bits = ~((u64 )EFER_SCE ); -#endif static u64 __read_mostly cr4_reserved_bits =CR4_RESERVED_BITS ;
@@ -9366,6 +9358,9 @@ int kvm_x86_vendor_init(struct kvm_x86_iif (r !=0 ) goto out_mmu_exit; +if (kvm_cpu_cap_has (X86_FEATURE_LM )) +kvm_enable_efer_bits (EFER_LME |EFER_LMA ); +kvm_ops_update (ops);for_each_online_cpu (cpu) {
Greg Kroah-Hartman
maintainerPATCH 671/877 scsi: qla2xxx: Zero dport diagnostics buffer to avoid info leak
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit a152edab3854f01dd2daf3eaf8f32cbabdb3834e ]
qla2x00_do_dport_diagnostics() allocates the qla_dport_diag response buffer with kmalloc_obj() (non-zeroing) and, on success, copies the full sizeof(*dd) back to user space via sg_copy_from_buffer(). The inbound sg_copy_to_buffer() only fills as many bytes as the user request payload provides, and qla26xx_dport_diagnostics() zeroes only dd->buf. The options and unused[] fields are therefore copied out uninitialized, leaking kernel heap contents to user space.
Allocate with kzalloc_obj(), matching qla2x00_do_dport_diagnostics_v2().
--- drivers/scsi/qla2xxx/qla_bsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/qla2xxx/qla_bsg.c +1 -1
@@ -2412,7 +2412,7 @@ qla2x00_do_dport_diagnostics(struct bsg_ !IS_QLA28XX(vha->hw))return -EPERM ; - dd =kmalloc (sizeof (*dd),GFP_KERNEL ); + dd =kzalloc (sizeof (*dd),GFP_KERNEL );if (!dd) {ql_log (ql_log_warn, vha,0x70db ,"Failed to allocate memory for dport.\n" );
Greg Kroah-Hartman
maintainerPATCH 672/877 scsi: qla2xxx: Fix queue teardown NULL dma_free and bitmap locking
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 34a40e0dff940ac5eba494a69b553ea571e24873 ]
qla25xx_free_req_que() and qla25xx_free_rsp_que() have two pre-existing bugs exposed on the error path of qla25xx_create_{req,rsp}_que():
1. When dma_alloc_coherent() fails during queue creation, the error path calls the free function with req->ring / rsp->ring still NULL (from kzalloc). The unconditional dma_free_coherent() with a NULL cpu_addr is undefined behavior and can panic.
2. The free functions clear req_qid_map / rsp_qid_map under vport_lock, but the create functions protect the same bitmaps with mq_lock. This provides no mutual exclusion. Additionally, the create error path clears the bit and releases mq_lock before calling the free function, creating a window where another thread can allocate the same que_id and have its ha->req_q_map entry clobbered by the subsequent lockless NULL assignment in the free function.
Fix by:
- Guarding dma_free_coherent() with a NULL check on the ring pointer.
- Using mq_lock (the lock held by all creators) in the free functions to atomically NULL the map entry and clear the bitmap bit.
- Removing the now-redundant clear_bit blocks from the create error paths since the free functions handle it atomically.
Backport adaptation for the stable tree: the 29xx IOCB size-selection helpers are absent, and queue creation still allocates fixed-size entries. Initialize the local req_entry_size and rsp_entry_size values with sizeof(request_t) and sizeof(response_t), respectively, so DMA freeing continues to match allocation without adding helper functions or 29xx support. Retain all NULL-ring guards, mq_lock protection, and removal of the premature bitmap clears.
Keep the response-ring cleanup layout used by upstream so target commit 19788a55cab61d78e33e0914a5a31d27843e8a4a applies unchanged.
Stable-dep-of: 19788a55cab6 ("scsi: qla2xxx: Fix use-after-free of qpair work on queue teardown")
--- drivers/scsi/qla2xxx/qla_mid.c | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-)
drivers/scsi/qla2xxx/qla_mid.c +15 -14
@@ -574,16 +574,19 @@ qla25xx_free_req_que(struct scsi_qla_hos {struct qla_hw_data *ha = vha->hw;uint16_t que_id = req->id; +size_t req_entry_size =sizeof (request_t); -dma_free_coherent (&ha->pdev->dev, (req->length +1 ) * -sizeof (request_t), req->ring, req->dma); +if (req->ring) +dma_free_coherent (&ha->pdev->dev, + (req->length +1 ) * req_entry_size, + req->ring, req->dma); req->ring =NULL ; req->dma =0 ;if (que_id) { +mutex_lock (&ha->mq_lock); ha->req_q_map[que_id] =NULL ; -mutex_lock (&ha->vport_lock);clear_bit (que_id, ha->req_qid_map); -mutex_unlock (&ha->vport_lock); +mutex_unlock (&ha->mq_lock); }kfree (req->outstanding_cmds);kfree (req);
@@ -594,6 +597,7 @@ qla25xx_free_rsp_que(struct scsi_qla_hos {struct qla_hw_data *ha = vha->hw;uint16_t que_id = rsp->id; +size_t rsp_entry_size =sizeof (response_t);if (rsp->msix && rsp->msix->have_irq) {free_irq (rsp->msix->vector, rsp->msix->handle);
@@ -601,15 +605,18 @@ qla25xx_free_rsp_que(struct scsi_qla_hos rsp->msix->in_use =0 ; rsp->msix->handle =NULL ; } -dma_free_coherent (&ha->pdev->dev, (rsp->length +1 ) * -sizeof (response_t), rsp->ring, rsp->dma); + +if (rsp->ring) +dma_free_coherent (&ha->pdev->dev, + (rsp->length +1 ) * rsp_entry_size, + rsp->ring, rsp->dma); rsp->ring =NULL ; rsp->dma =0 ;if (que_id) { +mutex_lock (&ha->mq_lock); ha->rsp_q_map[que_id] =NULL ; -mutex_lock (&ha->vport_lock);clear_bit (que_id, ha->rsp_qid_map); -mutex_unlock (&ha->vport_lock); +mutex_unlock (&ha->mq_lock); }kfree (rsp); }
@@ -794,9 +801,6 @@ qla25xx_create_req_que(struct qla_hw_datif (ret !=QLA_SUCCESS ) {ql_log (ql_log_fatal, base_vha,0x00df ,"%s failed.\n" , __func__); -mutex_lock (&ha->mq_lock); -clear_bit (que_id, ha->req_qid_map); -mutex_unlock (&ha->mq_lock); goto que_failed; } vha->flags.qpairs_req_created =1 ;
@@ -908,9 +912,6 @@ qla25xx_create_rsp_que(struct qla_hw_datif (ret !=QLA_SUCCESS ) {ql_log (ql_log_fatal, base_vha,0x00e7 ,"%s failed.\n" , __func__); -mutex_lock (&ha->mq_lock); -clear_bit (que_id, ha->rsp_qid_map); -mutex_unlock (&ha->mq_lock); goto que_failed; } vha->flags.qpairs_rsp_created =1 ;
Greg Kroah-Hartman
maintainerPATCH 673/877 scsi: qla2xxx: Fix use-after-free of qpair work on queue teardown
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 19788a55cab61d78e33e0914a5a31d27843e8a4a ]
The response queue MSI-X handler qla2xxx_msix_rsp_q() schedules qla_do_work() via queue_work(ha->wq, &qpair->q_work). qla_do_work() dereferences the qpair (vha, rsp) and takes qpair->qp_lock.
During teardown, qla2xxx_delete_qpair() deletes the response queue, which calls free_irq() in qla25xx_free_rsp_que(), and then frees the queue and the qpair. free_irq() waits for running hardirq handlers but does not cancel work already placed on ha->wq. A still-pending q_work then runs qla_do_work() against the freed qpair and response queue, causing a use-after-free. This is especially likely during full adapter teardown, where destroy_workqueue(ha->wq) forces pending work to run after the queue pairs have been freed.
Flush the work item with cancel_work_sync() in qla25xx_free_rsp_que() after free_irq() has released the interrupt (so no new work can be queued) and before the response queue and qpair memory are freed (so the flushed handler still sees valid memory). Guard on rsp->qpair and ha->wq to match the INIT_WORK() condition and avoid operating on an uninitialized work_struct.
--- drivers/scsi/qla2xxx/qla_mid.c | 4 ++++ 1 file changed, 4 insertions(+)
drivers/scsi/qla2xxx/qla_mid.c +4 -0
@@ -606,6 +606,10 @@ qla25xx_free_rsp_que(struct scsi_qla_hos rsp->msix->handle =NULL ; } +/* Flush any queued response work before freeing the queue/qpair. */ +if (rsp->qpair && ha->wq) +cancel_work_sync (&rsp->qpair->q_work); +if (rsp->ring) dma_free_coherent(&ha->pdev->dev, (rsp->length + 1) * rsp_entry_size,
Greg Kroah-Hartman
maintainerPATCH 674/877 scsi: qla2xxx: Null out freed pointers in qla2x00_mem_alloc() error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 6d90f0feb929f6c0f3010f9af4747c7230b75993 ]
When qla2x00_mem_alloc() fails, qla2x00_probe_one() jumps to probe_hw_failed and calls qla2x00_mem_free(). Several error labels in qla2x00_mem_alloc() freed adapter members (elsrej.c, purex_dma_pool, flt, sfp_data, loop_id_map, async_pd, sf_init_cb, ex_init_cb, npiv_info) but left the pointers dangling. qla2x00_mem_free() then freed them a second time. Worse, for the dma_pool members it issued dma_pool_free(ha->s_dma_pool, ...) after s_dma_pool had already been destroyed and set to NULL at fail_s_dma_pool, dereferencing a NULL pool.
Clear each freed pointer (and its DMA handle) in the error labels so the subsequent qla2x00_mem_free() skips them.
--- drivers/scsi/qla2xxx/qla_os.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/scsi/qla2xxx/qla_os.c +15 -0
@@ -4482,25 +4482,40 @@ qla2x00_mem_alloc(struct qla_hw_data *ha fail_lsrjt:dma_free_coherent (&ha->pdev->dev, ha->elsrej.size, ha->elsrej.c, ha->elsrej.cdma); + ha->elsrej.c =NULL ; + ha->elsrej.cdma =0 ; fail_elsrej:dma_pool_destroy (ha->purex_dma_pool); + ha->purex_dma_pool =NULL ; fail_flt:dma_free_coherent (&ha->pdev->dev,sizeof (struct qla_flt_header ) +FLT_REGIONS_SIZE , ha->flt, ha->flt_dma); + ha->flt =NULL ; + ha->flt_dma =0 ; fail_flt_buffer:dma_free_coherent (&ha->pdev->dev,SFP_DEV_SIZE , ha->sfp_data, ha->sfp_data_dma); + ha->sfp_data =NULL ; + ha->sfp_data_dma =0 ; fail_sfp_data:kfree (ha->loop_id_map); + ha->loop_id_map =NULL ; fail_loop_id_map:dma_pool_free (ha->s_dma_pool, ha->async_pd, ha->async_pd_dma); + ha->async_pd =NULL ; + ha->async_pd_dma =0 ; fail_async_pd:dma_pool_free (ha->s_dma_pool, ha->sf_init_cb, ha->sf_init_cb_dma); + ha->sf_init_cb =NULL ; + ha->sf_init_cb_dma =0 ; fail_sf_init_cb:dma_pool_free (ha->s_dma_pool, ha->ex_init_cb, ha->ex_init_cb_dma); + ha->ex_init_cb =NULL ; + ha->ex_init_cb_dma =0 ; fail_ex_init_cb:kfree (ha->npiv_info); + ha->npiv_info =NULL ; fail_npiv_info:dma_free_coherent (&ha->pdev->dev, ((*rsp)->length +1 ) *sizeof (response_t), (*rsp)->ring, (*rsp)->dma);
Greg Kroah-Hartman
maintainerPATCH 675/877 scsi: qla2xxx: Bound VP index against VP_CTRL IOCB bitmap size
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 878613ecb5a36db26859c4fd83daf9283a334fa2 ]
The VP control IOCB selects its target virtual port by setting one bit in vp_idx_map, a fixed 16-byte (128-bit) array in both vp_ctrl_entry_24xx and vp_ctrl_entry_24xx_ext. qla25xx_ctrlvp_iocb() computes map = (vp_index - 1) / 8 and writes vce->vp_idx_map[map] without checking that map stays within the array.
max_npiv_vports is taken from firmware and only sanitized to a MIN_MULTI_ID_FABRIC-aligned boundary, so it can legitimately be 191 or 255, and qla24xx_control_vp() only rejects vp_index >= max_npiv_vports. A vp_index above 128 therefore yields map >= 16 and an out-of-bounds write of up to 16 bytes past vp_idx_map, corrupting the trailing IOCB fields (or the adjacent request-ring slot on the 64-byte layout).
Reject a vp_index that cannot be represented in the IOCB bitmap in qla24xx_control_vp(), and add a defensive ARRAY_SIZE() guard in qla25xx_ctrlvp_iocb() before the write. Adapters that report the usual 63 or 127 NPIV vports are unaffected.
--- drivers/scsi/qla2xxx/qla_iocb.c | 6 ++++++ drivers/scsi/qla2xxx/qla_mid.c | 8 ++++++++ 2 files changed, 14 insertions(+)
drivers/scsi/qla2xxx/qla_iocb.c +6 -0
@@ -3828,6 +3828,12 @@ qla25xx_ctrlvp_iocb(srb_t *sp, struct vp*/ map = (sp->u.iocb_cmd.u.ctrlvp.vp_index -1 ) /8 ; pos = (sp->u.iocb_cmd.u.ctrlvp.vp_index -1 ) &7 ; +if (map >=ARRAY_SIZE (vce->vp_idx_map)) { +ql_log (ql_log_warn, sp->vha,0x307c , +"ctrlvp: vp_index %u exceeds vp_idx_map capacity\n" , + sp->u.iocb_cmd.u.ctrlvp.vp_index); +return ; + } vce->vp_idx_map[map] |=1 << pos; }
drivers/scsi/qla2xxx/qla_mid.c +8 -0
@@ -962,6 +962,14 @@ int qla24xx_control_vp(scsi_qla_host_t *if (vp_index ==0 || vp_index >= ha->max_npiv_vports)return QLA_PARAMETER_ERROR ; +/* +* The VP_CTRL IOCB selects the target VP through a fixed 128-bit +* (16-byte) vp_idx_map bitmap, so vp_index must fit within it even +* if firmware advertises more NPIV vports. +*/ + if (vp_index > sizeof_field(struct vp_ctrl_entry_24xx, vp_idx_map) * 8) +return QLA_PARAMETER_ERROR ; +/* ref: INIT */ sp =qla2x00_get_sp (base_vha,NULL ,GFP_KERNEL );if (!sp)
Greg Kroah-Hartman
maintainerPATCH 676/877 media: chips-media: wave5: Add timeout while stop_streaming
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
[ Upstream commit 2ae7faed2e60d6d07d9efdd962d20dcb15330ced ]
When stop_streaming is called, an infinite loop may occur in some cases. Add a bounded poll of the queue status: loop until the queues drain, sleeping briefly between polls, and bail out once VPU_DEC_STOP_TIMEOUT elapses.
--- drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c | 12 ++++++------ drivers/media/platform/chips-media/wave5/wave5-vpuconfig.h | 1 + 2 files changed, 7 insertions(+), 6 deletions(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +6 -6
@@ -5,6 +5,7 @@* Copyright (C) 2021-2023 CHIPS&MEDIA INC */ +#include <linux/delay.h> #include "wave5-helper.h" #define VPU_DEC_DEV_NAME "C&M Wave5 VPU decoder"
@@ -1567,24 +1568,23 @@ static void wave5_vpu_dec_stop_streaming {struct vpu_instance *inst =vb2_get_drv_priv (q);struct v4l2_m2m_ctx *m2m_ctx = inst->v4l2_fh.m2m_ctx; -bool check_cmd = TRUE; +unsigned long timeout;dev_dbg (inst->dev->dev,"%s: type: %u\n" , __func__, q->type); -while (check_cmd) { + timeout = jiffies +msecs_to_jiffies (VPU_DEC_STOP_TIMEOUT ); +while (true) {struct queue_status_info q_status; -struct dec_output_info dec_output_info;wave5_vpu_dec_give_command (inst,DEC_GET_QUEUE_STATUS , &q_status);if (q_status.report_queue_count ==0 )break ; -if (wave5_vpu_wait_interrupt (inst,VPU_DEC_TIMEOUT ) <0 ) +if (time_after (jiffies, timeout))break ; -if (wave5_vpu_dec_get_output_info (inst, &dec_output_info)) -dev_dbg (inst->dev->dev,"there is no output info\n" ); +usleep_range (1000 ,2000 ); }v4l2_m2m_update_stop_streaming_state (m2m_ctx, q);
drivers/media/platform/chips-media/wave5/wave5-vpuconfig.h +1 -0
@@ -40,6 +40,7 @@// application specific configuration #define VPU_ENC_TIMEOUT 60000#define VPU_DEC_TIMEOUT 60000 +#define VPU_DEC_STOP_TIMEOUT 300// for WAVE encoder #define USE_SRC_PRP_AXI 0
Greg Kroah-Hartman
maintainerPATCH 677/877 scsi: qla2xxx: Use ring-slot helpers in __qla2x00_alloc_iocbs
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 7e51b6d2d8f6b7f48d9cef1cf87471b55b12f6de ]
__qla2x00_alloc_iocbs() open-codes ring pointer selection and entry size based on IS_QLA29XX(ha): 29xx reaches the slot via ring_ext_ptr and zeroes REQUEST_ENTRY_SIZE_EXT bytes, while other adapters use ring_ptr with REQUEST_ENTRY_SIZE bytes.
Replace the two branches with the qla_req_ring_slot() and qla_req_entry_size() helpers, and initialise pkt at declaration. The IS_QLAFX00 register-mapped writes remain guarded because IS_QLAFX00 and IS_QLA29XX cannot be true simultaneously.
No functional change: the bytes written to the firmware-visible IOCB are identical.
Stable adaptation:
This tree has no QLA29xx support, extended request ring, or ring-slot helpers. Provide file-local macro helpers mapping to req->ring_ptr and REQUEST_ENTRY_SIZE, preserving the existing 64-byte ring behavior without adding functions or importing the unrelated QLA29xx support series.
Retain the helper calls and declaration initialization from this change. Use a multiline packet-preparation comment so commit 626e44f3d8a9 ("scsi: qla2xxx: Use memset_io() to clear QLAFX00 request ring slot") applies unchanged, including its leading context. That commit remains responsible for changing the FX00 clearing operation to memset_io().
Stable-dep-of: 626e44f3d8a9 ("scsi: qla2xxx: Use memset_io() to clear QLAFX00 request ring slot")
--- drivers/scsi/qla2xxx/qla_iocb.c | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/scsi/qla2xxx/qla_iocb.c +10 -5
@@ -11,6 +11,10 @@#include <scsi/scsi_tcq.h> +/* All adapters supported by this tree use the 64-byte request ring. */ +#define qla_req_ring_slot (ha, req) ((req)->ring_ptr) +#define qla_req_entry_size (ha) REQUEST_ENTRY_SIZE +static int qla_start_scsi_type6 (srb_t *sp);/** * qla2x00_get_cmd_direction() - Determine control_flag data direction.
@@ -2286,10 +2290,9 @@ __qla2x00_alloc_iocbs(struct qla_qpair *struct req_que *req = qpair->req;device_reg_t *reg =ISP_QUE_REG (ha, req->id);uint32_t handle; -request_t *pkt;uint16_t cnt, req_cnt; +request_t *pkt =NULL ; - pkt =NULL ; req_cnt =1 ; handle =0 ;
@@ -2343,10 +2346,12 @@ __qla2x00_alloc_iocbs(struct qla_qpair * sp->handle = handle; } -/* Prep packet */ +/* +* Prep the current request-ring slot. +*/ req->cnt -= req_cnt; - pkt = req->ring_ptr; -memset (pkt,0 ,REQUEST_ENTRY_SIZE ); + pkt =qla_req_ring_slot (ha, req); +memset (pkt,0 ,qla_req_entry_size (ha));if (IS_QLAFX00 (ha)) {wrt_reg_byte ((u8 __force __iomem *)&pkt->entry_count, req_cnt);wrt_reg_dword ((__le32 __force __iomem *)&pkt->handle, handle);
Greg Kroah-Hartman
maintainerPATCH 678/877 scsi: qla2xxx: Use memset_io() to clear QLAFX00 request ring slot
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 626e44f3d8a924a97a3848a9fd45833947e081e9 ]
For QLAFX00 the request ring is ioremapped device I/O memory (ha->iobase + req_que_off), not DMA-coherent RAM, which is why the rest of the FX00 path accesses it through memcpy_toio() and the wrt_reg_* helpers. __qla2x00_alloc_iocbs() however zeroed the producer slot with a plain memset(). On architectures such as ARM64 a regular memset() may emit unaligned or block-zeroing instructions (e.g. DC ZVA) that are invalid on Device memory, leading to a synchronous external abort.
Use memset_io() to clear the slot for QLAFX00, matching the I/O accessors used elsewhere on this ring. Other adapters keep the plain memset() on their DMA-coherent rings. The zero-fill is retained for FX00 because its IOCB builders (e.g. qlafx00_fxdisc_iocb()) copy only part of the entry and rely on the unused tail being pre-zeroed.
--- drivers/scsi/qla2xxx/qla_iocb.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/scsi/qla2xxx/qla_iocb.c +3 -1
@@ -2351,11 +2351,13 @@ __qla2x00_alloc_iocbs(struct qla_qpair **/ req->cnt -= req_cnt; pkt =qla_req_ring_slot (ha, req); -memset (pkt,0 ,qla_req_entry_size (ha));if (IS_QLAFX00 (ha)) { +memset_io ((void __iomem __force *)pkt,0 , +qla_req_entry_size (ha));wrt_reg_byte ((u8 __force __iomem *)&pkt->entry_count, req_cnt);wrt_reg_dword ((__le32 __force __iomem *)&pkt->handle, handle); }else { +memset (pkt,0 ,qla_req_entry_size (ha)); pkt->entry_count = req_cnt; pkt->handle = handle; }
Greg Kroah-Hartman
maintainerPATCH 679/877 scsi: qla2xxx: Fix 64G link speed reporting in get_data_rate
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 52fba32317ee631faa878725b2f7cd5c08acacd3 ]
qla2x00_get_data_rate() skips updating ha->link_data_rate when the firmware returns mcp->mb[1] == 0x7. That value was a legacy sentinel from before 64G hardware existed, but PORT_SPEED_64GB is now defined as 0x07 and ha->link_data_rate is decoded with the PORT_SPEED_* encoding. On a 64G-capable adapter a genuine 64G link is therefore dropped, and the port speed is misreported (port_speed sysfs, fc_host speed, FDMI).
Only 28xx and 29xx support 64G, so accept 0x07 on those adapters while keeping the legacy filter for older ones. Also drop the duplicate copy of the check at the end of the success branch; it repeated the first assignment with no intervening change.
--- drivers/scsi/qla2xxx/qla_mbx.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/scsi/qla2xxx/qla_mbx.c +1 -3
@@ -5658,7 +5658,7 @@ qla2x00_get_data_rate(scsi_qla_host_t *vql_dbg (ql_dbg_mbx, vha,0x1107 ,"Failed=%x mb[0]=%x.\n" , rval, mcp->mb[0 ]); }else { -if (mcp->mb[1 ] !=0x7 ) +if (mcp->mb[1 ] !=0x7 ||IS_QLA28XX (ha)) ha->link_data_rate = mcp->mb[1 ];if (IS_QLA83XX (ha) ||IS_QLA27XX (ha) ||IS_QLA28XX (ha)) {
@@ -5669,8 +5669,6 @@ qla2x00_get_data_rate(scsi_qla_host_t *vql_dbg (ql_dbg_mbx + ql_dbg_verbose, vha,0x1108 ,"Done %s.\n" , __func__); -if (mcp->mb[1 ] !=0x7 ) - ha->link_data_rate = mcp->mb[1 ]; }return rval;
Greg Kroah-Hartman
maintainerPATCH 680/877 scsi: qla2xxx: Skip vport under deletion in report ID acquisition
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 23582731afa35031c94fadb71a4f3b4afd094649 ]
qla24xx_report_id_acquisition() format-1 handling walks ha->vp_list under vport_slock, takes a vref_count on the matching vport and calls qla_update_host_map() to register its port id.
A vport teardown via qla24xx_vport_delete() sets VPORT_DELETE, then qla24xx_disable_vp() removes the vport from the host_map btree and zeroes vha->d_id (RESET_AL_PA). The vport is only unlinked from vp_list later, in qla24xx_deallocate_vp_id(), which clears vp_map[idx] (RESET_VP_IDX) but does not touch host_map. In the window in between, report ID acquisition can still find the vport on vp_list and call qla_update_host_map(); with d_id already zeroed it takes the btree_insert32() path and re-inserts the dying vport into host_map. Nothing cleans that entry afterwards, so once scsi_host_put() frees the vha a later host_map lookup dereferences freed memory.
Skip a vport that has VPORT_DELETE set before taking the reference, so it is neither re-registered nor scheduled for DPC re-registration. This mirrors the existing guard in qla2x00_alert_all_vps().
--- drivers/scsi/qla2xxx/qla_mbx.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/scsi/qla2xxx/qla_mbx.c +2 -0
@@ -4147,6 +4147,8 @@ qla24xx_report_id_acquisition(scsi_qla_hspin_lock_irqsave (&ha->vport_slock, flags);list_for_each_entry (vp, &ha->vp_list, list) {if (rptid_entry->vp_idx == vp->vp_idx) { +if (test_bit (VPORT_DELETE , &vp->dpc_flags)) +break ; found =1 ;atomic_inc (&vp->vref_count);break ;
Greg Kroah-Hartman
maintainerPATCH 681/877 scsi: qla2xxx: Fix soft lockup polling continuation IOCB signature
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit d7e3fa7d06bf7fcaac186d3c4d635caac166d36c ]
qla27xx_copy_multiple_pkt() and qla27xx_copy_fpin_pkt() poll rsp_q->ring_ptr->signature for RESPONSE_PROCESSED (0xDEADDEAD) to decide whether the next continuation IOCB has arrived, spinning on cpu_relax() without advancing the ring or decrementing the entry count while it has not. response_t::signature lives at byte offset 60, but a continuation IOCB (sts_cont_entry_t / struct sts_cont_entry_ext) carries raw FC frame payload at that offset (data[56..59]). A received frame whose payload bytes happen to equal 0xDEADDEAD is therefore misread as "not yet arrived", and the loop spins forever in interrupt/DPC context, causing a CPU soft lockup.
The poll is also unnecessary: callers of qla27xx_copy_multiple_pkt() (PT_LS4_UNSOL and the NVMe purls path) already gate on qla_chk_cont_iocb_avail(), which guarantees all entry_count IOCBs are present before copying begins. The sibling helper __qla_copy_purex_to_buffer() already drops the signature poll and relies on the entry_type == STATUS_CONT_TYPE guard instead.
Remove the signature busy-wait from both helpers, keeping the entry_type guard, and gate the FPIN path with qla_chk_cont_iocb_avail() so it defers and re-processes on the next interrupt once all continuation IOCBs have arrived, mirroring the ELS_AUTH_ELS and PT_LS4_UNSOL arms. With this the signature field is never read on a continuation IOCB, eliminating the payload-aliasing lockup.
--- drivers/scsi/qla2xxx/qla_isr.c | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-)
drivers/scsi/qla2xxx/qla_isr.c +16 -17
@@ -921,14 +921,6 @@ qla27xx_copy_multiple_pkt(struct scsi_ql do { while ((total_bytes > 0) && (entry_count_remaining > 0)) { - if (rsp_q->ring_ptr->signature == RESPONSE_PROCESSED) { - ql_dbg(ql_dbg_async, vha, 0x5084, - "Ran out of IOCBs, partial data 0x%x\n", - buffer_copy_offset); - cpu_relax(); - continue; - } - new_pkt = (sts_cont_entry_t *)rsp_q->ring_ptr; *pkt = new_pkt;
@@ -1205,14 +1197,6 @@ qla27xx_copy_fpin_pkt(struct scsi_qla_ho do { while ((total_bytes > 0) && (entry_count_remaining > 0)) { - if (rsp_q->ring_ptr->signature == RESPONSE_PROCESSED) { - ql_dbg(ql_dbg_async, vha, 0x5084, - "Ran out of IOCBs, partial data 0x%x\n", - buffer_copy_offset); - cpu_relax(); - continue; - } - new_pkt = (sts_cont_entry_t *)rsp_q->ring_ptr; *pkt = new_pkt;
@@ -4142,9 +4126,24 @@ process_err: "SCM not active for this port\n");break ; } +if (qla_chk_cont_iocb_avail (vha, rsp, + (response_t *)pkt, rsp_in)) { +/* +* ring_ptr and ring_index were +* pre-incremented above. Reset them +* back to current. Wait for next +* interrupt with all IOCBs to arrive +* and re-process. +*/ + rsp->ring_ptr = (response_t *)pkt; + rsp->ring_index = cur_ring_index; + +ql_dbg (ql_dbg_init, vha,0x5095 , +"Defer processing FPIN...\n" ); +return ; + } pure_item =qla27xx_copy_fpin_pkt (vha, (void **)&pkt, &rsp); -__update_rsp_in (is_shadow_hba, rsp, rsp_in);if (!pure_item)break ; qla24xx_queue_purex_item(vha, pure_item,
Greg Kroah-Hartman
maintainerPATCH 682/877 scsi: qla2xxx: Clamp max_npiv_vports to VP_CTRL bitmap capacity
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 2ac6a829843cf3df522d19e091276109b94c4c7a ]
ha->max_npiv_vports is taken from firmware (mcp->mb[11]) and only constrained so that (max_npiv_vports + 1) is a multiple of MIN_MULTI_ID_FABRIC, which permits values of 63, 127, 191 and 255. NPIV vports are then allocated up to that count.
VP enable uses the VP_CONFIG IOCB, which addresses a vport through a plain vp_index byte, so a vp_index beyond 128 is enabled without issue. VP disable, however, uses the VP_CTRL IOCB, which selects target vports through the fixed 128-bit vp_idx_map bitmap. qla24xx_control_vp() rejects a vp_index past that bitmap and the IOCB builder cannot set a bit beyond 127, yet qla24xx_vport_delete() frees the local state regardless. A vport with vp_index > 128 can therefore be created and enabled but never disabled, leaving it permanently active in firmware: a resource leak.
Cap ha->max_npiv_vports at init to the vp_idx_map capacity so such vports are never created. This collapses 191/255 to 127 (still modulo-valid) and leaves the real-world 63/127 cases unaffected.
--- drivers/scsi/qla2xxx/qla_fw.h | 4 ++++ drivers/scsi/qla2xxx/qla_init.c | 13 +++++++++++++ drivers/scsi/qla2xxx/qla_mid.c | 8 ++++++++ 3 files changed, 25 insertions(+)
drivers/scsi/qla2xxx/qla_fw.h +4 -0
@@ -1442,6 +1442,10 @@ struct vp_ctrl_entry_24xx {uint8_t reserved_5[24 ]; }; +/* vp_idx_map is a 128-bit (16-byte) bitmap selecting target VPs. */ +#define VP_CTRL_IDX_MAP_BITS \ + (sizeof_field(struct vp_ctrl_entry_24xx, vp_idx_map) * 8) +/* * Modify Virtual Port Configuration IOCB */
drivers/scsi/qla2xxx/qla_init.c +13 -0
@@ -4408,6 +4408,19 @@ enable_82xx_npiv: MIN_MULTI_ID_FABRIC)) ha->max_npiv_vports =MIN_MULTI_ID_FABRIC -1 ; + +/* +* The VP_CTRL IOCB selects target VPs +* through the fixed vp_idx_map bitmap, +* so a vp_index beyond it can be enabled +* via VP_CONFIG but never disabled via +* VP_CTRL, leaking the VP. Cap the count +* to the bitmap capacity. +*/ +if (ha->max_npiv_vports >= +VP_CTRL_IDX_MAP_BITS ) + ha->max_npiv_vports = +VP_CTRL_IDX_MAP_BITS -1 ; }qla2x00_get_resource_cnts (vha);qla_init_iocb_limit (vha);
drivers/scsi/qla2xxx/qla_mid.c +8 -0
@@ -970,6 +970,14 @@ int qla24xx_control_vp(scsi_qla_host_t * if (vp_index > sizeof_field(struct vp_ctrl_entry_24xx, vp_idx_map) * 8)return QLA_PARAMETER_ERROR ; +/* +* The VP_CTRL IOCB selects the target VP through a fixed 128-bit +* (16-byte) vp_idx_map bitmap, so vp_index must fit within it even +* if firmware advertises more NPIV vports. +*/ +if (vp_index >VP_CTRL_IDX_MAP_BITS ) +return QLA_PARAMETER_ERROR ; +/* ref: INIT */ sp =qla2x00_get_sp (base_vha,NULL ,GFP_KERNEL );if (!sp)
Greg Kroah-Hartman
maintainerPATCH 683/877 scsi: qla2xxx: Unlink NVMe unsol ctx before freeing on LS reject error
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit e46160a5d4fa59bf4d5f3412b6b5cb79edb967dd ]
qla_nvme_xmt_ls_rsp() obtains uctx, which was linked into fcport->unsol_ctx_head by qla2xxx_process_purls_iocb() and is still linked when the NVMe transport calls back to transmit the LS response. On the error (out:) path the function frees uctx with kfree() but never removes it from the list. This leaves a freed node in fcport->unsol_ctx_head: the next list_add_tail() for that fcport writes through the freed node, and a subsequent list_del() can corrupt the list or panic.
Unlink uctx with list_del() before kfree() on the error path, matching the other free sites in qla_nvme_release_lsrsp_cmd_kref() and qla2xxx_process_purls_pkt(). qla2x00_rel_sp() in the failure path only returns the SRB to its pool and does not invoke sp->put_fn, so the out:
path is the sole free and uctx is always still linked there.
Stable-dep-of: 76da0c43c63e ("scsi: qla2xxx: Serialize NVMe unsol ctx list with a per-fcport lock")
--- drivers/scsi/qla2xxx/qla_nvme.c | 1 + 1 file changed, 1 insertion(+)
drivers/scsi/qla2xxx/qla_nvme.c +1 -0
@@ -446,6 +446,7 @@ out:qla_nvme_ls_reject_iocb (vha, ha->base_qpair, &a, true);spin_unlock_irqrestore (ha->base_qpair->qp_lock_ptr, flags); } +list_del (&uctx->elem);kfree (uctx);return rval; }
Greg Kroah-Hartman
maintainerPATCH 684/877 scsi: qla2xxx: Serialize NVMe unsol ctx list with a per-fcport lock
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 76da0c43c63eb0496649e372ac64466364d0fe7d ]
The fcport->unsol_ctx_head list is modified from several contexts without a common lock. Entries are added in qla2xxx_process_purls_iocb() from the response queue ISR (under the qpair qp_lock), while they are removed from qla2xxx_process_purls_pkt() (DPC/purex worker), qla_nvme_xmt_ls_rsp() (NVMe-FC transport callback) and qla_nvme_release_lsrsp_cmd_kref() (SRB completion). The qpair qp_lock cannot serialize this per-fcport list since multiqueue adapters add entries through different qpairs, so a concurrent add and delete (or two concurrent deletes) can corrupt the list pointers.
Introduce a dedicated per-fcport spinlock, unsol_ctx_lock, initialized in qla2x00_alloc_fcport(), and take it around every list_add_tail()/list_del() on unsol_ctx_head. The add nests under the existing qp_lock; no delete path takes qp_lock, so the lock order is consistent and deadlock free.
--- drivers/scsi/qla2xxx/qla_def.h | 2 ++ drivers/scsi/qla2xxx/qla_init.c | 1 + drivers/scsi/qla2xxx/qla_nvme.c | 9 +++++++++ 3 files changed, 12 insertions(+)
drivers/scsi/qla2xxx/qla_def.h +2 -0
@@ -2570,6 +2570,8 @@ typedef struct fc_port {struct list_head list;struct scsi_qla_host *vha;struct list_head unsol_ctx_head; +/* Serializes unsol_ctx_head against ISR, DPC and NVMe transport. */ +spinlock_t unsol_ctx_lock; unsigned int conf_compl_supported:1; unsigned int deleted:2;
drivers/scsi/qla2xxx/qla_init.c +1 -0
@@ -5649,6 +5649,7 @@ qla2x00_alloc_fcport(scsi_qla_host_t *vhINIT_LIST_HEAD (&fcport->gnl_entry);INIT_LIST_HEAD (&fcport->list);INIT_LIST_HEAD (&fcport->unsol_ctx_head); +spin_lock_init (&fcport->unsol_ctx_lock);INIT_LIST_HEAD (&fcport->sess_cmd_list);spin_lock_init (&fcport->sess_cmd_lock);
drivers/scsi/qla2xxx/qla_nvme.c +9 -0
@@ -257,7 +257,9 @@ static void qla_nvme_release_lsrsp_cmd_k fd_rsp = uctx->fd_rsp; +spin_lock_irqsave (&uctx->fcport->unsol_ctx_lock, flags);list_del (&uctx->elem); +spin_unlock_irqrestore (&uctx->fcport->unsol_ctx_lock, flags); fd_rsp->done (fd_rsp);kfree (uctx);
@@ -446,7 +448,9 @@ out:qla_nvme_ls_reject_iocb (vha, ha->base_qpair, &a, true);spin_unlock_irqrestore (ha->base_qpair->qp_lock_ptr, flags); } +spin_lock_irqsave (&uctx->fcport->unsol_ctx_lock, flags);list_del (&uctx->elem); +spin_unlock_irqrestore (&uctx->fcport->unsol_ctx_lock, flags);kfree (uctx);return rval; }
@@ -1216,7 +1220,9 @@ qla2xxx_process_purls_pkt(struct scsi_qlspin_unlock_irqrestore (vha->hw->base_qpair->qp_lock_ptr, flags); } +spin_lock_irqsave (&uctx->fcport->unsol_ctx_lock, flags);list_del (&uctx->elem); +spin_unlock_irqrestore (&uctx->fcport->unsol_ctx_lock, flags);kfree (uctx); } }
@@ -1258,6 +1264,7 @@ void qla2xxx_process_purls_iocb(void **pstruct purex_item *item;port_id_t d_id = {0 };port_id_t id = {0 }; +unsigned long flags;u8 *opcode;bool xmt_reject = false;
@@ -1323,7 +1330,9 @@ void qla2xxx_process_purls_iocb(void **p uctx->ox_id = p->ox_id; qla_rport->uctx = uctx;INIT_LIST_HEAD (&uctx->elem); +spin_lock_irqsave (&fcport->unsol_ctx_lock, flags);list_add_tail (&uctx->elem, &fcport->unsol_ctx_head); +spin_unlock_irqrestore (&fcport->unsol_ctx_lock, flags); item->purls_context = (void *)uctx; ql_dbg(ql_dbg_unsol, vha, 0x2121,
Greg Kroah-Hartman
maintainerPATCH 685/877 scsi: qla2xxx: Validate BSG request_len before reading vendor_cmd[]
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
[ Upstream commit 4cf38dd9465736141263ebb63375868311a0ec81 ]
The FC BSG transport allocates job->request via memdup_user() using the exact user-supplied request_len. For FC_BSG_HST_VENDOR, fc_bsg_host_dispatch() only guarantees request_len covers msgcode and vendor_id; it does not account for the vendor_cmd[] flexible array.
qla2xxx then reads the command selector vendor_cmd[0] and, in several sub-handlers, vendor_cmd[1]/[2] or structures overlaid on the vendor command area without verifying request_len. A caller holding CAP_SYS_RAWIO can submit a short request whose vendor_id matches the host, triggering out-of-bounds heap reads (KASAN-detectable, and able to mis-select a command or panic).
Add a central guard in qla2x00_process_vendor_specific() so the selector is always in bounds, restrict the early vendor_cmd[0] read in qla24xx_bsg_request() to sufficiently long vendor messages, and add request_len checks to the sub-handlers that read further:qla24xx_proc_fcp_prio_cfg_cmd(), qla2x00_process_loopback(), qla84xx_reset(), qla84xx_updatefw(), qla2x00_read_optrom(), qla2x00_update_optrom(), qlafx00_mgmt_cmd() and qla28xx_validate_flash_image().
--- drivers/scsi/qla2xxx/qla_bsg.c | 45 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-)
drivers/scsi/qla2xxx/qla_bsg.c +43 -2
@@ -158,6 +158,12 @@ qla24xx_proc_fcp_prio_cfg_cmd(struct bsg goto exit_fcp_prio_cfg; } +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +2 *sizeof (uint32_t )) { + ret = -EINVAL ; + goto exit_fcp_prio_cfg; + } +/* Get the sub command */ oper = bsg_request->rqst_data.h_vendor.vendor_cmd[1 ];
@@ -756,6 +762,10 @@ qla2x00_process_loopback(struct bsg_jobreturn -EIO ; } +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +3 *sizeof (uint32_t )) +return -EINVAL ; +memset (&elreq,0 ,sizeof (elreq)); elreq.req_sg_cnt = dma_map_sg(&ha->pdev->dev,
@@ -988,6 +998,10 @@ qla84xx_reset(struct bsg_job *bsg_job)return -EINVAL ; } +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +2 *sizeof (uint32_t )) +return -EINVAL ; + flag = bsg_request->rqst_data.h_vendor.vendor_cmd[1 ]; rval =qla84xx_reset_chip (vha, flag ==A84_ISSUE_RESET_DIAG_FW );
@@ -1032,6 +1046,10 @@ qla84xx_updatefw(struct bsg_job *bsg_jobreturn -EINVAL ; } +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +2 *sizeof (uint32_t )) +return -EINVAL ; + sg_cnt =dma_map_sg (&ha->pdev->dev, bsg_job->request_payload.sg_list, bsg_job->request_payload.sg_cnt,DMA_TO_DEVICE );if (!sg_cnt) {
@@ -1482,6 +1500,10 @@ qla2x00_read_optrom(struct bsg_job *bsg_struct qla_hw_data *ha = vha->hw;int rval =0 ; +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +2 *sizeof (uint32_t )) +return -EINVAL ; +if (ha->flags.nic_core_reset_hdlr_active)return -EBUSY ;
@@ -1519,6 +1541,10 @@ qla2x00_update_optrom(struct bsg_job *bsstruct qla_hw_data *ha = vha->hw;int rval =0 ; +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +2 *sizeof (uint32_t )) +return -EINVAL ; +mutex_lock (&ha->optrom_mutex); rval =qla2x00_optrom_setup (bsg_job, vha,1 );if (rval) {
@@ -2010,6 +2036,11 @@ qlafx00_mgmt_cmd(struct bsg_job *bsg_jobstruct fc_port *fcport;char *type ="FC_BSG_HST_FX_MGMT" ; +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +sizeof (uint32_t ) + +sizeof (struct qla_mt_iocb_rqst_fx00 )) +return -EINVAL ; +/* Copy the IOCB specific information */ piocb_rqst = (struct qla_mt_iocb_rqst_fx00 *) &bsg_request->rqst_data.h_vendor.vendor_cmd[1 ];
@@ -2899,6 +2930,13 @@ qla2x00_process_vendor_specific(struct s {struct fc_bsg_request *bsg_request = bsg_job->request; +if (bsg_job->request_len < +sizeof (struct fc_bsg_request ) +sizeof (uint32_t )) { +ql_log (ql_log_warn, vha,0x7000 , +"BSG request too small for vendor cmd.\n" ); +return -EINVAL ; + } +ql_dbg (ql_dbg_edif, vha,0x911b ,"%s FC_BSG_HST_VENDOR cmd[0]=0x%x\n" , __func__, bsg_request->rqst_data.h_vendor.vendor_cmd[0 ]);
@@ -3024,8 +3062,11 @@ qla24xx_bsg_request(struct bsg_job *bsg_ }/* Disable port will bring down the chip, allow enable command */ -if (bsg_request->rqst_data.h_vendor.vendor_cmd[0 ] ==QL_VND_MANAGE_HOST_PORT || - bsg_request->rqst_data.h_vendor.vendor_cmd[0 ] ==QL_VND_GET_HOST_STATS ) +if (bsg_request->msgcode ==FC_BSG_HST_VENDOR && + bsg_job->request_len >= +sizeof (struct fc_bsg_request ) +sizeof (uint32_t ) && + (bsg_request->rqst_data.h_vendor.vendor_cmd[0 ] ==QL_VND_MANAGE_HOST_PORT || + bsg_request->rqst_data.h_vendor.vendor_cmd[0 ] ==QL_VND_GET_HOST_STATS )) goto skip_chip_chk;if (vha->hw->flags.port_isolated) {
Greg Kroah-Hartman
maintainerPATCH 686/877 f2fs: validate MOVE_RANGE destination size
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wenjie Qi <[email protected]>
[ Upstream commit e533889fc26aea0cd83c90327063f272061dd820 ]
F2FS_IOC_MOVE_RANGE checks the source range, but not the destination end before updating i_size. A source hole can expose this: __clone_blkaddrs() skips NULL_ADDR entries and returns success, so the caller can still extend the destination inode with unchecked pos_out + len.
Reject destination overflow and use inode_newsize_ok() before extending the destination inode.
--- fs/f2fs/file.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-)
fs/f2fs/file.c +12 -4
@@ -3100,8 +3100,9 @@ static int f2fs_move_file_range(struct fstruct inode *src =file_inode (file_in);struct inode *dst =file_inode (file_out);struct f2fs_sb_info *sbi =F2FS_I_SB (src); -size_t olen = len, dst_max_i_size =0 ; -size_t dst_osize; +size_t olen = len; +loff_t dst_max_i_size =0 ; +loff_t dst_osize, dst_end;int ret; if (file_in->f_path.mnt != file_out->f_path.mnt ||
@@ -3158,8 +3159,15 @@ static int f2fs_move_file_range(struct f } dst_osize = dst->i_size; -if (pos_out + olen > dst->i_size) - dst_max_i_size = pos_out + olen; +if (olen >LLONG_MAX - pos_out) + goto out_unlock; + dst_end = pos_out + olen; +if (dst_end > dst->i_size) { + ret =inode_newsize_ok (dst, dst_end); +if (ret) + goto out_unlock; + dst_max_i_size = dst_end; + }/* verify the end result is block aligned */ if (!IS_ALIGNED(pos_in, F2FS_BLKSIZE) ||
Greg Kroah-Hartman
maintainerPATCH 687/877 f2fs: convert F2FS_I_SB to sbi in f2fs_setattr()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: wangzijie <[email protected]>
[ Upstream commit 90c5ce37adf074ed85b26d1cd43074f29c0743ba ]
Introduce sbi in f2fs_setattr() and convert F2FS_I_SB to it. No logic change, just cleanup and prepare to get CAP_BLKS_PER_SEC(sbi).
Stable-dep-of: d0a481fad5c7 ("f2fs: fix to avoid potential section-unaligned pinfile")
--- fs/f2fs/file.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-)
fs/f2fs/file.c +7 -7
@@ -1064,9 +1064,10 @@ int f2fs_setattr(struct mnt_idmap *idmap {struct inode *inode =d_inode (dentry);struct f2fs_inode_info *fi =F2FS_I (inode); +struct f2fs_sb_info *sbi =F2FS_I_SB (inode);int err; -if (unlikely (f2fs_cp_error (F2FS_I_SB (inode)))) +if (unlikely (f2fs_cp_error (sbi)))return -EIO ; err =setattr_prepare (idmap, dentry, attr);
@@ -1105,12 +1106,11 @@ int f2fs_setattr(struct mnt_idmap *idmap }if (i_uid_needs_update (idmap, attr, inode) ||i_gid_needs_update (idmap, attr, inode)) { -f2fs_lock_op (F2FS_I_SB (inode)); +f2fs_lock_op (sbi); err =dquot_transfer (idmap, inode, attr);if (err) { -set_sbi_flag (F2FS_I_SB (inode), -SBI_QUOTA_NEED_REPAIR ); -f2fs_unlock_op (F2FS_I_SB (inode)); +set_sbi_flag (sbi,SBI_QUOTA_NEED_REPAIR ); +f2fs_unlock_op (sbi);return err; }/*
@@ -1120,7 +1120,7 @@ int f2fs_setattr(struct mnt_idmap *idmapi_uid_update (idmap, attr, inode);i_gid_update (idmap, attr, inode);f2fs_mark_inode_dirty_sync (inode, true); -f2fs_unlock_op (F2FS_I_SB (inode)); +f2fs_unlock_op (sbi); }if (attr->ia_valid &ATTR_SIZE ) {
@@ -1188,7 +1188,7 @@ err_out:f2fs_mark_inode_dirty_sync (inode, true);/* inode change will produce dirty node pages flushed by checkpoint */ -f2fs_balance_fs (F2FS_I_SB (inode), true); +f2fs_balance_fs (sbi, true);return err; }
Greg Kroah-Hartman
maintainerPATCH 688/877 f2fs: dont allow unaligned truncation to smaller/equal size on pinned file
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: wangzijie <[email protected]>
[ Upstream commit d738f708564764ed591cb6ab50d55489f87c726a ]
To prevent scattered pin block generation, don't allow non-section aligned truncation to smaller or equal size on pinned file. But for truncation to larger size, after commit 3fdd89b452c2("f2fs: prevent writing without fallocate() for pinned files"), we only support overwrite IO to pinned file, so we don't need to consider attr->ia_size > i_size case.
Stable-dep-of: d0a481fad5c7 ("f2fs: fix to avoid potential section-unaligned pinfile")
--- fs/f2fs/file.c | 11 +++++++++++ 1 file changed, 11 insertions(+)
fs/f2fs/file.c +11 -0
@@ -1097,6 +1097,17 @@ int f2fs_setattr(struct mnt_idmap *idmap !IS_ALIGNED (attr->ia_size, F2FS_BLK_TO_BYTES(fi->i_cluster_size))) return -EINVAL; +/* +* To prevent scattered pin block generation, we don't allow +* smaller/equal size unaligned truncation for pinned file. +* We only support overwrite IO to pinned file, so don't +* care about larger size truncation. +*/ +if (f2fs_is_pinned_file (inode) && + attr->ia_size <=i_size_read (inode) && + !IS_ALIGNED (attr->ia_size, +F2FS_BLK_TO_BYTES (CAP_BLKS_PER_SEC (sbi)))) +return -EINVAL ; }if (is_quota_modification (idmap, inode, attr)) {
Greg Kroah-Hartman
maintainerPATCH 689/877 f2fs: fix to avoid potential section-unaligned pinfile
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chao Yu <[email protected]>
[ Upstream commit d0a481fad5c7a3a56ecf54a099651216869f4d0a ]
Blocks of pinfile may not aligned to section size due to wrong use on pinfile, result in heavy overhead of GC, let avoid this by adding additional check condition in f2fs_setattr().
- truncate -s 8mb pinfile
: random checkpoint may persist filesize w/ inode
- fallocate -o 0 -l 8mb pinfile
- f2fs_fallocate
- f2fs_expand_inode_data
- f2fs_allocate_pinning_section
- f2fs_map_blocks
- f2fs_map_lock
- __allocate_data_block
- file_need_truncate
: w/ FADVISE_TRUNC_BIT, we can expect unaligned mapping can be
truncated while open() if f2fs is not umount abnormally
- f2fs_map_unlock
: following f2fs checkpoint and sudden power-cut
- mount
- open pinfile
- f2fs_file_open
- finish_preallocate_blocks
- truncate_setsize
: filesize is 8mb
- f2fs_truncate
: can only truncate block outside filesize, rather than truncating
unaligned blocks inside filesize
--- fs/f2fs/file.c | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-)
fs/f2fs/file.c +17 -11
@@ -1097,17 +1097,23 @@ int f2fs_setattr(struct mnt_idmap *idmap !IS_ALIGNED (attr->ia_size, F2FS_BLK_TO_BYTES(fi->i_cluster_size))) return -EINVAL; -/* -* To prevent scattered pin block generation, we don't allow -* smaller/equal size unaligned truncation for pinned file. -* We only support overwrite IO to pinned file, so don't -* care about larger size truncation. -*/ -if (f2fs_is_pinned_file (inode) && - attr->ia_size <=i_size_read (inode) && - !IS_ALIGNED (attr->ia_size, -F2FS_BLK_TO_BYTES (CAP_BLKS_PER_SEC (sbi)))) -return -EINVAL ; + +if (f2fs_is_pinned_file (inode)) { +/* +* It may break section-aligned fallocate recovery +* mechanism, so do not allow larger size truncation. +*/ +if (attr->ia_size >i_size_read (inode)) +return -EINVAL ; +/* +* To prevent scattered pin block generation, we don't +* allow smaller/equal size unaligned truncation for +* pinned file. +*/ +else if (!IS_ALIGNED (attr->ia_size, +F2FS_BLK_TO_BYTES (CAP_BLKS_PER_SEC (sbi)))) +return -EINVAL ; + } }if (is_quota_modification (idmap, inode, attr)) {
Greg Kroah-Hartman
maintainerPATCH 690/877 f2fs: dirty directory inodes on mtime/ctime update
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joanne Chang <[email protected]>
[ Upstream commit 9ec09d5f4b317a417c8655c14056f70cbe71eb6c ]
Xfstests generic/547 sometimes fail with mismatched directory metadata before and after a power failure. This happens because when a directory entry is added, renamed, or deleted, its mtime and ctime are updated and the inode is marked dirty via f2fs_mark_inode_dirty_sync(dir, sync=false). The sync=false flag means the dirty inode is not added to the global DIRTY_META list. Therefore, subsequent checkpoints skip flushing these updated directory blocks, causing directory timestamps to revert to stale values after a sudden power failure.
Address this by changing the dirtying parameter to sync=true during directory entry mutations and renames. This forces F2FS to immediately queue the updated directory blocks on the global DIRTY_META list, ensuring timestamps are committed to checkpoints.
--- fs/f2fs/dir.c | 6 +++--- fs/f2fs/inline.c | 2 +- fs/f2fs/namei.c | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-)
fs/f2fs/dir.c +3 -3
@@ -437,7 +437,7 @@ void f2fs_set_link(struct inode *dir, stset_page_dirty (page);inode_set_mtime_to_ts (dir,inode_set_ctime_current (dir)); -f2fs_mark_inode_dirty_sync (dir, false); +f2fs_mark_inode_dirty_sync (dir, true);f2fs_put_page (page,1 ); }
@@ -591,7 +591,7 @@ void f2fs_update_parent_metadata(structclear_inode_flag (inode,FI_NEW_INODE ); }inode_set_mtime_to_ts (dir,inode_set_ctime_current (dir)); -f2fs_mark_inode_dirty_sync (dir, false); +f2fs_mark_inode_dirty_sync (dir, true);if (F2FS_I (dir)->i_current_depth != current_depth)f2fs_i_depth_write (dir, current_depth);
@@ -903,7 +903,7 @@ void f2fs_delete_entry(struct f2fs_dir_ef2fs_put_page (page,1 );inode_set_mtime_to_ts (dir,inode_set_ctime_current (dir)); -f2fs_mark_inode_dirty_sync (dir, false); +f2fs_mark_inode_dirty_sync (dir, true);if (inode)f2fs_drop_nlink (dir, inode);
fs/f2fs/inline.c +1 -1
@@ -727,7 +727,7 @@ void f2fs_delete_inline_entry(struct f2ff2fs_put_page (page,1 );inode_set_mtime_to_ts (dir,inode_set_ctime_current (dir)); -f2fs_mark_inode_dirty_sync (dir, false); +f2fs_mark_inode_dirty_sync (dir, true);if (inode)f2fs_drop_nlink (dir, inode);
fs/f2fs/namei.c +3 -3
@@ -1038,7 +1038,7 @@ static int f2fs_rename(struct mnt_idmapf2fs_up_write (&F2FS_I (old_inode)->i_sem);inode_set_ctime_current (old_inode); -f2fs_mark_inode_dirty_sync (old_inode, false); +f2fs_mark_inode_dirty_sync (old_inode, true);f2fs_delete_entry (old_entry, old_page, old_dir,NULL ); old_page =NULL ;
@@ -1207,7 +1207,7 @@ static int f2fs_cross_rename(struct inodf2fs_i_links_write (old_dir, old_nlink >0 );f2fs_up_write (&F2FS_I (old_dir)->i_sem); } -f2fs_mark_inode_dirty_sync (old_dir, false); +f2fs_mark_inode_dirty_sync (old_dir, true);/* update directory entry info of new dir inode */ f2fs_set_link (new_dir, new_entry, new_page, old_inode);
@@ -1226,7 +1226,7 @@ static int f2fs_cross_rename(struct inodf2fs_i_links_write (new_dir, new_nlink >0 );f2fs_up_write (&F2FS_I (new_dir)->i_sem); } -f2fs_mark_inode_dirty_sync (new_dir, false); +f2fs_mark_inode_dirty_sync (new_dir, true);if (F2FS_OPTION (sbi).fsync_mode ==FSYNC_MODE_STRICT ) {f2fs_add_ino_entry (sbi, old_dir->i_ino,TRANS_DIR_INO );
Greg Kroah-Hartman
maintainerPATCH 691/877 f2fs: limit recovery filename logging to stored length
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wenjie Qi <[email protected]>
[ Upstream commit 01027b2fcb74dade59fb833b51023f6593b6a9a2 ]
F2FS stores recovery filenames as a length plus a fixed-size i_name buffer. The buffer is not NUL-terminated, but recover_inode() and recover_dentry() print it with %s.
For a 255-byte filename, recovery logging can read past i_name into the following raw inode fields.
Print the name with a precision bounded by i_namelen and F2FS_NAME_LEN.
--- fs/f2fs/recovery.c | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-)
fs/f2fs/recovery.c +27 -14
@@ -157,6 +157,22 @@ static int init_recovered_filename(constreturn 0 ; } +static const char *recover_printable_name (struct inode *inode, +struct f2fs_inode *raw, +int *name_len) +{ +static const char encrypted_name[] ="<encrypted>" ; + +if (file_enc_name (inode)) { + *name_len =sizeof (encrypted_name) -1 ; +return encrypted_name; + } + + *name_len = min_t(unsigned int, le32_to_cpu(raw->i_namelen), +F2FS_NAME_LEN ); +return raw->i_name; +} +static int recover_dentry (struct inode *inode,struct page *ipage,struct list_head *dir_list) {
@@ -169,7 +185,8 @@ static int recover_dentry(struct inode *struct inode *dir, *einode;struct fsync_inode_entry *entry;int err =0 ; -char *name; +const char *name; +int name_len; entry =get_fsync_inode (dir_list, pino);if (!entry) {
@@ -228,12 +245,9 @@ retry: out_put:f2fs_put_page (page,0 ); out: -if (file_enc_name (inode)) - name ="<encrypted>" ; -else - name = raw_inode->i_name; -f2fs_notice (F2FS_I_SB (inode),"%s: ino = %x, name = %s, dir = %lx, err = %d" , - __func__,ino_of_node (ipage), name, + name =recover_printable_name (inode, raw_inode, &name_len); +f2fs_notice (F2FS_I_SB (inode),"%s: ino = %x, name = %.*s, dir = %lx, err = %d" , + __func__,ino_of_node (ipage), name_len, name,IS_ERR (dir) ?0 : dir->i_ino, err);return err; }
@@ -281,7 +295,8 @@ static int recover_inode(struct inode *i {struct f2fs_inode *raw =F2FS_INODE (page);struct f2fs_inode_info *fi =F2FS_I (inode); -char *name; +const char *name; +int name_len;int err; inode->i_mode =le16_to_cpu (raw->i_mode);
@@ -330,13 +345,11 @@ static int recover_inode(struct inode *if2fs_mark_inode_dirty_sync (inode, true); -if (file_enc_name (inode)) - name ="<encrypted>" ; -else - name =F2FS_INODE (page)->i_name; + name =recover_printable_name (inode, raw, &name_len); -f2fs_notice (F2FS_I_SB (inode),"recover_inode: ino = %x, name = %s, inline = %x" , -ino_of_node (page), name, raw->i_inline); +f2fs_notice (F2FS_I_SB (inode),"%s: ino = %x, name = %.*s, inline = %x" , + __func__,ino_of_node (page), name_len, name, + raw->i_inline);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 692/877 f2fs: fix dentry folio leak in find_in_level
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guanghui Yang <[email protected]>
[ Upstream commit cca7d3e30bf30333314e31bc70b9a739f1342167 ]
find_in_level() gets a dentry folio with f2fs_find_data_folio() before calling find_in_block(). If find_in_block() returns an error, the function stores the error in res_folio and breaks out of the loop without dropping the dentry folio.
This leaks the folio reference on the find_in_block() error path. Drop the dentry folio before returning the error to the caller.
--- fs/f2fs/dir.c | 1 + 1 file changed, 1 insertion(+)
fs/f2fs/dir.c +1 -0
@@ -298,6 +298,7 @@ start_find_bucket: de =find_in_block (dir, dentry_page, fname, &max_slots, use_hash);if (IS_ERR (de)) { +f2fs_put_page (dentry_page,0 ); *res_page =ERR_CAST (de); de =NULL ;break ;
Greg Kroah-Hartman
maintainerPATCH 693/877 f2fs: embed f2fs_gc_kthread in f2fs_sb_info
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chao Yu <[email protected]>
[ Upstream commit 3d7bca9d583793bb7d0bac0d95a24ddd2e129eed ]
Instead of allocating f2fs_gc_kthread dynamically, embed it in f2fs_sb_info. This simplifies lifetime management and prepares for fixing race conditions during teardown.
- __sbi_store - remount|shutdown
- f2fs_stop_gc_thread
- access sbi->gc_thread
- sbi->gc_thread = NULL
- access sbi->gc_thread->f2fs_gc_task
--- fs/f2fs/debug.c | 4 ---- fs/f2fs/f2fs.h | 29 ++++++++++++++++++++++++++++- fs/f2fs/gc.c | 36 +++++++++++++++--------------------- fs/f2fs/gc.h | 25 ------------------------- fs/f2fs/segment.c | 9 ++++----- fs/f2fs/super.c | 4 ++-- fs/f2fs/sysfs.c | 18 +++++++++--------- 7 files changed, 58 insertions(+), 67 deletions(-)
fs/f2fs/debug.c +0 -4
@@ -285,10 +285,6 @@ static void update_mem_info(struct f2fs_ get_cache: si->cache_mem =0 ; -/* build gc */ -if (sbi->gc_thread) - si->cache_mem +=sizeof (struct f2fs_gc_kthread ); -/* build merge flush thread */ if (SM_I (sbi)->fcc_info) si->cache_mem +=sizeof (struct flush_cmd_control );
fs/f2fs/f2fs.h +28 -1
@@ -1578,6 +1578,33 @@ struct decompress_io_ctx {#define MAX_COMPRESS_LOG_SIZE 8#define MAX_COMPRESS_WINDOW_SIZE (log_size) ((PAGE_SIZE) << (log_size)) +struct f2fs_gc_kthread { +struct task_struct *f2fs_gc_task; +wait_queue_head_t gc_wait_queue_head; + +/* for gc sleep time */ +unsigned int urgent_sleep_time; +unsigned int min_sleep_time; +unsigned int max_sleep_time; +unsigned int no_gc_sleep_time; + +/* for changing gc mode */ +bool gc_wake; + +/* for GC_MERGE mount option */ +wait_queue_head_t fggc_wq;/* +* caller of f2fs_balance_fs() +* will wait on this wait queue. +*/ + +/* for gc control for zoned devices */ +unsigned int no_zoned_gc_percent; +unsigned int boost_zoned_gc_percent; +unsigned int valid_thresh_ratio; +unsigned int boost_gc_multiple; +unsigned int boost_gc_greedy; +}; +struct f2fs_sb_info {struct super_block *sb;/* pointer to VFS super block */ struct proc_dir_entry *s_proc;/* proc entry */
@@ -1702,7 +1729,7 @@ struct f2fs_sb_info {* semaphore for GC, avoid * race between GC and GC or CP */ -struct f2fs_gc_kthread *gc_thread;/* GC thread */ +struct f2fs_gc_kthread gc_thread;/* GC thread */ struct atgc_management am;/* atgc management */ unsigned int cur_victim_sec;/* current victim section num */ unsigned int gc_mode;/* current GC state */
fs/f2fs/gc.c +15 -21
@@ -31,9 +31,9 @@ static unsigned int count_bits(const unsstatic int gc_thread_func (void *data) {struct f2fs_sb_info *sbi = data; -struct f2fs_gc_kthread *gc_th = sbi->gc_thread; -wait_queue_head_t *wq = &sbi->gc_thread->gc_wait_queue_head; -wait_queue_head_t *fggc_wq = &sbi->gc_thread->fggc_wq; +struct f2fs_gc_kthread *gc_th = &sbi->gc_thread; +wait_queue_head_t *wq = &sbi->gc_thread.gc_wait_queue_head; +wait_queue_head_t *fggc_wq = &sbi->gc_thread.fggc_wq;unsigned int wait_ms;struct f2fs_gc_control gc_control = { .victim_segno =NULL_SEGNO ,
@@ -191,13 +191,9 @@ next:int f2fs_start_gc_thread (struct f2fs_sb_info *sbi) { -struct f2fs_gc_kthread *gc_th; +struct f2fs_gc_kthread *gc_th = &sbi->gc_thread;dev_t dev = sbi->sb->s_bdev->bd_dev; - gc_th =f2fs_kmalloc (sbi,sizeof (struct f2fs_gc_kthread ),GFP_KERNEL ); -if (!gc_th) -return -ENOMEM ; - gc_th->urgent_sleep_time =DEF_GC_THREAD_URGENT_SLEEP_TIME ; gc_th->valid_thresh_ratio =DEF_GC_THREAD_VALID_THRESH_RATIO ; gc_th->boost_gc_multiple =BOOST_GC_MULTIPLE ;
@@ -219,16 +215,14 @@ int f2fs_start_gc_thread(struct f2fs_sb_ gc_th->gc_wake = false; - sbi->gc_thread = gc_th; -init_waitqueue_head (&sbi->gc_thread->gc_wait_queue_head); -init_waitqueue_head (&sbi->gc_thread->fggc_wq); - sbi->gc_thread->f2fs_gc_task =kthread_run (gc_thread_func, sbi, +init_waitqueue_head (&gc_th->gc_wait_queue_head); +init_waitqueue_head (&gc_th->fggc_wq); + gc_th->f2fs_gc_task =kthread_run (gc_thread_func, sbi,"f2fs_gc-%u:%u" ,MAJOR (dev),MINOR (dev));if (IS_ERR (gc_th->f2fs_gc_task)) {int err =PTR_ERR (gc_th->f2fs_gc_task); -kfree (gc_th); - sbi->gc_thread =NULL ; + gc_th->f2fs_gc_task =NULL ;return err; }
@@ -237,14 +231,14 @@ int f2fs_start_gc_thread(struct f2fs_sb_void f2fs_stop_gc_thread (struct f2fs_sb_info *sbi) { -struct f2fs_gc_kthread *gc_th = sbi->gc_thread; +struct f2fs_gc_kthread *gc_th = &sbi->gc_thread; -if (!gc_th) +if (!gc_th->f2fs_gc_task)return ; +kthread_stop (gc_th->f2fs_gc_task); + gc_th->f2fs_gc_task =NULL ;wake_up_all (&gc_th->fggc_wq); -kfree (gc_th); - sbi->gc_thread =NULL ; }static int select_gc_type (struct f2fs_sb_info *sbi,int gc_type)
@@ -406,7 +400,7 @@ static inline unsigned int get_gc_cost(sreturn get_seg_entry (sbi, segno)->ckpt_valid_blocks;if (p->one_time_gc && (get_valid_blocks (sbi, segno, true) >= -CAP_BLKS_PER_SEC (sbi) * sbi->gc_thread->valid_thresh_ratio / +CAP_BLKS_PER_SEC (sbi) * sbi->gc_thread.valid_thresh_ratio /100 ))return UINT_MAX ;
@@ -1795,9 +1789,9 @@ static int do_garbage_collect(struct f2fif (f2fs_sb_has_blkzoned (sbi) && !has_enough_free_blocks (sbi, - sbi->gc_thread->boost_zoned_gc_percent)) + sbi->gc_thread.boost_zoned_gc_percent)) window_granularity *= - sbi->gc_thread->boost_gc_multiple; + sbi->gc_thread.boost_gc_multiple; end_segno = start_segno + window_granularity; }
fs/f2fs/gc.h +0 -25
@@ -45,32 +45,7 @@#define NR_GC_CHECKPOINT_SECS (3)/* data/node/dentry sections */ -struct f2fs_gc_kthread { -struct task_struct *f2fs_gc_task; -wait_queue_head_t gc_wait_queue_head; -/* for gc sleep time */ -unsigned int urgent_sleep_time; -unsigned int min_sleep_time; -unsigned int max_sleep_time; -unsigned int no_gc_sleep_time; - -/* for changing gc mode */ -bool gc_wake; - -/* for GC_MERGE mount option */ -wait_queue_head_t fggc_wq;/* -* caller of f2fs_balance_fs() -* will wait on this wait queue. -*/ - -/* for gc control for zoned devices */ -unsigned int no_zoned_gc_percent; -unsigned int boost_zoned_gc_percent; -unsigned int valid_thresh_ratio; -unsigned int boost_gc_multiple; -unsigned int boost_gc_greedy; -};struct gc_inode_list {struct list_head ilist;
fs/f2fs/segment.c +4 -5
@@ -441,15 +441,14 @@ void f2fs_balance_fs(struct f2fs_sb_infof2fs_submit_merged_write (sbi,DATA );f2fs_submit_all_merged_ipu_writes (sbi); -if (test_opt (sbi,GC_MERGE ) && sbi->gc_thread && - sbi->gc_thread->f2fs_gc_task) { +if (test_opt (sbi,GC_MERGE ) && sbi->gc_thread.f2fs_gc_task) {DEFINE_WAIT (wait); -prepare_to_wait (&sbi->gc_thread->fggc_wq, &wait, +prepare_to_wait (&sbi->gc_thread.fggc_wq, &wait,TASK_UNINTERRUPTIBLE ); -wake_up (&sbi->gc_thread->gc_wait_queue_head); +wake_up (&sbi->gc_thread.gc_wait_queue_head);io_schedule (); -finish_wait (&sbi->gc_thread->fggc_wq, &wait); +finish_wait (&sbi->gc_thread.fggc_wq, &wait); }else {struct f2fs_gc_control gc_control = { .victim_segno =NULL_SEGNO ,
fs/f2fs/super.c +2 -2
@@ -2492,11 +2492,11 @@ static int f2fs_remount(struct super_bloif ((*flags &SB_RDONLY ) || (F2FS_OPTION (sbi).bggc_mode ==BGGC_MODE_OFF && !test_opt (sbi,GC_MERGE ))) { -if (sbi->gc_thread) { +if (sbi->gc_thread.f2fs_gc_task) {f2fs_stop_gc_thread (sbi); need_restart_gc = true; } - }else if (!sbi->gc_thread) { + }else if (!sbi->gc_thread.f2fs_gc_task) { err =f2fs_start_gc_thread (sbi);if (err) goto restore_opts;
fs/f2fs/sysfs.c +9 -9
@@ -74,7 +74,7 @@ static ssize_t f2fs_sbi_show(struct f2fsstatic unsigned char *__struct_ptr (struct f2fs_sb_info *sbi,int struct_type) {if (struct_type ==GC_THREAD ) -return (unsigned char *)sbi->gc_thread; +return (unsigned char *)&sbi->gc_thread;else if (struct_type ==SM_INFO )return (unsigned char *)SM_I (sbi);else if (struct_type ==DCC_INFO )
@@ -631,20 +631,20 @@ out: sbi->gc_mode =GC_NORMAL ; }else if (t ==1 ) { sbi->gc_mode =GC_URGENT_HIGH ; -if (sbi->gc_thread) { - sbi->gc_thread->gc_wake = true; +if (sbi->gc_thread.f2fs_gc_task) { + sbi->gc_thread.gc_wake = true;wake_up_interruptible_all ( - &sbi->gc_thread->gc_wait_queue_head); + &sbi->gc_thread.gc_wait_queue_head);wake_up_discard_thread (sbi, true); } }else if (t ==2 ) { sbi->gc_mode =GC_URGENT_LOW ; }else if (t ==3 ) { sbi->gc_mode =GC_URGENT_MID ; -if (sbi->gc_thread) { - sbi->gc_thread->gc_wake = true; +if (sbi->gc_thread.f2fs_gc_task) { + sbi->gc_thread.gc_wake = true;wake_up_interruptible_all ( - &sbi->gc_thread->gc_wait_queue_head); + &sbi->gc_thread.gc_wait_queue_head); } }else {return -EINVAL ;
@@ -901,14 +901,14 @@ out:if (!strcmp (a->attr.name,"gc_boost_gc_multiple" )) {if (t <1 || t >SEGS_PER_SEC (sbi))return -EINVAL ; - sbi->gc_thread->boost_gc_multiple = (unsigned int )t; + sbi->gc_thread.boost_gc_multiple = (unsigned int )t;return count; }if (!strcmp (a->attr.name,"gc_boost_gc_greedy" )) {if (t >GC_GREEDY )return -EINVAL ; - sbi->gc_thread->boost_gc_greedy = (unsigned int )t; + sbi->gc_thread.boost_gc_greedy = (unsigned int )t;return count; }
Greg Kroah-Hartman
maintainerPATCH 694/877 f2fs: Convert clear_node_page_dirty() to clear_node_folio_dirty()
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: "Matthew Wilcox (Oracle)" <[email protected]>
[ Upstream commit f16ebe0de73274fd1cf885b30cc4fe42d2a1821a ]
Both callers have a folio so pass it in, removing five calls to compound_head().
Backport to 6.12: retain the page-based node interfaces and pass page_folio() at the two existing cleanup call sites. Use F2FS_M_SB(folio->mapping), since this tree has no F2FS_F_SB() helper.
Keep a folio reference in __get_node_page() and convert its existing uptodate clearing and error reporting to use that folio. This preserves behavior while allowing the one-line error-path change in upstream commit 5b86eab84ac8e9289b5afc52ef88ab18ba5bacab to cherry-pick cleanly. No new functions or wider node-interface conversions are needed.
Stable-dep-of: 5b86eab84ac8 ("f2fs: fix to clear dirty flag on folio in error path")
--- fs/f2fs/node.c | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-)
fs/f2fs/node.c +12 -10
@@ -125,14 +125,14 @@ bool f2fs_available_free_memory(struct freturn res; } -static void clear_node_page_dirty (struct page *page) +static void clear_node_folio_dirty (struct folio *folio) { -if (PageDirty (page)) { -f2fs_clear_page_cache_dirty_tag (page_folio (page)); -clear_page_dirty_for_io (page); -dec_page_count (F2FS_P_SB (page),F2FS_DIRTY_NODES ); +if (folio_test_dirty (folio)) { +f2fs_clear_page_cache_dirty_tag (folio); +folio_clear_dirty_for_io (folio); +dec_page_count (F2FS_M_SB (folio->mapping),F2FS_DIRTY_NODES ); } -ClearPageUptodate (page); +folio_clear_uptodate (folio); }static struct page *get_current_nat_page (struct f2fs_sb_info *sbi,nid_t nid)
@@ -941,7 +941,7 @@ static int truncate_node(struct dnode_off2fs_inode_synced (dn->inode); } -clear_node_page_dirty (dn->node_page); +clear_node_folio_dirty (page_folio (dn->node_page));set_sbi_flag (sbi,SBI_IS_DIRTY ); index =page_folio (dn->node_page)->index;
@@ -1394,7 +1394,7 @@ struct page *f2fs_new_node_page(struct dinc_valid_inode_count (sbi);return page; fail: -clear_node_page_dirty (page); +clear_node_folio_dirty (page_folio (page));f2fs_put_page (page,1 );return ERR_PTR (err); }
@@ -1476,6 +1476,7 @@ static struct page *__get_node_page(stru struct page *parent, int start) {struct page *page; +struct folio *folio;int err;if (!nid)
@@ -1487,6 +1488,7 @@ repeat:if (!page)return ERR_PTR (-ENOMEM ); + folio =page_folio (page); err =read_node_page (page,0 );if (err <0 ) { goto out_put_err;
@@ -1526,11 +1528,11 @@ page_hit:f2fs_handle_error (sbi,ERROR_INCONSISTENT_FOOTER ); err = -EFSCORRUPTED ; out_err: -ClearPageUptodate (page); +folio_clear_uptodate (folio); out_put_err:/* ENOENT comes from read_node_page which is not an error. */ if (err != -ENOENT ) -f2fs_handle_page_eio (sbi,page_folio (page),NODE ); +f2fs_handle_page_eio (sbi, folio,NODE );f2fs_put_page (page,1 );return ERR_PTR (err); }
Greg Kroah-Hartman
maintainerPATCH 695/877 f2fs: fix to clear dirty flag on folio in error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chao Yu <[email protected]>
[ Upstream commit 5b86eab84ac8e9289b5afc52ef88ab18ba5bacab ]
If node block is corrupted due to chksum mismatch or inconsistent footer info, it needs to drop clear flag of node folio, in order to persist inconsistent node data to storage.
--- fs/f2fs/node.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
fs/f2fs/node.c +1 -1
@@ -1528,7 +1528,7 @@ page_hit:f2fs_handle_error (sbi,ERROR_INCONSISTENT_FOOTER ); err = -EFSCORRUPTED ; out_err: -folio_clear_uptodate (folio); +clear_node_folio_dirty (folio); out_put_err:/* ENOENT comes from read_node_page which is not an error. */ if (err != -ENOENT )
Greg Kroah-Hartman
maintainerPATCH 696/877 f2fs: accurately adjust free_sections during free_segment_range
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Daeho Jeong <[email protected]>
[ Upstream commit 8c963d1738fdca400082ff5f9d99e083de4f4e70 ]
In free_segment_range(), MAIN_SECS(sbi) is temporarily reduced by secs to restrict block allocation to the safe remaining main area while valid blocks in the truncated range are evacuated by GC.
However, FREE_I(sbi)->free_sections tracks the total number of free sections across the whole filesystem. If any sections within the truncated range were already free upon entering free_segment_range(), failing to deduct them from free_sections causes the filesystem to overestimate available free sections in the active, reduced main area. This leads to inconsistent free section accounting during GC data migration and can trigger unexpected allocation failures or assertion errors when space is tight.
Fix this by calculating the number of already-free sections in the truncated range, deducting them from free_sections upon entering free_segment_range(), and restoring them on exit.
--- fs/f2fs/gc.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-)
fs/f2fs/gc.c +14 -1
@@ -2144,8 +2144,9 @@ int f2fs_gc_range(struct f2fs_sb_info *sstatic int free_segment_range (struct f2fs_sb_info *sbi,unsigned int secs,bool dry_run) { -unsigned int next_inuse, start, end; +unsigned int secno, next_inuse, start, end, end_secno;struct cp_control cpc = {CP_RESIZE ,0 ,0 ,0 }; +unsigned int freed_secs =0 ;int gc_mode, gc_type;int err =0 ;int type;
@@ -2154,6 +2155,7 @@ static int free_segment_range(struct f2fMAIN_SECS (sbi) -= secs; start =MAIN_SECS (sbi) *SEGS_PER_SEC (sbi); end =MAIN_SEGS (sbi) -1 ; + end_secno =GET_SEC_FROM_SEG (sbi, end);mutex_lock (&DIRTY_I (sbi)->seglist_lock);for (gc_mode =0 ; gc_mode <MAX_GC_POLICY ; gc_mode++)
@@ -2165,6 +2167,14 @@ static int free_segment_range(struct f2f sbi->next_victim_seg[gc_type] =NULL_SEGNO ;mutex_unlock (&DIRTY_I (sbi)->seglist_lock); +spin_lock (&FREE_I (sbi)->segmap_lock); +for (secno =MAIN_SECS (sbi); secno <= end_secno; secno++) { +if (!test_bit (secno,FREE_I (sbi)->free_secmap)) + freed_secs++; + } +FREE_I (sbi)->free_sections -= freed_secs; +spin_unlock (&FREE_I (sbi)->segmap_lock); +/* Move out cursegs from the target range */ for (type =CURSEG_HOT_DATA ; type <NR_CURSEG_TYPE ; type++) { err =f2fs_allocate_segment_for_resize (sbi, type, start, end);
@@ -2189,6 +2199,9 @@ static int free_segment_range(struct f2ff2fs_bug_on (sbi,1 ); } out: +spin_lock (&FREE_I (sbi)->segmap_lock); +FREE_I (sbi)->free_sections += freed_secs; +spin_unlock (&FREE_I (sbi)->segmap_lock);MAIN_SECS (sbi) += secs;return err; }
Greg Kroah-Hartman
maintainerPATCH 697/877 drm/amdgpu: Fix missing unwind in amdgpu_ib_schedule() error path
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Srinivasan Shanmugam <[email protected]>
[ Upstream commit ba038065655c45728be346d0b174a6da08d8a5c5 ]
amdgpu_ib_schedule() returns early after calling amdgpu_ring_undo(). This skips the common free_fence cleanup path. Other error paths were already changed to use goto free_fence, but this one was missed.
Change the early return to goto free_fence so all error paths clean up the same way.
Fixes the below:drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c:232 amdgpu_ib_schedule()
warn: missing unwind goto?
drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c
124 int amdgpu_ib_schedule(struct amdgpu_ring *ring, unsigned int num_ibs,
125 struct amdgpu_ib *ibs, struct amdgpu_job *job,
126 struct dma_fence **f)
127 {
...
224
225 if (ring->funcs->insert_start)
226 ring->funcs->insert_start(ring);
227
228 if (job) {
229 r = amdgpu_vm_flush(ring, job, need_pipe_sync);
230 if (r) {
231 amdgpu_ring_undo(ring);--> 232 return r;
The patch changed the other error paths to goto free_fence but
this one was accidentally skipped.
233 }
234 }
235
236 amdgpu_ring_ib_begin(ring);
...
338
339 free_fence:
340 if (!job)
341 kfree(af);
342 return r;
343 }Stable-dep-of: 6760f5cb12d2 ("drm/amdgpu: avoid force-completing uninitialized UVD rings")
--- drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c +1 -1
@@ -217,7 +217,7 @@ int amdgpu_ib_schedule(struct amdgpu_rin r =amdgpu_vm_flush (ring, job, need_pipe_sync);if (r) {amdgpu_ring_undo (ring); -return r; + goto free_fence; } }
Greg Kroah-Hartman
maintainerPATCH 698/877 drm/amdgpu: add a helper to calculate ring distance
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Deucher <[email protected]>
[ Upstream commit 08e7d6c3cee880bd3ec3eb14c478f9fa805b0bdc ]
Add a helper to calculate the distance in DWs between two wptrs.
Stable-dep-of: 6760f5cb12d2 ("drm/amdgpu: avoid force-completing uninitialized UVD rings")
--- drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h +12 -6
@@ -431,6 +431,17 @@ static inline void amdgpu_ring_write_mul ring->count_dw -= count_dw; } +static inline unsigned int amdgpu_ring_get_dw_distance (struct amdgpu_ring *ring, +u64 start_wptr,u64 end_wptr) +{ +unsigned int start = start_wptr & ring->buf_mask; +unsigned int end = end_wptr & ring->buf_mask; + +if (end < start) + end += ring->ring_size >>2 ; +return end - start; +} +/** * amdgpu_ring_patch_cond_exec - patch dw count of conditional execute * @ring: amdgpu_ring structure
@@ -441,18 +452,13 @@ static inline void amdgpu_ring_write_mulstatic inline void amdgpu_ring_patch_cond_exec (struct amdgpu_ring *ring,unsigned int offset) { -unsigned cur; -if (!ring->funcs->init_cond_exec)return ;WARN_ON (offset > ring->buf_mask);WARN_ON (ring->ring[offset] !=0 ); - cur = (ring->wptr -1 ) & ring->buf_mask; -if (cur < offset) - cur += ring->ring_size >>2 ; - ring->ring[offset] = cur - offset; + ring->ring[offset] =amdgpu_ring_get_dw_distance (ring, offset, ring->wptr -1 ); }#define amdgpu_mes_ctx_get_offs_gpu_addr (ring, offset) \
Greg Kroah-Hartman
maintainerPATCH 699/877 drm/amdgpu: plumb timedout fence through to force completion
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Alex Deucher <[email protected]>
[ Upstream commit c184df870db1e328691ea0fbb7d0e59efd9d3f9f ]
When we do a full adapter reset, if we know the timedout fence mark the fence with -ETIME rather than -ECANCELED so it gets properly handled by userspace.
v2: rebase
Adapt this dependency to 6.12 without importing newer queue-reset infrastructure. Drop the SDMA/VCN/JPEG reset hunks and the adjacent ring-reset helper context because those functions do not exist here. Keep the two-argument force-completion API and its fence error handling.
Use &job->hw_fence.base for this branch's embedded job fence, and update the additional per-ring timeout caller in amdgpu_job.c to pass that fence. Preserve the existing full-reset job-fence clearing and resubmission flow. The UVD resume caller now matches the context required by the target fix. No functions are added.
The prerequisite ba038065655c also introduced a goto to the absent free_fence label in amdgpu_ib_schedule(). Restore the original return r:
6.12 embeds job fences and allocates non-job fences later, in amdgpu_fence_emit(), so this VM-flush failure path has no new fence to free. This removes the pre-existing build failure without importing the newer fence allocation and cleanup infrastructure.
[ sashal: Reduced backport -- upstream c184df870db1e touches 9 file(s), this
backport carries 7. Not backported here:
drivers/gpu/drm/amd/amdgpu/amdgpu_sdma.c drivers/gpu/drm/amd/amdgpu/amdgpu_vcn.c drivers/gpu/drm/amd/amdgpu/vcn_v4_0_3.c drivers/gpu/drm/amd/amdgpu/vcn_v5_0_1.c
This note is generated from the file lists only; see the resolution record for the reasoning. ]
Stable-dep-of: 6760f5cb12d2 ("drm/amdgpu: avoid force-completing uninitialized UVD rings")
--- drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_device.c | 6 +++++- drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c | 25 ++++++++++++++++++++++--- drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_job.c | 2 +- drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h | 3 ++- drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c | 2 +- 7 files changed, 33 insertions(+), 9 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_debugfs.c +1 -1
@@ -1962,7 +1962,7 @@ static int amdgpu_debugfs_ib_preempt(voi/* swap out the old fences */ amdgpu_ib_preempt_fences_swap (ring, fences); -amdgpu_fence_driver_force_completion (ring); +amdgpu_fence_driver_force_completion (ring,NULL );/* resubmit unfinished jobs */ amdgpu_ib_preempt_job_recovery (&ring->sched);
drivers/gpu/drm/amd/amdgpu/amdgpu_device.c +5 -1
@@ -5470,6 +5470,7 @@ int amdgpu_device_pre_asic_reset(struct {int i, r =0 ;struct amdgpu_job *job =NULL ; +struct dma_fence *fence =NULL ;struct amdgpu_device *tmp_adev = reset_context->reset_req_dev;bool need_full_reset =test_bit (AMDGPU_NEED_FULL_RESET , &reset_context->flags);
@@ -5482,6 +5483,9 @@ int amdgpu_device_pre_asic_reset(structamdgpu_fence_driver_isr_toggle (adev, true); +if (job) + fence = &job->hw_fence.base; +/* block all schedulers and reset given job's ring */ for (i =0 ; i <AMDGPU_MAX_RINGS ; ++i) {struct amdgpu_ring *ring = adev->rings[i];
@@ -5495,7 +5499,7 @@ int amdgpu_device_pre_asic_reset(structamdgpu_fence_driver_clear_job_fences (ring);/* after all hw jobs are reset, hw fence is meaningless, so force_completion */ -amdgpu_fence_driver_force_completion (ring); +amdgpu_fence_driver_force_completion (ring, fence); }amdgpu_fence_driver_isr_toggle (adev, false);
drivers/gpu/drm/amd/amdgpu/amdgpu_fence.c +22 -3
@@ -594,7 +594,7 @@ void amdgpu_fence_driver_hw_fini(struct r = -ENODEV ;/* no need to trigger GPU reset as we are unloading */ if (r) -amdgpu_fence_driver_force_completion (ring); +amdgpu_fence_driver_force_completion (ring,NULL ); if (!drm_dev_is_unplugged(adev_to_drm(adev)) && ring->fence_drv.irq_src &&
@@ -739,11 +739,30 @@ void amdgpu_fence_driver_set_error(struc* amdgpu_fence_driver_force_completion - force signal latest fence of ring * * @ring: fence of the ring to signal +* @timedout_fence: fence of the timedout job * */ -void amdgpu_fence_driver_force_completion (struct amdgpu_ring *ring) +void amdgpu_fence_driver_force_completion (struct amdgpu_ring *ring, +struct dma_fence *timedout_fence) { -amdgpu_fence_driver_set_error (ring, -ECANCELED ); +struct amdgpu_fence_driver *drv = &ring->fence_drv; +unsigned long flags; + +spin_lock_irqsave (&drv->lock, flags); +for (unsigned int i =0 ; i <= drv->num_fences_mask; ++i) { +struct dma_fence *fence; + + fence =rcu_dereference_protected (drv->fences[i], +lockdep_is_held (&drv->lock)); +if (fence && !dma_fence_is_signaled_locked (fence)) { +if (fence == timedout_fence) +dma_fence_set_error (fence, -ETIME ); +else +dma_fence_set_error (fence, -ECANCELED ); + } + } +spin_unlock_irqrestore (&drv->lock, flags); +amdgpu_fence_write (ring, ring->fence_drv.sync_seq);amdgpu_fence_process (ring); }
drivers/gpu/drm/amd/amdgpu/amdgpu_ib.c +1 -1
@@ -217,7 +217,7 @@ int amdgpu_ib_schedule(struct amdgpu_rin r =amdgpu_vm_flush (ring, job, need_pipe_sync);if (r) {amdgpu_ring_undo (ring); - goto free_fence; +return r; } }
drivers/gpu/drm/amd/amdgpu/amdgpu_job.c +1 -1
@@ -148,7 +148,7 @@ static enum drm_gpu_sched_stat amdgpu_joif (amdgpu_ring_sched_ready (ring))drm_sched_stop (&ring->sched, s_job);atomic_inc (&ring->adev->gpu_reset_counter); -amdgpu_fence_driver_force_completion (ring); +amdgpu_fence_driver_force_completion (ring, &job->hw_fence.base);if (amdgpu_ring_sched_ready (ring))drm_sched_start (&ring->sched); goto exit;
drivers/gpu/drm/amd/amdgpu/amdgpu_ring.h +2 -1
@@ -146,7 +146,8 @@ extern const struct drm_sched_backend_opvoid amdgpu_fence_driver_clear_job_fences (struct amdgpu_ring *ring);void amdgpu_fence_driver_set_error (struct amdgpu_ring *ring,int error); -void amdgpu_fence_driver_force_completion (struct amdgpu_ring *ring); +void amdgpu_fence_driver_force_completion (struct amdgpu_ring *ring, +struct dma_fence *timedout_fence);int amdgpu_fence_driver_init_ring (struct amdgpu_ring *ring); int amdgpu_fence_driver_start_ring(struct amdgpu_ring *ring,
drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c +1 -1
@@ -516,7 +516,7 @@ int amdgpu_uvd_resume(struct amdgpu_devi }memset_io (ptr,0 , size);/* to restore uvd fence seq */ -amdgpu_fence_driver_force_completion (&adev->uvd.inst[i].ring); +amdgpu_fence_driver_force_completion (&adev->uvd.inst[i].ring,NULL ); } }return 0 ;
Greg Kroah-Hartman
maintainerPATCH 700/877 drm/amdgpu: avoid force-completing uninitialized UVD rings
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bob Zhou <[email protected]>
[ Upstream commit 6760f5cb12d2366ddd58a2d8637f7583d73f596b ]
uvd_v7_0_sw_init() does not initialize the UVD decode ring for an SR-IOV VF. However, amdgpu_uvd_resume() unconditionally force-completes the decode ring when restoring its fence sequence.
Skip fence completion when the fence driver is not initialized.
--- drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_uvd.c +2 -1
@@ -516,7 +516,8 @@ int amdgpu_uvd_resume(struct amdgpu_devi }memset_io (ptr,0 , size);/* to restore uvd fence seq */ -amdgpu_fence_driver_force_completion (&adev->uvd.inst[i].ring,NULL ); +if (adev->uvd.inst[i].ring.fence_drv.initialized) +amdgpu_fence_driver_force_completion (&adev->uvd.inst[i].ring,NULL ); } }return 0 ;
Greg Kroah-Hartman
maintainerPATCH 701/877 drm/nouveau/disp/r535: Add scanline position support + head state support
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lyude Paul <[email protected]>
[ Upstream commit 804cb093b245c752f15d17186e0d404f10303593 ]
That's right! It looks like this never actually got finished, something which I just noticed today when I saw this fun message spamming one of my test machine's kernel logs when enabling display debug output for nouveau:
[drm:drm_crtc_vblank_helper_get_vblank_timestamp_internal] crtc 0 : scanoutpos query failed.
So it looks like we've been falling back to DRM's core fallback for a while now, whoops.
So, while it seems that we do have the option of doing this through GSP - that doesn't seem like a great idea. Mainly because reading this from GSP would involve a lot more latency then we should have for vblank handling due to the RPC communication. So instead of implementing that, just use gv100_head_state and gv100_head_rgpos for implementing .state and .rgpos. It seems to work perfectly fine!
--- drivers/gpu/drm/nouveau/nvkm/engine/disp/gv100.c | 4 ++-- drivers/gpu/drm/nouveau/nvkm/engine/disp/head.h | 2 ++ drivers/gpu/drm/nouveau/nvkm/engine/disp/r535.c | 8 ++------ 3 files changed, 6 insertions(+), 8 deletions(-)
drivers/gpu/drm/nouveau/nvkm/engine/disp/gv100.c +2 -2
@@ -253,7 +253,7 @@ gv100_head_vblank_get(struct nvkm_head *nvkm_mask (device,0x611d80 + (head->id *4 ),0x00000004 ,0x00000004 ); } -static void +void gv100_head_rgpos (struct nvkm_head *head,u16 *hline,u16 *vline) {struct nvkm_device *device = head->disp->engine.subdev.device;
@@ -263,7 +263,7 @@ gv100_head_rgpos(struct nvkm_head *head, *hline =nvkm_rd32 (device,0x616334 + hoff) &0x0000ffff ; } -static void +void gv100_head_state (struct nvkm_head *head,struct nvkm_head_state *state) {struct nvkm_device *device = head->disp->engine.subdev.device;
drivers/gpu/drm/nouveau/nvkm/engine/disp/head.h +2 -0
@@ -53,6 +53,8 @@ void gf119_head_rgclk(struct nvkm_head *int gv100_head_cnt (struct nvkm_disp *,unsigned long *);int gv100_head_new (struct nvkm_disp *,int id); +void gv100_head_state (struct nvkm_head *head,struct nvkm_head_state *state); +void gv100_head_rgpos (struct nvkm_head *head,u16 *hline,u16 *vline); #define HEAD_MSG(h,l,f,a...) do { \ struct nvkm_head *_h = (h); \
drivers/gpu/drm/nouveau/nvkm/engine/disp/r535.c +2 -6
@@ -623,14 +623,10 @@ r535_head_vblank_get(struct nvkm_head *hnvkm_mask (device,0x611d80 + (head->id *4 ),0x00000002 ,0x00000002 ); } -static void -r535_head_state (struct nvkm_head *head,struct nvkm_head_state *state) -{ -} -static const struct nvkm_head_func r535_head = { - .state = r535_head_state, + .state = gv100_head_state, + .rgpos = gv100_head_rgpos, .vblank_get = r535_head_vblank_get, .vblank_put = r535_head_vblank_put, };
Greg Kroah-Hartman
maintainerPATCH 702/877 drm/amd/display: Set gpuvm min page size to 4K on dcn35/36
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 9ce3169430f1db035d491481086e2fae2552569c ]
[WHY]
Splash screen corruption on some 8K monitors.
[HOW]
Set GPUVM min page size to 4K for DCN35/36 to use the correct DML2 calculations, avoiding the corruption path observed during splash.
--- drivers/gpu/drm/amd/display/dc/dml2/dml2_translation_helper.c | 1 + 1 file changed, 1 insertion(+)
drivers/gpu/drm/amd/display/dc/dml2/dml2_translation_helper.c +1 -0
@@ -297,6 +297,7 @@ void dml2_init_socbb_params(struct dml2_ out->smn_latency_us =2 ; out->dispclk_dppclk_vco_speed_mhz =3600 ; out->pct_ideal_dram_bw_after_urgent_pixel_only =65.0 ; + out->gpuvm_min_page_size_kbytes =4 ;break ;case dml_project_dcn401:
Greg Kroah-Hartman
maintainerPATCH 703/877 drm/sysfb: simpledrm: Improve panel-size validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Zimmermann <[email protected]>
[ Upstream commit 3a75a0761914d01c7362adf1f906cc1d1762c189 ]
Validate the panel size from the device-tree node against the limitations of struct drm_display_mode. The type only stores sizes in 16-bit fields. Fail transparently on errors; do not warn.
v3:
- move comments to a more prominent place (Thierry) v2:
- only use initialized values in debugging output (Sashiko)
--- drivers/gpu/drm/tiny/simpledrm.c | 49 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-)
drivers/gpu/drm/tiny/simpledrm.c +46 -3
@@ -212,6 +212,39 @@ simplefb_get_memory_of(struct drm_devicereturn res; } +static int __simplefb_get_panel_size_mm_of (struct drm_device *dev, +struct device_node *of_panel_node, +const char *name) +{ +int ret; +u32 value; + + ret =of_property_read_u32 (of_panel_node, name, &value); +if (ret) { +drm_dbg (dev,"simplefb: cannot parse panel %s: error %d\n" , + name, ret); +return ret; + }else if (value >U16_MAX ) { +drm_dbg (dev,"simplefb: panel %s of %u exceeds maximum value\n" , + name, value); +return -EINVAL ; + } + +return value; +} + +static int simplefb_get_panel_width_mm_of (struct drm_device *dev, +struct device_node *of_panel_node) +{ +return __simplefb_get_panel_size_mm_of (dev, of_panel_node,"width-mm" ); +} + +static int simplefb_get_panel_height_mm_of (struct drm_device *dev, +struct device_node *of_panel_node) +{ +return __simplefb_get_panel_size_mm_of (dev, of_panel_node,"height-mm" ); +} +/* * Simple Framebuffer device */
@@ -781,7 +814,7 @@ static struct simpledrm_device *simpledrstruct simpledrm_device *sdev;struct drm_device *dev;int width, height, stride; -int width_mm =0 , height_mm =0 ; +u16 width_mm =0 , height_mm =0 ;struct device_node *panel_node;const struct drm_format_info *format;struct resource *res, *mem =NULL ;
@@ -844,8 +877,18 @@ static struct simpledrm_device *simpledrreturn ERR_CAST (mem); panel_node =of_parse_phandle (of_node,"panel" ,0 );if (panel_node) { -simplefb_read_u32_of (dev, panel_node,"width-mm" , &width_mm); -simplefb_read_u32_of (dev, panel_node,"height-mm" , &height_mm); +/* +* Ignore errors from parsing the physical panel +* size. Using the pre-initialized sizes of 0 will +* make drm_sysfb_mode() calculate a default physical +* size based on a resolution of 96 dpi. +*/ + ret =simplefb_get_panel_width_mm_of (dev, panel_node); +if (ret >0 ) + width_mm = ret; + ret =simplefb_get_panel_height_mm_of (dev, panel_node); +if (ret >0 ) + height_mm = ret;of_node_put (panel_node); } }else {
Greg Kroah-Hartman
maintainerPATCH 704/877 drm/sysfb: simpledrm: Improve stride validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Zimmermann <[email protected]>
[ Upstream commit df6533f11688aa30be3bb883c7637f4ffdbb7cbd ]
Validate the computed stride against the maximum value INT_MAX.
--- drivers/gpu/drm/tiny/simpledrm.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/gpu/drm/tiny/simpledrm.c +8 -2
@@ -896,9 +896,15 @@ static struct simpledrm_device *simpledrreturn ERR_PTR (-ENODEV ); }if (!stride) { - stride =drm_format_info_min_pitch (format,0 , width); -if (drm_WARN_ON (dev, !stride)) +u64 pitch =drm_format_info_min_pitch (format,0 , width); + +if (drm_WARN_ON (dev, !pitch)) { +return ERR_PTR (-EINVAL );/* driver bug */ + }else if (pitch >INT_MAX ) { +drm_warn (dev,"stride of %llu exceeds maximum\n" , pitch);return ERR_PTR (-EINVAL ); + } + stride = pitch; }/*
Greg Kroah-Hartman
maintainerPATCH 705/877 firmware: sysfb: Move bpp-depth calculation into screen_info helper
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Zimmermann <[email protected]>
[ Upstream commit 1ce4c3aeef333be1e6290ec6d1f7891c2bfc7a1f ]
Move the calculation of the bits per pixels for screen_info into a helper function. This will make it available to other callers besides the firmware code.
Stable-dep-of: 03f1a3545b72 ("drm/sysfb: simpledrm: Improve framebuffer-size validation")
--- drivers/firmware/sysfb_simplefb.c | 31 +------------------------------ drivers/video/screen_info_generic.c | 36 ++++++++++++++++++++++++++++++++++++ include/linux/screen_info.h | 2 ++ 3 files changed, 39 insertions(+), 30 deletions(-)
drivers/firmware/sysfb_simplefb.c +1 -30
@@ -35,36 +35,7 @@ __init bool sysfb_parse_mode(const strucif (type !=VIDEO_TYPE_VLFB && type !=VIDEO_TYPE_EFI )return false; -/* -* The meaning of depth and bpp for direct-color formats is -* inconsistent: -* -* - DRM format info specifies depth as the number of color -* bits; including alpha, but not including filler bits. -* - Linux' EFI platform code computes lfb_depth from the -* individual color channels, including the reserved bits. -* - VBE 1.1 defines lfb_depth for XRGB1555 as 16, but later -* versions use 15. -* - On the kernel command line, 'bpp' of 32 is usually -* XRGB8888 including the filler bits, but 15 is XRGB1555 -* not including the filler bit. -* -* It's not easily possible to fix this in struct screen_info, -* as this could break UAPI. The best solution is to compute -* bits_per_pixel from the color bits, reserved bits and -* reported lfb_depth, whichever is highest. In the loop below, -* ignore simplefb formats with alpha bits, as EFI and VESA -* don't specify alpha channels. -*/ -if (si->lfb_depth >8 ) { - bits_per_pixel =max (max3 (si->red_size + si->red_pos, - si->green_size + si->green_pos, - si->blue_size + si->blue_pos), - si->rsvd_size + si->rsvd_pos); - bits_per_pixel =max_t (u32, bits_per_pixel, si->lfb_depth); - }else { - bits_per_pixel = si->lfb_depth; - } + bits_per_pixel =__screen_info_lfb_bits_per_pixel (si);for (i =0 ; i <ARRAY_SIZE (formats); ++i) {const struct simplefb_format *f = &formats[i];
drivers/video/screen_info_generic.c +36 -0
@@ -144,3 +144,39 @@ ssize_t screen_info_resources(const strureturn pos - r; }EXPORT_SYMBOL (screen_info_resources); + +/* +* The meaning of depth and bpp for direct-color formats is +* inconsistent: +* +* - DRM format info specifies depth as the number of color +* bits; including alpha, but not including filler bits. +* - Linux' EFI platform code computes lfb_depth from the +* individual color channels, including the reserved bits. +* - VBE 1.1 defines lfb_depth for XRGB1555 as 16, but later +* versions use 15. +* - On the kernel command line, 'bpp' of 32 is usually +* XRGB8888 including the filler bits, but 15 is XRGB1555 +* not including the filler bit. +* +* It is not easily possible to fix this in struct screen_info, +* as this could break UAPI. The best solution is to compute +* bits_per_pixel from the color bits, reserved bits and +* reported lfb_depth, whichever is highest. +*/ + +u32 __screen_info_lfb_bits_per_pixel (const struct screen_info *si) +{ +u32 bits_per_pixel = si->lfb_depth; + +if (bits_per_pixel >8 ) { + bits_per_pixel =max (max3 (si->red_size + si->red_pos, + si->green_size + si->green_pos, + si->blue_size + si->blue_pos), + si->rsvd_size + si->rsvd_pos); + bits_per_pixel =max_t (u32, bits_per_pixel, si->lfb_depth); + } + +return bits_per_pixel; +} +EXPORT_SYMBOL (__screen_info_lfb_bits_per_pixel);
include/linux/screen_info.h +2 -0
@@ -128,6 +128,8 @@ static inline unsigned int screen_info_vssize_t screen_info_resources (const struct screen_info *si,struct resource *r,size_t num); +u32 __screen_info_lfb_bits_per_pixel (const struct screen_info *si); +#if defined(CONFIG_PCI )void screen_info_apply_fixups (void );struct pci_dev *screen_info_pci_dev (const struct screen_info *si);
Greg Kroah-Hartman
maintainerPATCH 706/877 drm/sysfb: simpledrm: Improve framebuffer-size validation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Thomas Zimmermann <[email protected]>
[ Upstream commit 03f1a3545b721fa7fdadd00080e237519a286a97 ]
Validate the framebuffer size from the firmware against the limitations of struct drm_display_mode. The type only stores sizes in 16-bit fields. Fail probing on errors.
v2:
- remove unused function simplefb_get_validated_int0() (Sashiko)
--- drivers/gpu/drm/tiny/simpledrm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/tiny/simpledrm.c +1 -1
@@ -54,7 +54,7 @@ static int simplefb_get_validated_int0(struct drm_device *dev, const char *name, uint32_t value) { - if (!value) { + if (!value || value > U16_MAX) { drm_err(dev, "simplefb: invalid framebuffer %s of %u\n", name, value);return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 707/877 drm/sysfb: ofdrm: Fix integer overflow in fb_size calculation
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shixiong Ou <[email protected]>
[ Upstream commit c6f48e59ece0123f6a11527ad4d89b21c2d65b87 ]
The framebuffer size calculation fb_size = linebytes * height can overflow when both values are large (e.g., 46341 * 46341 > INT_MAX). Since linebytes and height are both int types, the multiplication is performed as int * int, which results in undefined behavior on overflow.
Use check_mul_overflow() to detect and prevent this overflow, consistent with the approach used in simpledrm.c and corebootdrm.c.
--- drivers/gpu/drm/tiny/ofdrm.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/gpu/drm/tiny/ofdrm.c +5 -1
@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-2.0-only #include <linux/of_address.h> +#include <linux/overflow.h> #include <linux/pci.h> #include <linux/platform_device.h>
@@ -1182,7 +1183,10 @@ static struct ofdrm_device *ofdrm_devicereturn ERR_PTR (-EINVAL ); } - fb_size = linebytes * height; +if (check_mul_overflow (linebytes, height, &fb_size)) { +drm_err (dev,"framebuffer size exceeds maximum\n" ); +return ERR_PTR (-EINVAL ); + }/* * Try to figure out the address of the framebuffer. Unfortunately, Open
Greg Kroah-Hartman
maintainerPATCH 708/877 drm/sysfb: ofdrm: Fix is_avivo() constant comparison bug
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shixiong Ou <[email protected]>
[ Upstream commit 958f35cbb8955ca3fa439cd9f2092cb42414aa8c ]
The is_avivo() function has a logic error where it compares a constant to another constant instead of checking the device parameter:
(PCI_VENDOR_ID_ATI_R600 >= 0x9400)
--- drivers/gpu/drm/tiny/ofdrm.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/tiny/ofdrm.c +1 -1
@@ -232,7 +232,7 @@ static bool is_avivo(u32 vendor, u32 dev/* This will match most R5xx */ return (vendor ==PCI_VENDOR_ID_ATI ) && ((device >=PCI_VENDOR_ID_ATI_R520 && device <0x7800 ) || - (PCI_VENDOR_ID_ATI_R600 >=0x9400 )); + (device >=PCI_VENDOR_ID_ATI_R600 )); }static enum ofdrm_model display_get_model_of (struct drm_device *dev,struct device_node *of_node)
Greg Kroah-Hartman
maintainerPATCH 709/877 configfs:get_target() - release path as soon as we grab configfs_item reference
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Al Viro <[email protected]>
[ Upstream commit 1b25dea3867abc9bad6f0337d395c6f0ce4e4f6f ]
... and get rid of path argument - it turns into a local variable in get_target()
Stable-dep-of: a7c1290eef60 ("configfs: pin the symlink target's dirent instead of chasing ->ci_dentry")
--- fs/configfs/symlink.c | 33 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 20 deletions(-)
fs/configfs/symlink.c +13 -20
@@ -114,26 +114,21 @@ static int create_link(struct config_ite } -static int get_target (const char *symname,struct path *path, -struct config_item **target,struct super_block *sb) +static int get_target (const char *symname,struct config_item **target, +struct super_block *sb) { + struct path path __free(path_put) = {};int ret; - ret =kern_path (symname,LOOKUP_FOLLOW |LOOKUP_DIRECTORY , path); -if (!ret) { -if (path->dentry->d_sb == sb) { - *target =configfs_get_config_item (path->dentry); -if (!*target) { - ret = -ENOENT ; -path_put (path); - } - }else { - ret = -EPERM ; -path_put (path); - } - } - -return ret; + ret =kern_path (symname,LOOKUP_FOLLOW |LOOKUP_DIRECTORY , &path); +if (ret) +return ret; +if (path.dentry->d_sb != sb) +return -EPERM ; + *target =configfs_get_config_item (path.dentry); +if (!*target) +return -ENOENT ; +return 0 ; }
@@ -141,7 +136,6 @@ int configfs_symlink(struct mnt_idmap *i struct dentry *dentry, const char *symname) { int ret; -struct path path;struct configfs_dirent *sd;struct config_item *parent_item;struct config_item *target_item =NULL ;
@@ -188,7 +182,7 @@ int configfs_symlink(struct mnt_idmap *i* AV, a thoroughly annoyed bastard. */ inode_unlock (dir); - ret =get_target (symname, &path, &target_item, dentry->d_sb); + ret =get_target (symname, &target_item, dentry->d_sb);inode_lock (dir);if (ret) goto out_put;
@@ -210,7 +204,6 @@ int configfs_symlink(struct mnt_idmap *i }config_item_put (target_item); -path_put (&path); out_put:config_item_put (parent_item);
Greg Kroah-Hartman
maintainerPATCH 710/877 configfs: pin the symlink targets dirent instead of chasing ->ci_dentry
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vasileios Almpanis <[email protected]>
[ Upstream commit a7c1290eef60711c10289c056ad32ed1f2b47b12 ]
create_link() reads the target's configfs_dirent from item->ci_dentry->d_fsdata, relying on the item reference taken by get_target(). That reference pins the item, not its dentry: the dentry is pinned by DCACHE_PERSISTENT, which configfs_remove_dir() releases via simple_rmdir() while the item is still alive. A symlink racing with rmdir of its target can therefore find ->ci_dentry freed and its dirent released, triggering WARN_ON(!atomic_read(&sd->s_count)) in configfs_get().
Take the dirent in get_target() as well, under ->d_lock and atomically with the item reference, and pass it down to create_link(). A hashed dentry has not been killed yet, so its ->d_fsdata reference keeps the dirent alive there.
--- fs/configfs/symlink.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-)
fs/configfs/symlink.c +20 -4
@@ -76,9 +76,9 @@ static int configfs_get_target_path(strustatic int create_link (struct config_item *parent_item,struct config_item *item, +struct configfs_dirent *target_sd,struct dentry *dentry) { -struct configfs_dirent *target_sd = item->ci_dentry->d_fsdata;char *body;int ret;
@@ -115,6 +115,7 @@ static int create_link(struct config_itestatic int get_target (const char *symname,struct config_item **target, +struct configfs_dirent **target_sd,struct super_block *sb) { struct path path __free(path_put) = {};
@@ -125,7 +126,20 @@ static int get_target(const char *symnamreturn ret;if (path.dentry->d_sb != sb)return -EPERM ; - *target =configfs_get_config_item (path.dentry); +/* +* A hashed dentry guarantees that neither the item nor the dirent +* have been released yet, as removals unhash before dropping. +* Grab both references here. An item reference alone would not keep +* ->ci_dentry alive. +*/ +spin_lock (&path.dentry->d_lock); +if (!d_unhashed (path.dentry)) { +struct configfs_dirent *sd = path.dentry->d_fsdata; + + *target =config_item_get (sd->s_element); + *target_sd =configfs_get (sd); + } +spin_unlock (&path.dentry->d_lock);if (!*target)return -ENOENT ;return 0 ;
@@ -139,6 +153,7 @@ int configfs_symlink(struct mnt_idmap *istruct configfs_dirent *sd;struct config_item *parent_item;struct config_item *target_item =NULL ; +struct configfs_dirent *target_sd =NULL ;const struct config_item_type *type; sd = dentry->d_parent->d_fsdata;
@@ -182,7 +197,7 @@ int configfs_symlink(struct mnt_idmap *i* AV, a thoroughly annoyed bastard. */ inode_unlock (dir); - ret =get_target (symname, &target_item, dentry->d_sb); + ret =get_target (symname, &target_item, &target_sd, dentry->d_sb);inode_lock (dir);if (ret) goto out_put;
@@ -196,13 +211,14 @@ int configfs_symlink(struct mnt_idmap *i ret = type->ct_item_ops->allow_link (parent_item, target_item);if (!ret) {mutex_lock (&configfs_symlink_mutex); - ret =create_link (parent_item, target_item, dentry); + ret =create_link (parent_item, target_item, target_sd, dentry);mutex_unlock (&configfs_symlink_mutex);if (ret && type->ct_item_ops->drop_link) type->ct_item_ops->drop_link (parent_item, target_item); } +configfs_put (target_sd);config_item_put (target_item); out_put:
Greg Kroah-Hartman
maintainerPATCH 711/877 tracing: Fix memory corruption from a "STACKTRACE" histogram key
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Donggeun Yoo <[email protected]>
[ Upstream commit 7f711e62355bb3123a2ca2f97a2facbfebc678c6 ]
"cpu", "CPU", "stacktrace" and "STACKTRACE" are generic fields, defined with an offset and a size of zero so that the filter code can match them by name. parse_field() maps them onto their common_* equivalents for backward compatibility, but unlike the common_* names it hands the placeholder back to the caller instead of NULL.
create_hist_field() takes a non-NULL field as a promise that the record carries a stacktrace and picks HIST_FIELD_FN_STACK, so the __data_loc word is read from offset 0, that is from common_type, and its low 16 bits are followed as an offset into the record. What is found there becomes the length of an unbounded memcpy. Pick an event whose id is small enough that the offset stays inside its own record and the length is a kernel text address:
# cd /sys/kernel/tracing # echo 'hist:keys=STACKTRACE' > events/ftrace/print/trigger # echo hello > trace_marker
Oops: general protection fault, probably for non-canonical address RIP: 0010:rb_next+0x23/0x60 </IRQ> RIP: 0010:memcpy+0xc/0x30 event_hist_trigger+0x2e7/0x12c0 Kernel panic - not syncing: Fatal exception in interrupt
Leave the field NULL, which is what the comment above the branch says the code does and what common_stacktrace already does. FILTER_CPU and FILTER_COMM are left alone, their create_hist_field() branches never look at the field.
--- kernel/trace/trace_events_hist.c | 1 + 1 file changed, 1 insertion(+)
kernel/trace/trace_events_hist.c +1 -0
@@ -2379,6 +2379,7 @@ parse_field(struct hist_trigger_data *hi *flags |=HIST_FIELD_FL_CPU ; }else if (field && field->filter_type ==FILTER_STACKTRACE ) { *flags |=HIST_FIELD_FL_STACKTRACE ; + field =NULL ; }else {hist_err (tr,HIST_ERR_FIELD_NOT_FOUND ,errpos (field_name));
Greg Kroah-Hartman
maintainerPATCH 712/877 ipmr: account multicast table and route memory
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zihan Xi <[email protected]>
[ Upstream commit b7ee18725f2292ab554aa96a101ae42d45f008bd ]
A netadmin in a user+net namespace can create many IPv4 and IPv6 multicast routing tables with MRT_TABLE and MRT6_TABLE. Each unseen id allocates an mr_table via the shared mr_table_alloc(), links it into the per-net list, and leaves it until netns teardown. Those objects were not charged to memcg, so the host unreclaimable slab grows with the table count.
Account mr_table allocations with GFP_KERNEL_ACCOUNT and mark the IPv4/IPv6 MFC caches SLAB_ACCOUNT. This matches the established handling of IP addresses, routes and alternate interface names.
Unresolved MFC entries are still allocated from softIRQ with GFP_ATOMIC and are not charged. They expire after 10 seconds and are bounded by the socket receive queue; see commit 0079ad8e8dc3 ("ipmr: remove hard code cache_resolve_queue_len limit").
--- net/ipv4/ipmr.c | 3 ++- net/ipv4/ipmr_base.c | 2 +- net/ipv6/ip6mr.c | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-)
net/ipv4/ipmr.c +2 -1
@@ -3162,7 +3162,8 @@ int __init ip_mr_init(void) {int err; - mrt_cachep =KMEM_CACHE (mfc_cache,SLAB_HWCACHE_ALIGN |SLAB_PANIC ); + mrt_cachep =KMEM_CACHE (mfc_cache, +SLAB_HWCACHE_ALIGN |SLAB_PANIC |SLAB_ACCOUNT ); err =register_pernet_subsys (&ipmr_net_ops);if (err)
net/ipv4/ipmr_base.c +1 -1
@@ -38,7 +38,7 @@ mr_table_alloc(struct net *net, u32 id,struct mr_table *mrt;int err; - mrt =kzalloc (sizeof (*mrt),GFP_KERNEL ); + mrt =kzalloc (sizeof (*mrt),GFP_KERNEL_ACCOUNT );if (!mrt)return ERR_PTR (-ENOMEM ); mrt->id = id;
net/ipv6/ip6mr.c +1 -1
@@ -1387,7 +1387,7 @@ int __init ip6_mr_init(void) {int err; - mrt_cachep =KMEM_CACHE (mfc6_cache,SLAB_HWCACHE_ALIGN ); + mrt_cachep =KMEM_CACHE (mfc6_cache,SLAB_HWCACHE_ALIGN |SLAB_ACCOUNT );if (!mrt_cachep)return -ENOMEM ;
Greg Kroah-Hartman
maintainerPATCH 713/877 sysctl: move the "cad_pid" entry from pid_table[] to kern_reboot_table[]
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Oleg Nesterov <[email protected]>
[ Upstream commit 7170ca01623b399c97f2ae9d3e228badc1f25ea3 ]
cad_pid is global, and kill_cad_pid() is only used in the root namespace.
However, due to pid_table_root_permissions(), a non-root user can unshare pid/user namespaces and modify it from the child namespace. This makes no sense and is simply wrong.
Move it to kern_reboot_table[] where it logically belongs; this ensures that only GLOBAL_ROOT_UID can read/modify this sysctl.
Note that this patch doesn't preserve "#ifdef CONFIG_PROC_SYSCTL" around the "cad_pid"; CONFIG_PROC_SYSCTL selects CONFIG_SYSCTL, so it is always set when kern_reboot_table[] is compiled.
[6.12 dependency adaptation]
The stable tree still keeps cad_pid in the global kernel/sysctl.c table; it does not have the upstream per-PID-namespace table. Move the existing handler and entry directly from kernel/sysctl.c to kernel/reboot.c, using proc_dointvec() with a local table copy because __do_proc_dointvec() is private to sysctl.c. Leave kernel/pid.c unchanged and retain the mutable ctl_table required by the stable registration API.
Make the existing kernel_reboot_sysctls_init() an independent late initcall outside CONFIG_SYSFS so cad_pid remains available with PROC_SYSCTL=y and SYSFS=n, and does not depend on sysfs object allocation succeeding.
Prepare context for 5a88f78df753 without importing newer scheduler or timer
implementations: move the existing kick_process() declaration/stub before cad_pid and expand the empty stub, and guard the existing POSIX-only sigqueue helpers with CONFIG_POSIX_TIMERS using the upstream comment. No new functions are introduced, and the target's RCU fix is left for the target commit.
[ sashal: Reduced backport -- upstream 7170ca01623b3 touches 2 file(s), this
backport carries 4. Not backported here:
kernel/pid.c
This note is generated from the file lists only; see the resolution record for the reasoning. ]
Stable-dep-of: 5a88f78df753 ("reboot: fix cad_pid use-after-free race")
--- include/linux/sched.h | 14 ++++++++------ kernel/reboot.c | 40 +++++++++++++++++++++++++++++++++++----- kernel/signal.c | 12 +++++------- kernel/sysctl.c | 31 ------------------------------- 4 files changed, 48 insertions(+), 49 deletions(-)
include/linux/sched.h +8 -6
@@ -1675,6 +1675,14 @@ static inline char task_state_to_char(streturn task_index_to_char (task_state_index (tsk)); } +#ifdef CONFIG_SMP +extern void kick_process (struct task_struct *tsk); +#else +static inline void kick_process (struct task_struct *tsk) +{ +} +#endif +extern struct pid *cad_pid;/*
@@ -1953,12 +1961,6 @@ extern int wake_up_state(struct task_strextern int wake_up_process (struct task_struct *tsk);extern void wake_up_new_task (struct task_struct *tsk); -#ifdef CONFIG_SMP -extern void kick_process (struct task_struct *tsk); -#else -static inline void kick_process (struct task_struct *tsk) { } -#endif -extern void __set_task_comm (struct task_struct *tsk,const char *from,bool exec);static inline void set_task_comm (struct task_struct *tsk,const char *from)
kernel/reboot.c +35 -5
@@ -1280,7 +1280,32 @@ static struct attribute *reboot_attrs[] NULL, }; +#endif /* CONFIG_SYSFS */ + #ifdef CONFIG_SYSCTL +static int proc_do_cad_pid(const struct ctl_table *table, int write, void *buffer, + size_t *lenp, loff_t *ppos) +{ + struct ctl_table tmp_table = *table; + struct pid *new_pid; + pid_t tmp_pid; + int r; + + tmp_pid = pid_vnr(cad_pid); + tmp_table.data = &tmp_pid; + + r = proc_dointvec(&tmp_table, write, buffer, lenp, ppos); + if (r || !write) + return r; + + new_pid = find_get_pid(tmp_pid); + if (!new_pid) + return -ESRCH; + + put_pid(xchg(&cad_pid, new_pid)); + return 0; +} + static struct ctl_table kern_reboot_table[] = { { .procname = "poweroff_cmd",
@@ -1296,16 +1321,23 @@ static struct ctl_table kern_reboot_tabl .mode = 0644, .proc_handler = proc_dointvec, }, + { + .procname = "cad_pid", + .maxlen = sizeof(int), + .mode = 0600, + .proc_handler = proc_do_cad_pid, + }, }; -static void __init kernel_reboot_sysctls_init (void ) +static int __init kernel_reboot_sysctls_init (void ) {register_sysctl_init ("kernel" , kern_reboot_table); +return 0 ; } -#else -#define kernel_reboot_sysctls_init () do { } while (0) +late_initcall (kernel_reboot_sysctls_init);#endif /* CONFIG_SYSCTL */ +#ifdef CONFIG_SYSFS static const struct attribute_group reboot_attr_group = { .attrs = reboot_attrs, };
@@ -1325,8 +1357,6 @@ static int __init reboot_ksysfs_init(voireturn ret; } -kernel_reboot_sysctls_init (); -return 0 ; }late_initcall (reboot_ksysfs_init);
kernel/signal.c +5 -7
@@ -1936,14 +1936,10 @@ int kill_pid(struct pid *pid, int sig, i }EXPORT_SYMBOL (kill_pid); +#ifdef CONFIG_POSIX_TIMERS /* -* These functions support sending signals using preallocated sigqueue -* structures. This is needed "because realtime applications cannot -* afford to lose notifications of asynchronous events, like timer -* expirations or I/O completions". In the case of POSIX Timers -* we allocate the sigqueue structure from the timer_create. If this -* allocation fails we are able to report the failure to the application -* with an EAGAIN error. +* These functions handle POSIX timer signals. POSIX timers use +* preallocated sigqueue structs for sending signals. */ struct sigqueue *sigqueue_alloc (void ) {
@@ -2043,6 +2039,8 @@ ret: return ret; } +#endif /* CONFIG_POSIX_TIMERS */ +void do_notify_pidfd (struct task_struct *task) {struct pid *pid =task_pid (task);
kernel/sysctl.c +0 -31
@@ -1322,28 +1322,6 @@ int proc_dointvec_ms_jiffies(const struc do_proc_dointvec_ms_jiffies_conv, NULL); } -static int proc_do_cad_pid (const struct ctl_table *table,int write,void *buffer, -size_t *lenp,loff_t *ppos) -{ -struct pid *new_pid; -pid_t tmp; -int r; - - tmp =pid_vnr (cad_pid); - - r =__do_proc_dointvec (&tmp, table, write, buffer, - lenp, ppos,NULL ,NULL ); -if (r || !write) -return r; - - new_pid =find_get_pid (tmp); -if (!new_pid) -return -ESRCH ; - -put_pid (xchg (&cad_pid, new_pid)); -return 0 ; -} -/** * proc_do_large_bitmap - read/write from/to a large bitmap * @table: the sysctl table
@@ -1761,15 +1739,6 @@ static struct ctl_table kern_table[] = { .proc_handler = sysrq_sysctl_handler, },#endif -#ifdef CONFIG_PROC_SYSCTL - { - .procname = "cad_pid", - .data = NULL, - .maxlen = sizeof (int), - .mode = 0600, - .proc_handler = proc_do_cad_pid, - }, -#endif { .procname = "threads-max", .data = NULL,
Greg Kroah-Hartman
maintainerPATCH 714/877 reboot: fix cad_pid use-after-free race
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 5a88f78df753993469dab4d1831f8fb4256a9468 ]
cad_pid is a single kernel-wide struct pid pointer. proc_do_cad_pid() reads it and passes it to pid_vnr() without protecting the lifetime of the referenced struct pid. A concurrent writer can replace cad_pid and drop the final reference to the old struct pid after the reader has loaded the pointer but before pid_vnr() has finished dereferencing it, causing a use-after-free.
kill_cad_pid() has the same lifetime race when it passes cad_pid to kill_pid().
At the time this issue was reported, an unprivileged user could reach the sysctl through user and PID namespaces because cad_pid was registered in pid_table[]. Moving cad_pid back to the global reboot sysctl table corrected that namespace and permission mismatch, but did not fix the underlying lifetime race.
Fix this by treating cad_pid as an RCU-protected pointer at both read sites and by waiting for a grace period before dropping the old reference on the write side.
call_rcu(&old_pid->rcu, ...) cannot be used here because free_pid() also queues pid->rcu; queueing the same rcu_head twice can corrupt the RCU callback list.
Original KASAN crash stack:
kernel/pid.c:545 pid_nr_ns() # reads freed pid->level kernel/pid.c:556 pid_vnr() # calls pid_nr_ns() kernel/pid.c:775 proc_do_cad_pid() # calls pid_vnr(cad_pid)
--- include/linux/sched.h | 2 +- include/linux/sched/signal.h | 5 +---- init/main.c | 2 +- kernel/reboot.c | 19 +++++++++++++++---- kernel/signal.c | 12 ++++++++++++ 5 files changed, 30 insertions(+), 10 deletions(-)
include/linux/sched.h +1 -1
@@ -1683,7 +1683,7 @@ static inline void kick_process(struct t }#endif -extern struct pid *cad_pid; +extern struct pid __rcu *cad_pid;/* * Per process flags
include/linux/sched/signal.h +1 -4
@@ -558,10 +558,7 @@ static inline sigset_t *sigmask_to_save(return res; } -static inline int kill_cad_pid (int sig,int priv) -{ -return kill_pid (cad_pid, sig, priv); -} +int kill_cad_pid (int sig,int priv);/* These can be the second arg to send_sig_info/send_group_sig_info. */ #define SEND_SIG_NOINFO ((struct kernel_siginfo *) 0)
init/main.c +1 -1
@@ -1523,7 +1523,7 @@ static noinline void __init kernel_init_*/ set_mems_allowed (node_states[N_MEMORY ]); - cad_pid =get_pid (task_pid (current)); +rcu_assign_pointer (cad_pid,get_pid (task_pid (current)));smp_prepare_cpus (setup_max_cpus);
kernel/reboot.c +15 -4
@@ -13,7 +13,9 @@#include <linux/kexec.h> #include <linux/kmod.h> #include <linux/kmsg_dump.h> +#include <linux/rcupdate.h> #include <linux/reboot.h> +#include <linux/sched/signal.h> #include <linux/suspend.h> #include <linux/syscalls.h> #include <linux/syscore_ops.h>
@@ -24,8 +26,7 @@*/ static int C_A_D =1 ; -struct pid *cad_pid; -EXPORT_SYMBOL (cad_pid); +struct pid __rcu *cad_pid;#if defined(CONFIG_ARM )#define DEFAULT_REBOOT_MODE = REBOOT_HARD
@@ -1288,10 +1289,14 @@ static int proc_do_cad_pid(const struct {struct ctl_table tmp_table = *table;struct pid *new_pid; +struct pid *old_pid;pid_t tmp_pid;int r; - tmp_pid =pid_vnr (cad_pid); +rcu_read_lock (); + tmp_pid =pid_vnr (rcu_dereference (cad_pid)); +rcu_read_unlock (); + tmp_table.data = &tmp_pid; r =proc_dointvec (&tmp_table, write, buffer, lenp, ppos);
@@ -1302,7 +1307,13 @@ static int proc_do_cad_pid(const structif (!new_pid)return -ESRCH ; -put_pid (xchg (&cad_pid, new_pid)); + old_pid =unrcu_pointer (xchg (&cad_pid,RCU_INITIALIZER (new_pid))); +/* +* Wait for cad_pid readers before put_pid(). We cannot use +* call_rcu() here because free_pid() already owns pid->rcu. +*/ +synchronize_rcu (); +put_pid (old_pid);return 0 ; }
kernel/signal.c +12 -0
@@ -1936,6 +1936,18 @@ int kill_pid(struct pid *pid, int sig, i }EXPORT_SYMBOL (kill_pid); +int kill_cad_pid (int sig,int priv) +{ +int ret; + +rcu_read_lock (); + ret =kill_pid (rcu_dereference (cad_pid), sig, priv); +rcu_read_unlock (); + +return ret; +} +EXPORT_SYMBOL (kill_cad_pid); +#ifdef CONFIG_POSIX_TIMERS /* * These functions handle POSIX timer signals. POSIX timers use
Greg Kroah-Hartman
maintainerPATCH 715/877 configfs: unhash the dentry before dropping the item in rmdir
In reply to Greg Kroah-Hartman6.12-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vasileios Almpanis <[email protected]>
[ Upstream commit f06c2d26d1999d37e93299db0ecead04ca7d0b9f ]
configfs_get_config_item() treats a hashed dentry as proof that sd->s_element is a live config_item. configfs_rmdir() breaks that:simple_rmdir() leaves the dentry hashed, the last reference to the item is dropped right after, and the dentry is only unhashed by d_delete() once ->rmdir() has returned. configfs_symlink() resolves its target holding no lock on it, so get_target() can land in that window:
BUG: KASAN: slab-use-after-free in config_item_get+0x26/0x90 get_target fs/configfs/symlink.c:128 [inline] configfs_symlink+0x4ab/0x1030 fs/configfs/symlink.c:185
Unhash in configfs_remove_dir(), while the item is still guaranteed to be there. A reference obtained just before that stays harmless, as create_link() rechecks CONFIGFS_USET_DROPPING, already set by configfs_detach_prep(). Both configfs_unregister_subsystem() paths d_drop() after detaching, so this only makes rmdir match them.
--- fs/configfs/dir.c | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-)
fs/configfs/dir.c +11 -2
@@ -395,8 +395,17 @@ static void remove_dir(struct dentry * dconfigfs_remove_dirent (d); -if (d_really_is_positive (d)) -simple_rmdir (d_inode (parent),d); +if (d_really_is_positive (d)) { +if (!simple_rmdir (d_inode (parent), d)) +/* +* configfs_get_config_item() takes a hashed dentry as +* proof that ->s_element is still alive. Our caller +* is about to drop the last reference to the item and +* the VFS will not unhash until after we return, so +* unhash it here. +*/ +d_drop (d); + }pr_debug (" o %pd removing done (%d)\n" , d,d_count (d));