Skip to contentSkip to conversation

Make the kernel preemptible

RFC PATCH NAK Ankur Arora 26 participants 250 messages Nov 7, 2023 – Dec 8, 2023 Page 3 of 3

Subsystems (254)
lore
Share & tools
lore
#202 lore raw

RFC PATCH 82/86 treewide: mtd: remove cond_resched()

In reply to Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

    cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

Most of the uses here are in set-1 (some right after we give up a lock or enable bottom-halves, causing an explicit preemption check.)

There are a few cases from set-3. Replace them with cond_resched_stall(). Some of those places, however, have wait-times milliseconds, so maybe we should just have an msleep() there?

[1] https://lore.kernel.org/lkml/[email protected]/

Cc Miquel Raynal <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Vignesh Raghavendra <[email protected]>
Cc Kyungmin Park <[email protected]>
Cc Tudor Ambarus <[email protected]>
Cc Pratyush Yadav <[email protected]>
---
 drivers/mtd/chips/cfi_cmdset_0001.c        |  6 ------
 drivers/mtd/chips/cfi_cmdset_0002.c        |  1 -
 drivers/mtd/chips/cfi_util.c               |  2 +-
 drivers/mtd/devices/spear_smi.c            |  2 +-
 drivers/mtd/devices/sst25l.c               |  3 +--
 drivers/mtd/devices/st_spi_fsm.c           |  4 ----
 drivers/mtd/inftlcore.c                    |  5 -----
 drivers/mtd/lpddr/lpddr_cmds.c             |  6 +-----
 drivers/mtd/mtd_blkdevs.c                  |  1 -
 drivers/mtd/nand/onenand/onenand_base.c    | 18 +-----------------
 drivers/mtd/nand/onenand/onenand_samsung.c |  8 +++++++-
 drivers/mtd/nand/raw/diskonchip.c          |  4 ++--
 drivers/mtd/nand/raw/fsmc_nand.c           |  3 +--
 drivers/mtd/nand/raw/hisi504_nand.c        |  2 +-
 drivers/mtd/nand/raw/nand_base.c           |  3 +--
 drivers/mtd/nand/raw/nand_legacy.c         | 17 +++++++++++++++--
 drivers/mtd/spi-nor/core.c                 |  8 +++++++-
 drivers/mtd/tests/mtd_test.c               |  2 --
 drivers/mtd/tests/mtd_test.h               |  2 +-
 drivers/mtd/tests/pagetest.c               |  1 -
 drivers/mtd/tests/readtest.c               |  2 --
 drivers/mtd/tests/torturetest.c            |  1 -
 drivers/mtd/ubi/attach.c                   | 10 ----------
 drivers/mtd/ubi/build.c                    |  2 --
 drivers/mtd/ubi/cdev.c                     |  4 ----
 drivers/mtd/ubi/eba.c                      |  8 --------
 drivers/mtd/ubi/misc.c                     |  2 --
 drivers/mtd/ubi/vtbl.c                     |  6 ------
 drivers/mtd/ubi/wl.c                       | 13 -------------
 29 files changed, 40 insertions(+), 106 deletions(-)
drivers/mtd/chips/cfi_cmdset_0001.c +0 -6
index 11b06fefaa0e..c6abed74e4df 100644
@@ -1208,7 +1208,6 @@ static int __xipram xip_wait_for_operation(
 			local_irq_enable();
 			mutex_unlock(&chip->mutex);
 			xip_iprefetch();
-			cond_resched();
 
 			/*
 			 * We're back.  However someone else might have
@@ -1337,7 +1336,6 @@ static int inval_cache_and_wait_for_operation(
 			sleep_time = 1000000/HZ;
 		} else {
 			udelay(1);
-			cond_resched();
 			timeo--;
 		}
 		mutex_lock(&chip->mutex);
@@ -1913,10 +1911,6 @@ static int cfi_intelext_writev (struct mtd_info *mtd, const struct kvec *vecs,
 				return 0;
 		}
 
-		/* Be nice and reschedule with the chip in a usable state for other
-		   processes. */
-		cond_resched();
-
 	} while (len);
 
 	return 0;
drivers/mtd/chips/cfi_cmdset_0002.c +0 -1
index df589d9b4d70..f6d8f8ccbe3f 100644
@@ -1105,7 +1105,6 @@ static void __xipram xip_udelay(struct map_info *map, struct flchip *chip,
 			local_irq_enable();
 			mutex_unlock(&chip->mutex);
 			xip_iprefetch();
-			cond_resched();
 
 			/*
 			 * We're back.  However someone else might have
drivers/mtd/chips/cfi_util.c +1 -1
index 140c69a67e82..c178dae31a59 100644
@@ -28,7 +28,7 @@ void cfi_udelay(int us)
 		msleep(DIV_ROUND_UP(us, 1000));
 	} else {
 		udelay(us);
-		cond_resched();
+		cond_resched_stall();
 	}
 }
 EXPORT_SYMBOL(cfi_udelay);
drivers/mtd/devices/spear_smi.c +1 -1
index 0a35e5236ae5..9b4d226633a9 100644
@@ -278,7 +278,7 @@ static int spear_smi_wait_till_ready(struct spear_smi *dev, u32 bank,
 			return 0;
 		}
 
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after_eq(jiffies, finish));
 
 	dev_err(&dev->pdev->dev, "smi controller is busy, timeout\n");
drivers/mtd/devices/sst25l.c +1 -2
index 8813994ce9f4..ff16147d9bdd 100644
@@ -132,8 +132,7 @@ static int sst25l_wait_till_ready(struct sst25l_flash *flash)
 			return err;
 		if (!(status & SST25L_STATUS_BUSY))
 			return 0;
-
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after_eq(jiffies, deadline));
 
 	return -ETIMEDOUT;
drivers/mtd/devices/st_spi_fsm.c +0 -4
index 95530cbbb1e0..a0f5874c1941 100644
@@ -738,8 +738,6 @@ static void stfsm_wait_seq(struct stfsm *fsm)
 
 		if (stfsm_is_idle(fsm))
 			return;
-
-		cond_resched();
 	}
 
 	dev_err(fsm->dev, "timeout on sequence completion\n");
@@ -901,8 +899,6 @@ static uint8_t stfsm_wait_busy(struct stfsm *fsm)
 		if (!timeout)
 			/* Restart */
 			writel(seq->seq_cfg, fsm->base + SPI_FAST_SEQ_CFG);
-
-		cond_resched();
 	}
 
 	dev_err(fsm->dev, "timeout on wait_busy\n");
drivers/mtd/inftlcore.c +0 -5
index 9739387cff8c..c757b8a25748 100644
@@ -732,11 +732,6 @@ static void INFTL_trydeletechain(struct INFTLrecord *inftl, unsigned thisVUC)
 
 		/* Now sort out whatever was pointing to it... */
 		*prevEUN = BLOCK_NIL;
-
-		/* Ideally we'd actually be responsive to new
-		   requests while we're doing this -- if there's
-		   free space why should others be made to wait? */
-		cond_resched();
 	}
 
 	inftl->VUtable[thisVUC] = BLOCK_NIL;
drivers/mtd/lpddr/lpddr_cmds.c +1 -5
index 3c3939bc2dad..ad8992d24082 100644
@@ -161,7 +161,7 @@ static int wait_for_ready(struct map_info *map, struct flchip *chip,
 			sleep_time = 1000000/HZ;
 		} else {
 			udelay(1);
-			cond_resched();
+			cond_resched_stall();
 			timeo--;
 		}
 		mutex_lock(&chip->mutex);
@@ -677,10 +677,6 @@ static int lpddr_writev(struct mtd_info *mtd, const struct kvec *vecs,
 		(*retlen) += size;
 		len -= size;
 
-		/* Be nice and reschedule with the chip in a usable
-		 * state for other processes */
-		cond_resched();
-
 	} while (len);
 
 	return 0;
drivers/mtd/mtd_blkdevs.c +0 -1
index ff18636e0889..96bff5627a31 100644
@@ -158,7 +158,6 @@ static void mtd_blktrans_work(struct mtd_blktrans_dev *dev)
 		}
 
 		background_done = 0;
-		cond_resched();
 		spin_lock_irq(&dev->queue_lock);
 	}
 }
drivers/mtd/nand/onenand/onenand_base.c +1 -17
index f66385faf631..97d07e4cc150 100644
@@ -567,7 +567,7 @@ static int onenand_wait(struct mtd_info *mtd, int state)
 			break;
 
 		if (state != FL_READING && state != FL_PREPARING_ERASE)
-			cond_resched();
+			cond_resched_stall();
 	}
 	/* To get correct interrupt status in timeout case */
 	interrupt = this->read_word(this->base + ONENAND_REG_INTERRUPT);
@@ -1143,8 +1143,6 @@ static int onenand_mlc_read_ops_nolock(struct mtd_info *mtd, loff_t from,
 	stats = mtd->ecc_stats;
 
 	while (read < len) {
-		cond_resched();
-
 		thislen = min_t(int, writesize, len - read);
 
 		column = from & (writesize - 1);
@@ -1307,7 +1305,6 @@ static int onenand_read_ops_nolock(struct mtd_info *mtd, loff_t from,
 		buf += thislen;
 		thislen = min_t(int, writesize, len - read);
 		column = 0;
-		cond_resched();
 		/* Now wait for load */
 		ret = this->wait(mtd, FL_READING);
 		onenand_update_bufferram(mtd, from, !ret);
@@ -1378,8 +1375,6 @@ static int onenand_read_oob_nolock(struct mtd_info *mtd, loff_t from,
 	readcmd = ONENAND_IS_4KB_PAGE(this) ? ONENAND_CMD_READ : ONENAND_CMD_READOOB;
 
 	while (read < len) {
-		cond_resched();
-
 		thislen = oobsize - column;
 		thislen = min_t(int, thislen, len);
 
@@ -1565,8 +1560,6 @@ int onenand_bbt_read_oob(struct mtd_info *mtd, loff_t from,
 	readcmd = ONENAND_IS_4KB_PAGE(this) ? ONENAND_CMD_READ : ONENAND_CMD_READOOB;
 
 	while (read < len) {
-		cond_resched();
-
 		thislen = mtd->oobsize - column;
 		thislen = min_t(int, thislen, len);
 
@@ -1838,8 +1831,6 @@ static int onenand_write_ops_nolock(struct mtd_info *mtd, loff_t to,
 			thislen = min_t(int, mtd->writesize - column, len - written);
 			thisooblen = min_t(int, oobsize - oobcolumn, ooblen - oobwritten);
 
-			cond_resched();
-
 			this->command(mtd, ONENAND_CMD_BUFFERRAM, to, thislen);
 
 			/* Partial page write */
@@ -2022,8 +2013,6 @@ static int onenand_write_oob_nolock(struct mtd_info *mtd, loff_t to,
 	while (written < len) {
 		int thislen = min_t(int, oobsize, len - written);
 
-		cond_resched();
-
 		this->command(mtd, ONENAND_CMD_BUFFERRAM, to, mtd->oobsize);
 
 		/* We send data to spare ram with oobsize
@@ -2232,7 +2221,6 @@ static int onenand_multiblock_erase(struct mtd_info *mtd,
 		}
 
 		/* last block of 64-eb series */
-		cond_resched();
 		this->command(mtd, ONENAND_CMD_ERASE, addr, block_size);
 		onenand_invalidate_bufferram(mtd, addr, block_size);
 
@@ -2288,8 +2276,6 @@ static int onenand_block_by_block_erase(struct mtd_info *mtd,
 
 	/* Loop through the blocks */
 	while (len) {
-		cond_resched();
-
 		/* Check if we have a bad block, we do not erase bad blocks */
 		if (onenand_block_isbad_nolock(mtd, addr, 0)) {
 			printk(KERN_WARNING "%s: attempt to erase a bad block "
@@ -2799,8 +2785,6 @@ static int onenand_otp_write_oob_nolock(struct mtd_info *mtd, loff_t to,
 	while (written < len) {
 		int thislen = min_t(int, oobsize, len - written);
 
-		cond_resched();
-
 		block = (int) (to >> this->erase_shift);
 		/*
 		 * Write 'DFS, FBA' of Flash
drivers/mtd/nand/onenand/onenand_samsung.c +7 -1
index fd6890a03d55..2e0c8f50d77d 100644
@@ -338,8 +338,14 @@ static int s3c_onenand_wait(struct mtd_info *mtd, int state)
 		if (stat & flags)
 			break;
 
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?
+		 */
 		if (state != FL_READING)
-			cond_resched();
+			cond_resched_stall();
 	}
 	/* To get correct interrupt status in timeout case */
 	stat = s3c_read_reg(INT_ERR_STAT_OFFSET);
drivers/mtd/nand/raw/diskonchip.c +2 -2
index 5d2ddb037a9a..930b4fdf75e0 100644
@@ -248,7 +248,7 @@ static int _DoC_WaitReady(struct doc_priv *doc)
 				return -EIO;
 			}
 			udelay(1);
-			cond_resched();
+			cond_resched_stall();
 		}
 	} else {
 		while (!(ReadDOC(docptr, CDSNControl) & CDSN_CTRL_FR_B)) {
@@ -257,7 +257,7 @@ static int _DoC_WaitReady(struct doc_priv *doc)
 				return -EIO;
 			}
 			udelay(1);
-			cond_resched();
+			cond_resched_stall();
 		}
 	}
 
drivers/mtd/nand/raw/fsmc_nand.c +1 -2
index 811982da3557..20e88e98e517 100644
@@ -398,8 +398,7 @@ static int fsmc_read_hwecc_ecc4(struct nand_chip *chip, const u8 *data,
 	do {
 		if (readl_relaxed(host->regs_va + STS) & FSMC_CODE_RDY)
 			break;
-
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after_eq(jiffies, deadline));
 
 	if (time_after_eq(jiffies, deadline)) {
drivers/mtd/nand/raw/hisi504_nand.c +1 -1
index fe291a2e5c77..bf669b1750f8 100644
@@ -819,7 +819,7 @@ static int hisi_nfc_suspend(struct device *dev)
 		if (((hinfc_read(host, HINFC504_STATUS) & 0x1) == 0x0) &&
 		    (hinfc_read(host, HINFC504_DMA_CTRL) &
 		     HINFC504_DMA_CTRL_DMA_START)) {
-			cond_resched();
+			cond_resched_stall();
 			return 0;
 		}
 	}
drivers/mtd/nand/raw/nand_base.c +1 -2
index 1fcac403cee6..656126b05f09 100644
@@ -730,8 +730,7 @@ int nand_gpio_waitrdy(struct nand_chip *chip, struct gpio_desc *gpiod,
 	do {
 		if (gpiod_get_value_cansleep(gpiod))
 			return 0;
-
-		cond_resched();
+		cond_resched_stall();
 	} while	(time_before(jiffies, timeout_ms));
 
 	return gpiod_get_value_cansleep(gpiod) ? 0 : -ETIMEDOUT;
drivers/mtd/nand/raw/nand_legacy.c +15 -2
index 743792edf98d..aaef537b46c3 100644
@@ -203,7 +203,13 @@ void nand_wait_ready(struct nand_chip *chip)
 	do {
 		if (chip->legacy.dev_ready(chip))
 			return;
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?
+		 */
+		cond_resched_stall();
 	} while (time_before(jiffies, timeo));
 
 	if (!chip->legacy.dev_ready(chip))
@@ -565,7 +571,14 @@ static int nand_wait(struct nand_chip *chip)
 				if (status & NAND_STATUS_READY)
 					break;
 			}
-			cond_resched();
+
+			/*
+			 * Use a cond_resched_stall() to avoid spinning in
+			 * a tight loop.
+			 * Though, given that the timeout is in milliseconds,
+			 * maybe this should timeout or event wait?
+			 */
+			cond_resched_stall();
 		} while (time_before(jiffies, timeo));
 	}
 
drivers/mtd/spi-nor/core.c +7 -1
index 1b0c6770c14e..e32e6eebb0e2 100644
@@ -730,7 +730,13 @@ static int spi_nor_wait_till_ready_with_timeout(struct spi_nor *nor,
 		if (ret)
 			return 0;
 
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?
+		 */
+		cond_resched_stall();
 	}
 
 	dev_dbg(nor->dev, "flash operation timed out\n");
drivers/mtd/tests/mtd_test.c +0 -2
index c84250beffdc..5bb0c6ef7df9 100644
@@ -51,7 +51,6 @@ int mtdtest_scan_for_bad_eraseblocks(struct mtd_info *mtd, unsigned char *bbt,
 		bbt[i] = is_block_bad(mtd, eb + i) ? 1 : 0;
 		if (bbt[i])
 			bad += 1;
-		cond_resched();
 	}
 	pr_info("scanned %d eraseblocks, %d are bad\n", i, bad);
 
@@ -70,7 +69,6 @@ int mtdtest_erase_good_eraseblocks(struct mtd_info *mtd, unsigned char *bbt,
 		err = mtdtest_erase_eraseblock(mtd, eb + i);
 		if (err)
 			return err;
-		cond_resched();
 	}
 
 	return 0;
drivers/mtd/tests/mtd_test.h +1 -1
index 5a6e3bbe0474..4742f53c6f25 100644
@@ -4,7 +4,7 @@
 
 static inline int mtdtest_relax(void)
 {
-	cond_resched();
+	cond_resched_stall();
 	if (signal_pending(current)) {
 		pr_info("aborting test due to pending signal!\n");
 		return -EINTR;
drivers/mtd/tests/pagetest.c +0 -1
index 8eb40b6e6dfa..79330c0ccd85 100644
@@ -43,7 +43,6 @@ static int write_eraseblock(int ebnum)
 	loff_t addr = (loff_t)ebnum * mtd->erasesize;
 
 	prandom_bytes_state(&rnd_state, writebuf, mtd->erasesize);
-	cond_resched();
 	return mtdtest_write(mtd, addr, mtd->erasesize, writebuf);
 }
 
drivers/mtd/tests/readtest.c +0 -2
index 99670ef91f2b..c862d9a6dc1d 100644
@@ -91,7 +91,6 @@ static void dump_eraseblock(int ebnum)
 		for (j = 0; j < 32 && i < n; j++, i++)
 			p += sprintf(p, "%02x", (unsigned int)iobuf[i]);
 		printk(KERN_CRIT "%s\n", line);
-		cond_resched();
 	}
 	if (!mtd->oobsize)
 		return;
@@ -106,7 +105,6 @@ static void dump_eraseblock(int ebnum)
 				p += sprintf(p, "%02x",
 					     (unsigned int)iobuf1[i]);
 			printk(KERN_CRIT "%s\n", line);
-			cond_resched();
 		}
 }
 
drivers/mtd/tests/torturetest.c +0 -1
index 841689b4d86d..94cf4f6c6c4c 100644
@@ -390,7 +390,6 @@ static void report_corrupt(unsigned char *read, unsigned char *written)
 	       " what was read from flash and what was expected\n");
 
 	for (i = 0; i < check_len; i += pgsize) {
-		cond_resched();
 		bytes = bits = 0;
 		first = countdiffs(written, read, i, pgsize, &bytes,
 				   &bits);
drivers/mtd/ubi/attach.c +0 -10
index ae5abe492b52..0994d2d8edf0 100644
@@ -1390,8 +1390,6 @@ static int scan_all(struct ubi_device *ubi, struct ubi_attach_info *ai,
 		goto out_ech;
 
 	for (pnum = start; pnum < ubi->peb_count; pnum++) {
-		cond_resched();
-
 		dbg_gen("process PEB %d", pnum);
 		err = scan_peb(ubi, ai, pnum, false);
 		if (err < 0)
@@ -1504,8 +1502,6 @@ static int scan_fast(struct ubi_device *ubi, struct ubi_attach_info **ai)
 		goto out_ech;
 
 	for (pnum = 0; pnum < UBI_FM_MAX_START; pnum++) {
-		cond_resched();
-
 		dbg_gen("process PEB %d", pnum);
 		err = scan_peb(ubi, scan_ai, pnum, true);
 		if (err < 0)
@@ -1674,8 +1670,6 @@ static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai)
 	ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
 		int leb_count = 0;
 
-		cond_resched();
-
 		vols_found += 1;
 
 		if (ai->is_empty) {
@@ -1715,8 +1709,6 @@ static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai)
 
 		last_aeb = NULL;
 		ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
-			cond_resched();
-
 			last_aeb = aeb;
 			leb_count += 1;
 
@@ -1790,8 +1782,6 @@ static int self_check_ai(struct ubi_device *ubi, struct ubi_attach_info *ai)
 		ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
 			int vol_type;
 
-			cond_resched();
-
 			last_aeb = aeb;
 
 			err = ubi_io_read_vid_hdr(ubi, aeb->pnum, vidb, 1);
drivers/mtd/ubi/build.c +0 -2
index 8ee51e49fced..52740f461259 100644
@@ -1257,8 +1257,6 @@ static int __init ubi_init(void)
 		struct mtd_dev_param *p = &mtd_dev_param[i];
 		struct mtd_info *mtd;
 
-		cond_resched();
-
 		mtd = open_mtd_device(p->name);
 		if (IS_ERR(mtd)) {
 			err = PTR_ERR(mtd);
drivers/mtd/ubi/cdev.c +0 -4
index f43430b9c1e6..e60c0ad0eeb4 100644
@@ -209,8 +209,6 @@ static ssize_t vol_cdev_read(struct file *file, __user char *buf, size_t count,
 	lnum = div_u64_rem(*offp, vol->usable_leb_size, &off);
 
 	do {
-		cond_resched();
-
 		if (off + len >= vol->usable_leb_size)
 			len = vol->usable_leb_size - off;
 
@@ -289,8 +287,6 @@ static ssize_t vol_cdev_direct_write(struct file *file, const char __user *buf,
 	len = count > tbuf_size ? tbuf_size : count;
 
 	while (count) {
-		cond_resched();
-
 		if (off + len >= vol->usable_leb_size)
 			len = vol->usable_leb_size - off;
 
drivers/mtd/ubi/eba.c +0 -8
index 655ff41863e2..f1e097503826 100644
@@ -1408,9 +1408,7 @@ int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
 		aldata_size = data_size =
 			ubi_calc_data_len(ubi, ubi->peb_buf, data_size);
 
-	cond_resched();
 	crc = crc32(UBI_CRC32_INIT, ubi->peb_buf, data_size);
-	cond_resched();
 
 	/*
 	 * It may turn out to be that the whole @from physical eraseblock
@@ -1432,8 +1430,6 @@ int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
 		goto out_unlock_buf;
 	}
 
-	cond_resched();
-
 	/* Read the VID header back and check if it was written correctly */
 	err = ubi_io_read_vid_hdr(ubi, to, vidb, 1);
 	if (err) {
@@ -1454,8 +1450,6 @@ int ubi_eba_copy_leb(struct ubi_device *ubi, int from, int to,
 				err = MOVE_TARGET_WR_ERR;
 			goto out_unlock_buf;
 		}
-
-		cond_resched();
 	}
 
 	ubi_assert(vol->eba_tbl->entries[lnum].pnum == from);
@@ -1640,8 +1634,6 @@ int ubi_eba_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
 		if (!vol)
 			continue;
 
-		cond_resched();
-
 		tbl = ubi_eba_create_table(vol, vol->reserved_pebs);
 		if (IS_ERR(tbl)) {
 			err = PTR_ERR(tbl);
drivers/mtd/ubi/misc.c +0 -2
index 1794d66b6eb7..8751337a8101 100644
@@ -61,8 +61,6 @@ int ubi_check_volume(struct ubi_device *ubi, int vol_id)
 	for (i = 0; i < vol->used_ebs; i++) {
 		int size;
 
-		cond_resched();
-
 		if (i == vol->used_ebs - 1)
 			size = vol->last_eb_bytes;
 		else
drivers/mtd/ubi/vtbl.c +0 -6
index f700f0e4f2ec..6e0d8b3109d5 100644
@@ -163,8 +163,6 @@ static int vtbl_check(const struct ubi_device *ubi,
 	const char *name;
 
 	for (i = 0; i < ubi->vtbl_slots; i++) {
-		cond_resched();
-
 		reserved_pebs = be32_to_cpu(vtbl[i].reserved_pebs);
 		alignment = be32_to_cpu(vtbl[i].alignment);
 		data_pad = be32_to_cpu(vtbl[i].data_pad);
@@ -526,8 +524,6 @@ static int init_volumes(struct ubi_device *ubi,
 	struct ubi_volume *vol;
 
 	for (i = 0; i < ubi->vtbl_slots; i++) {
-		cond_resched();
-
 		if (be32_to_cpu(vtbl[i].reserved_pebs) == 0)
 			continue; /* Empty record */
 
@@ -736,8 +732,6 @@ static int check_attaching_info(const struct ubi_device *ubi,
 	}
 
 	for (i = 0; i < ubi->vtbl_slots + UBI_INT_VOL_COUNT; i++) {
-		cond_resched();
-
 		av = ubi_find_av(ai, i);
 		vol = ubi->volumes[i];
 		if (!vol) {
drivers/mtd/ubi/wl.c +0 -13
index 26a214f016c1..5ff22ac93ba9 100644
@@ -190,8 +190,6 @@ static int do_work(struct ubi_device *ubi)
 	int err;
 	struct ubi_work *wrk;
 
-	cond_resched();
-
 	/*
 	 * @ubi->work_sem is used to synchronize with the workers. Workers take
 	 * it in read mode, so many of them may be doing works at a time. But
@@ -519,7 +517,6 @@ static void serve_prot_queue(struct ubi_device *ubi)
 			 * too long.
 			 */
 			spin_unlock(&ubi->wl_lock);
-			cond_resched();
 			goto repeat;
 		}
 	}
@@ -1703,8 +1700,6 @@ int ubi_thread(void *u)
 			}
 		} else
 			failures = 0;
-
-		cond_resched();
 	}
 
 	dbg_wl("background thread \"%s\" is killed", ubi->bgt_name);
@@ -1805,8 +1800,6 @@ int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
 
 	ubi->free_count = 0;
 	list_for_each_entry_safe(aeb, tmp, &ai->erase, u.list) {
-		cond_resched();
-
 		err = erase_aeb(ubi, aeb, false);
 		if (err)
 			goto out_free;
@@ -1815,8 +1808,6 @@ int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
 	}
 
 	list_for_each_entry(aeb, &ai->free, u.list) {
-		cond_resched();
-
 		e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
 		if (!e) {
 			err = -ENOMEM;
@@ -1837,8 +1828,6 @@ int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
 
 	ubi_rb_for_each_entry(rb1, av, &ai->volumes, rb) {
 		ubi_rb_for_each_entry(rb2, aeb, &av->root, u.rb) {
-			cond_resched();
-
 			e = kmem_cache_alloc(ubi_wl_entry_slab, GFP_KERNEL);
 			if (!e) {
 				err = -ENOMEM;
@@ -1864,8 +1853,6 @@ int ubi_wl_init(struct ubi_device *ubi, struct ubi_attach_info *ai)
 	}
 
 	list_for_each_entry(aeb, &ai->fastmap, u.list) {
-		cond_resched();
-
 		e = ubi_find_fm_block(ubi, aeb->pnum);
 
 		if (e) {
Signature · 1 line
2.31.1
maintainer
#203 lore raw

Re: [RFC PATCH 82/86] treewide: mtd: remove cond_resched()

Hi Ankur,

[email protected] wrote on Tue, 7 Nov 2023 15:08:18 -0800:

Quoted 33 lines

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

    cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

Quoted 6 lines

Most of the uses here are in set-1 (some right after we give up a lock or enable bottom-halves, causing an explicit preemption check.)

There are a few cases from set-3. Replace them with cond_resched_stall(). Some of those places, however, have wait-times milliseconds, so maybe we should just have an msleep() there?

Yeah, I believe this should work.

Quoted 11 lines

[1] https://lore.kernel.org/lkml/[email protected]/

Cc Miquel Raynal <[email protected]>
Cc Richard Weinberger <[email protected]>
Cc Vignesh Raghavendra <[email protected]>
Cc Kyungmin Park <[email protected]>
Cc Tudor Ambarus <[email protected]>
Cc Pratyush Yadav <[email protected]>

---

[...]

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 210

Quoted 12 lines
drivers/mtd/nand/raw/nand_legacy.c +5 -1
@@ -203,7 +203,13 @@ void nand_wait_ready(struct nand_chip *chip)
 	do {
 		if (chip->legacy.dev_ready(chip))
 			return;
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?

Event waiting is precisely what we do here, with the hardware access which are available in this case. So I believe this part of the comment (in general) is not relevant. Now regarding the timeout I believe it is closer to the second than the millisecond, so timeout-ing is not relevant either in most cases (talking about mtd/ in general).

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 213

Quoted 3 lines
drivers/mtd/nand/raw/nand_legacy.c +2 -0
+		 */
+		cond_resched_stall();
 	} while (time_before(jiffies, timeo));

Thanks,
Miquèl

maintainer
#204 lore raw

Re: [RFC PATCH 82/86] treewide: mtd: remove cond_resched()

Quoted 10 lines · Miquel Raynal
Quoted 10 lines
drivers/mtd/nand/raw/nand_legacy.c +3 -1
@@ -203,7 +203,13 @@ void nand_wait_ready(struct nand_chip *chip)
 	do {
 		if (chip->legacy.dev_ready(chip))
 			return;
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
Quoted 8 lines

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 210

Quoted 2 lines
drivers/mtd/nand/raw/nand_legacy.c +2 -0
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?

Event waiting is precisely what we do here, with the hardware access which are available in this case. So I believe this part of the comment (in general) is not relevant. Now regarding the timeout I believe it is closer to the second than the millisecond, so timeout-ing is not relevant either in most cases (talking about mtd/ in general).

I think you've misunderstood what Ankur wrote here. What you're currently doing is spinning in a very tight loop. The comment is suggesting you might want to msleep(1) or something to avoid burning CPU cycles. It'd be even better if the hardware could signal you somehow, but I bet it can't.

Quoted 7 lines

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 213

Quoted 3 lines
drivers/mtd/nand/raw/nand_legacy.c +2 -0
+		 */
+		cond_resched_stall();
 	} while (time_before(jiffies, timeo));

Thanks,
Miquèl

maintainer
#205 lore raw

Re: [RFC PATCH 82/86] treewide: mtd: remove cond_resched()

Quoted 20 lines · On Wed, 8 Nov 2023 16:32:36 +0000 Matthew Wilcox <[email protected]> wrote:
Quoted 10 lines · Miquel Raynal
Quoted 10 lines
drivers/mtd/nand/raw/nand_legacy.c +3 -1
@@ -203,7 +203,13 @@ void nand_wait_ready(struct nand_chip *chip)
 	do {
 		if (chip->legacy.dev_ready(chip))
 			return;
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
Quoted 8 lines

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 210

Quoted 2 lines
drivers/mtd/nand/raw/nand_legacy.c +2 -0
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?  

Event waiting is precisely what we do here, with the hardware access which are available in this case. So I believe this part of the comment (in general) is not relevant. Now regarding the timeout I believe it is closer to the second than the millisecond, so timeout-ing is not relevant either in most cases (talking about mtd/ in general).

Quoted 6 lines

I think you've misunderstood what Ankur wrote here. What you're currently doing is spinning in a very tight loop. The comment is suggesting you might want to msleep(1) or something to avoid burning CPU cycles. It'd be even better if the hardware could signal you somehow, but I bet it can't.

Oh how I wish we could bring back the old PREEMPT_RT cpu_chill()...

#define cpu_chill() msleep(1)

;-)

-- Steve

Quoted 7 lines
Quoted 7 lines

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 213

Quoted 3 lines
drivers/mtd/nand/raw/nand_legacy.c +2 -0
+		 */
+		cond_resched_stall();
 	} while (time_before(jiffies, timeo));  

Thanks,
Miquèl

maintainer
#206 lore raw

Re: [RFC PATCH 82/86] treewide: mtd: remove cond_resched()

Hello,

[email protected] wrote on Wed, 8 Nov 2023 12:21:16 -0500:

Quoted 23 lines
Quoted 20 lines · On Wed, 8 Nov 2023 16:32:36 +0000 Matthew Wilcox <[email protected]> wrote:
Quoted 18 lines · Miquel Raynal

drivers/mtd/nand/raw/nand_legacy.c void nand_wait_ready(struct nand_chip *chip) · line 210

Quoted 12 lines
drivers/mtd/nand/raw/nand_legacy.c +5 -1
@@ -203,7 +203,13 @@ void nand_wait_ready(struct nand_chip *chip)
 	do {
 		if (chip->legacy.dev_ready(chip))
 			return;
-		cond_resched();
+		/*
+		 * Use a cond_resched_stall() to avoid spinning in
+		 * a tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?    

Event waiting is precisely what we do here, with the hardware access which are available in this case. So I believe this part of the comment (in general) is not relevant. Now regarding the timeout I believe it is closer to the second than the millisecond, so timeout-ing is not relevant either in most cases (talking about mtd/ in general).

Quoted 5 lines
Quoted 5 lines

I think you've misunderstood what Ankur wrote here. What you're currently doing is spinning in a very tight loop. The comment is suggesting you might want to msleep(1) or something to avoid burning CPU cycles. It'd be even better if the hardware could signal you somehow, but I bet it can't.

Well, I think I'm aligned with the change and the first sentence in the comment, but not with the second sentence which I find not relevant.

Maybe I don't understand what "maybe this should timeout" and Ankur meant "sleeping" there, but for me a timeout is when you bail out with an error. If sleeping is advised, then why not using a more explicit wording? As for hardware events, in this case it is not relevant, as you noticed, so I asked this part of the sentence to be dropped.

This is a legacy part of the core but is still part of the core. In general I don't mind treewide changes to be slightly generic and I will not be bothered too much with the device drivers changes, but the core is more important to my eyes.

Quoted 3 lines

Oh how I wish we could bring back the old PREEMPT_RT cpu_chill()...

#define cpu_chill() msleep(1)

:')

Thanks,
Miquèl

#207 lore raw

RFC PATCH 83/86 treewide: drm: remove cond_resched()

In reply to Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

    cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

Most of the uses here are in set-1 (some right after we give up a lock or enable bottom-halves, causing an explicit preemption check.)

There are a few cases from set-3. Replace them with cond_resched_stall().

[1] https://lore.kernel.org/lkml/[email protected]/

Cc Inki Dae <[email protected]>
Cc Jagan Teki <[email protected]>
Cc Marek Szyprowski <[email protected]>
Cc Andrzej Hajda <[email protected]>
Cc Neil Armstrong <[email protected]>
Cc Robert Foss <[email protected]>
Cc David Airlie <[email protected]>
Cc Daniel Vetter <[email protected]>
Cc Maarten Lankhorst <[email protected]>
Cc Maxime Ripard <[email protected]>
Cc Thomas Zimmermann <[email protected]>
---
 drivers/gpu/drm/bridge/samsung-dsim.c         |  2 +-
 drivers/gpu/drm/drm_buddy.c                   |  1 -
 drivers/gpu/drm/drm_gem.c                     |  1 -
 .../gpu/drm/i915/gem/i915_gem_execbuffer.c    |  2 +-
 drivers/gpu/drm/i915/gem/i915_gem_object.c    |  1 -
 drivers/gpu/drm/i915/gem/i915_gem_shmem.c     |  2 --
 .../gpu/drm/i915/gem/selftests/huge_pages.c   |  6 ----
 .../drm/i915/gem/selftests/i915_gem_mman.c    |  5 ----
 drivers/gpu/drm/i915/gt/intel_breadcrumbs.c   |  2 +-
 drivers/gpu/drm/i915/gt/intel_gt.c            |  2 +-
 drivers/gpu/drm/i915/gt/intel_migrate.c       |  4 ---
 drivers/gpu/drm/i915/gt/selftest_execlists.c  |  4 ---
 drivers/gpu/drm/i915/gt/selftest_hangcheck.c  |  2 --
 drivers/gpu/drm/i915/gt/selftest_lrc.c        |  2 --
 drivers/gpu/drm/i915/gt/selftest_migrate.c    |  2 --
 drivers/gpu/drm/i915/gt/selftest_timeline.c   |  4 ---
 drivers/gpu/drm/i915/i915_active.c            |  2 +-
 drivers/gpu/drm/i915/i915_gem_evict.c         |  2 --
 drivers/gpu/drm/i915/i915_gpu_error.c         | 18 ++++--------
 drivers/gpu/drm/i915/intel_uncore.c           |  1 -
 drivers/gpu/drm/i915/selftests/i915_gem_gtt.c |  2 --
 drivers/gpu/drm/i915/selftests/i915_request.c |  2 --
 .../gpu/drm/i915/selftests/i915_selftest.c    |  3 --
 drivers/gpu/drm/i915/selftests/i915_vma.c     |  9 ------
 .../gpu/drm/i915/selftests/igt_flush_test.c   |  2 --
 .../drm/i915/selftests/intel_memory_region.c  |  4 ---
 drivers/gpu/drm/tests/drm_buddy_test.c        |  5 ----
 drivers/gpu/drm/tests/drm_mm_test.c           | 29 -------------------
 28 files changed, 11 insertions(+), 110 deletions(-)
drivers/gpu/drm/bridge/samsung-dsim.c +1 -1
index cf777bdb25d2..ae537b9bf8df 100644
@@ -1013,7 +1013,7 @@ static int samsung_dsim_wait_for_hdr_fifo(struct samsung_dsim *dsi)
 		if (reg & DSIM_SFR_HEADER_EMPTY)
 			return 0;
 
-		if (!cond_resched())
+		if (!cond_resched_stall())
 			usleep_range(950, 1050);
 	} while (--timeout);
 
drivers/gpu/drm/drm_buddy.c +0 -1
index e6f5ba5f4baf..fe401d18bf4d 100644
@@ -311,7 +311,6 @@ void drm_buddy_free_list(struct drm_buddy *mm, struct list_head *objects)
 
 	list_for_each_entry_safe(block, on, objects, link) {
 		drm_buddy_free_block(mm, block);
-		cond_resched();
 	}
 	INIT_LIST_HEAD(objects);
 }
drivers/gpu/drm/drm_gem.c +0 -1
index 44a948b80ee1..881caa4b48a9 100644
@@ -506,7 +506,6 @@ static void drm_gem_check_release_batch(struct folio_batch *fbatch)
 {
 	check_move_unevictable_folios(fbatch);
 	__folio_batch_release(fbatch);
-	cond_resched();
 }
 
 /**
drivers/gpu/drm/i915/gem/i915_gem_execbuffer.c +1 -1
index 5a687a3686bd..0b16689423b4 100644
@@ -1812,7 +1812,7 @@ static noinline int eb_relocate_parse_slow(struct i915_execbuffer *eb)
 		err = eb_copy_relocations(eb);
 		have_copy = err == 0;
 	} else {
-		cond_resched();
+		cond_resched_stall();
 		err = 0;
 	}
 
drivers/gpu/drm/i915/gem/i915_gem_object.c +0 -1
index ef9346ed6d0f..172eee1e8889 100644
@@ -414,7 +414,6 @@ static void __i915_gem_free_objects(struct drm_i915_private *i915,
 
 		/* But keep the pointer alive for RCU-protected lookups */
 		call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
-		cond_resched();
 	}
 }
 
drivers/gpu/drm/i915/gem/i915_gem_shmem.c +0 -2
index 73a4a4eb29e0..38ea2fc206e0 100644
@@ -26,7 +26,6 @@ static void check_release_folio_batch(struct folio_batch *fbatch)
 {
 	check_move_unevictable_folios(fbatch);
 	__folio_batch_release(fbatch);
-	cond_resched();
 }
 
 void shmem_sg_free_table(struct sg_table *st, struct address_space *mapping,
@@ -108,7 +107,6 @@ int shmem_sg_alloc_table(struct drm_i915_private *i915, struct sg_table *st,
 		gfp_t gfp = noreclaim;
 
 		do {
-			cond_resched();
 			folio = shmem_read_folio_gfp(mapping, i, gfp);
 			if (!IS_ERR(folio))
 				break;
drivers/gpu/drm/i915/gem/selftests/huge_pages.c +0 -6
index 6b9f6cf50bf6..fae0fa993404 100644
@@ -1447,8 +1447,6 @@ static int igt_ppgtt_smoke_huge(void *arg)
 
 		if (err)
 			break;
-
-		cond_resched();
 	}
 
 	return err;
@@ -1538,8 +1536,6 @@ static int igt_ppgtt_sanity_check(void *arg)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -1738,8 +1734,6 @@ static int igt_ppgtt_mixed(void *arg)
 			break;
 
 		addr += obj->base.size;
-
-		cond_resched();
 	}
 
 	i915_gem_context_unlock_engines(ctx);
drivers/gpu/drm/i915/gem/selftests/i915_gem_mman.c +0 -5
index 72957a36a36b..c994071532cf 100644
@@ -221,7 +221,6 @@ static int check_partial_mappings(struct drm_i915_gem_object *obj,
 		u32 *cpu;
 
 		GEM_BUG_ON(view.partial.size > nreal);
-		cond_resched();
 
 		vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
 		if (IS_ERR(vma)) {
@@ -1026,8 +1025,6 @@ static void igt_close_objects(struct drm_i915_private *i915,
 		i915_gem_object_put(obj);
 	}
 
-	cond_resched();
-
 	i915_gem_drain_freed_objects(i915);
 }
 
@@ -1041,8 +1038,6 @@ static void igt_make_evictable(struct list_head *objects)
 			i915_gem_object_unpin_pages(obj);
 		i915_gem_object_unlock(obj);
 	}
-
-	cond_resched();
 }
 
 static int igt_fill_mappable(struct intel_memory_region *mr,
drivers/gpu/drm/i915/gt/intel_breadcrumbs.c +1 -1
index ecc990ec1b95..e016f1203f7c 100644
@@ -315,7 +315,7 @@ void __intel_breadcrumbs_park(struct intel_breadcrumbs *b)
 		local_irq_disable();
 		signal_irq_work(&b->irq_work);
 		local_irq_enable();
-		cond_resched();
+		cond_resched_stall();
 	}
 }
 
drivers/gpu/drm/i915/gt/intel_gt.c +1 -1
index 449f0b7fc843..40cfdf4f5fff 100644
@@ -664,7 +664,7 @@ int intel_gt_wait_for_idle(struct intel_gt *gt, long timeout)
 
 	while ((timeout = intel_gt_retire_requests_timeout(gt, timeout,
 							   &remaining_timeout)) > 0) {
-		cond_resched();
+		cond_resched_stall();
 		if (signal_pending(current))
 			return -EINTR;
 	}
drivers/gpu/drm/i915/gt/intel_migrate.c +0 -4
index 576e5ef0289b..cc3f62d5c28f 100644
@@ -906,8 +906,6 @@ intel_context_migrate_copy(struct intel_context *ce,
 			err = -EINVAL;
 			break;
 		}
-
-		cond_resched();
 	} while (1);
 
 out_ce:
@@ -1067,8 +1065,6 @@ intel_context_migrate_clear(struct intel_context *ce,
 		i915_request_add(rq);
 		if (err || !it.sg || !sg_dma_len(it.sg))
 			break;
-
-		cond_resched();
 	} while (1);
 
 out_ce:
drivers/gpu/drm/i915/gt/selftest_execlists.c +0 -4
index 4202df5b8c12..52c8fa3e5cad 100644
@@ -60,8 +60,6 @@ static int wait_for_submit(struct intel_engine_cs *engine,
 
 		if (done)
 			return -ETIME;
-
-		cond_resched();
 	} while (1);
 }
 
@@ -72,7 +70,6 @@ static int wait_for_reset(struct intel_engine_cs *engine,
 	timeout += jiffies;
 
 	do {
-		cond_resched();
 		intel_engine_flush_submission(engine);
 
 		if (READ_ONCE(engine->execlists.pending[0]))
@@ -1373,7 +1370,6 @@ static int live_timeslice_queue(void *arg)
 
 		/* Wait until we ack the release_queue and start timeslicing */
 		do {
-			cond_resched();
 			intel_engine_flush_submission(engine);
 		} while (READ_ONCE(engine->execlists.pending[0]));
 
drivers/gpu/drm/i915/gt/selftest_hangcheck.c +0 -2
index 0dd4d00ee894..e751ed2cf8b2 100644
@@ -939,8 +939,6 @@ static void active_engine(struct kthread_work *work)
 			pr_err("[%s] Request put failed: %d!\n", engine->name, err);
 			break;
 		}
-
-		cond_resched();
 	}
 
 	for (count = 0; count < ARRAY_SIZE(rq); count++) {
drivers/gpu/drm/i915/gt/selftest_lrc.c +0 -2
index 5f826b6dcf5d..83a42492f0d0 100644
@@ -70,8 +70,6 @@ static int wait_for_submit(struct intel_engine_cs *engine,
 
 		if (done)
 			return -ETIME;
-
-		cond_resched();
 	} while (1);
 }
 
drivers/gpu/drm/i915/gt/selftest_migrate.c +0 -2
index 3def5ca72dec..9dfa70699df9 100644
@@ -210,8 +210,6 @@ static int intel_context_copy_ccs(struct intel_context *ce,
 		i915_request_add(rq);
 		if (err || !it.sg || !sg_dma_len(it.sg))
 			break;
-
-		cond_resched();
 	} while (1);
 
 out_ce:
drivers/gpu/drm/i915/gt/selftest_timeline.c +0 -4
index fa36cf920bde..15b8fd41ad90 100644
@@ -352,7 +352,6 @@ static int bench_sync(void *arg)
 		__func__, count, (long long)div64_ul(ktime_to_ns(kt), count));
 
 	mock_timeline_fini(&tl);
-	cond_resched();
 
 	mock_timeline_init(&tl, 0);
 
@@ -382,7 +381,6 @@ static int bench_sync(void *arg)
 		__func__, count, (long long)div64_ul(ktime_to_ns(kt), count));
 
 	mock_timeline_fini(&tl);
-	cond_resched();
 
 	mock_timeline_init(&tl, 0);
 
@@ -405,7 +403,6 @@ static int bench_sync(void *arg)
 	pr_info("%s: %lu repeated insert/lookups, %lluns/op\n",
 		__func__, count, (long long)div64_ul(ktime_to_ns(kt), count));
 	mock_timeline_fini(&tl);
-	cond_resched();
 
 	/* Benchmark searching for a known context id and changing the seqno */
 	for (last_order = 1, order = 1; order < 32;
@@ -434,7 +431,6 @@ static int bench_sync(void *arg)
 			__func__, count, order,
 			(long long)div64_ul(ktime_to_ns(kt), count));
 		mock_timeline_fini(&tl);
-		cond_resched();
 	}
 
 	return 0;
drivers/gpu/drm/i915/i915_active.c +1 -1
index 5ec293011d99..810251c33495 100644
@@ -865,7 +865,7 @@ int i915_active_acquire_preallocate_barrier(struct i915_active *ref,
 
 	/* Wait until the previous preallocation is completed */
 	while (!llist_empty(&ref->preallocated_barriers))
-		cond_resched();
+		cond_resched_stall();
 
 	/*
 	 * Preallocate a node for each physical engine supporting the target
drivers/gpu/drm/i915/i915_gem_evict.c +0 -2
index c02ebd6900ae..1a600f42a3ad 100644
@@ -267,8 +267,6 @@ i915_gem_evict_something(struct i915_address_space *vm,
 	if (ret)
 		return ret;
 
-	cond_resched();
-
 	flags |= PIN_NONBLOCK;
 	goto search_again;
 
drivers/gpu/drm/i915/i915_gpu_error.c +6 -12
index 4008bb09fdb5..410072145d4d 100644
@@ -320,8 +320,6 @@ static int compress_page(struct i915_vma_compress *c,
 
 		if (zlib_deflate(zstream, Z_NO_FLUSH) != Z_OK)
 			return -EIO;
-
-		cond_resched();
 	} while (zstream->avail_in);
 
 	/* Fallback to uncompressed if we increase size? */
@@ -408,7 +406,6 @@ static int compress_page(struct i915_vma_compress *c,
 	if (!(wc && i915_memcpy_from_wc(ptr, src, PAGE_SIZE)))
 		memcpy(ptr, src, PAGE_SIZE);
 	list_add_tail(&virt_to_page(ptr)->lru, &dst->page_list);
-	cond_resched();
 
 	return 0;
 }
@@ -2325,13 +2322,6 @@ void intel_klog_error_capture(struct intel_gt *gt,
 						 l_count, line++, ptr2);
 					ptr[pos] = chr;
 					ptr2 = ptr + pos;
-
-					/*
-					 * If spewing large amounts of data via a serial console,
-					 * this can be a very slow process. So be friendly and try
-					 * not to cause 'softlockup on CPU' problems.
-					 */
-					cond_resched();
 				}
 
 				if (ptr2 < (ptr + count))
@@ -2352,8 +2342,12 @@ void intel_klog_error_capture(struct intel_gt *gt,
 				got--;
 			}
 
-			/* As above. */
-			cond_resched();
+			/*
+			 * If spewing large amounts of data via a serial console,
+			 * this can be a very slow process. So be friendly and try
+			 * not to cause 'softlockup on CPU' problems.
+			 */
+			cond_resched_stall();
 		}
 
 		if (got)
drivers/gpu/drm/i915/intel_uncore.c +0 -1
index dfefad5a5fec..d2e74cfb1aac 100644
@@ -487,7 +487,6 @@ intel_uncore_forcewake_reset(struct intel_uncore *uncore)
 		}
 
 		spin_unlock_irqrestore(&uncore->lock, irqflags);
-		cond_resched();
 	}
 
 	drm_WARN_ON(&uncore->i915->drm, active_domains);
drivers/gpu/drm/i915/selftests/i915_gem_gtt.c +0 -2
index 5c397a2df70e..4b497e969a33 100644
@@ -201,7 +201,6 @@ static int igt_ppgtt_alloc(void *arg)
 		}
 
 		ppgtt->vm.allocate_va_range(&ppgtt->vm, &stash, 0, size);
-		cond_resched();
 
 		ppgtt->vm.clear_range(&ppgtt->vm, 0, size);
 
@@ -224,7 +223,6 @@ static int igt_ppgtt_alloc(void *arg)
 
 		ppgtt->vm.allocate_va_range(&ppgtt->vm, &stash,
 					    last, size - last);
-		cond_resched();
 
 		i915_vm_free_pt_stash(&ppgtt->vm, &stash);
 	}
drivers/gpu/drm/i915/selftests/i915_request.c +0 -2
index a9b79888c193..43bb54fc8c78 100644
@@ -438,8 +438,6 @@ static void __igt_breadcrumbs_smoketest(struct kthread_work *work)
 
 		num_fences += count;
 		num_waits++;
-
-		cond_resched();
 	}
 
 	atomic_long_add(num_fences, &t->num_fences);
drivers/gpu/drm/i915/selftests/i915_selftest.c +0 -3
index ee79e0809a6d..17e6bbc3c87e 100644
@@ -179,7 +179,6 @@ static int __run_selftests(const char *name,
 		if (!st->enabled)
 			continue;
 
-		cond_resched();
 		if (signal_pending(current))
 			return -EINTR;
 
@@ -381,7 +380,6 @@ int __i915_subtests(const char *caller,
 	int err;
 
 	for (; count--; st++) {
-		cond_resched();
 		if (signal_pending(current))
 			return -EINTR;
 
@@ -414,7 +412,6 @@ bool __igt_timeout(unsigned long timeout, const char *fmt, ...)
 	va_list va;
 
 	if (!signal_pending(current)) {
-		cond_resched();
 		if (time_before(jiffies, timeout))
 			return false;
 	}
drivers/gpu/drm/i915/selftests/i915_vma.c +0 -9
index 71b52d5efef4..1bacdcd77c5b 100644
@@ -197,8 +197,6 @@ static int igt_vma_create(void *arg)
 			list_del_init(&ctx->link);
 			mock_context_close(ctx);
 		}
-
-		cond_resched();
 	}
 
 end:
@@ -347,8 +345,6 @@ static int igt_vma_pin1(void *arg)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 	err = 0;
@@ -697,7 +693,6 @@ static int igt_vma_rotate_remap(void *arg)
 						pr_err("Unbinding returned %i\n", err);
 						goto out_object;
 					}
-					cond_resched();
 				}
 			}
 		}
@@ -858,8 +853,6 @@ static int igt_vma_partial(void *arg)
 					pr_err("Unbinding returned %i\n", err);
 					goto out_object;
 				}
-
-				cond_resched();
 			}
 		}
 
@@ -1085,8 +1078,6 @@ static int igt_vma_remapped_gtt(void *arg)
 				}
 			}
 			i915_vma_unpin_iomap(vma);
-
-			cond_resched();
 		}
 	}
 
drivers/gpu/drm/i915/selftests/igt_flush_test.c +0 -2
index 29110abb4fe0..fbc1b606df29 100644
@@ -22,8 +22,6 @@ int igt_flush_test(struct drm_i915_private *i915)
 		if (intel_gt_is_wedged(gt))
 			ret = -EIO;
 
-		cond_resched();
-
 		if (intel_gt_wait_for_idle(gt, HZ * 3) == -ETIME) {
 			pr_err("%pS timed out, cancelling all further testing.\n",
 			       __builtin_return_address(0));
drivers/gpu/drm/i915/selftests/intel_memory_region.c +0 -4
index d985d9bae2e8..3fce433284bd 100644
@@ -46,8 +46,6 @@ static void close_objects(struct intel_memory_region *mem,
 		i915_gem_object_put(obj);
 	}
 
-	cond_resched();
-
 	i915_gem_drain_freed_objects(i915);
 }
 
@@ -1290,8 +1288,6 @@ static int _perf_memcpy(struct intel_memory_region *src_mr,
 			div64_u64(mul_u32_u32(4 * size,
 					      1000 * 1000 * 1000),
 				  t[1] + 2 * t[2] + t[3]) >> 20);
-
-		cond_resched();
 	}
 
 	i915_gem_object_unpin_map(dst);
drivers/gpu/drm/tests/drm_buddy_test.c +0 -5
index 09ee6f6af896..7ee65bad4bb7 100644
@@ -29,7 +29,6 @@ static bool __timeout(unsigned long timeout, const char *fmt, ...)
 	va_list va;
 
 	if (!signal_pending(current)) {
-		cond_resched();
 		if (time_before(jiffies, timeout))
 			return false;
 	}
@@ -485,8 +484,6 @@ static void drm_test_buddy_alloc_smoke(struct kunit *test)
 
 		if (err || timeout)
 			break;
-
-		cond_resched();
 	}
 
 	kfree(order);
@@ -681,8 +678,6 @@ static void drm_test_buddy_alloc_range(struct kunit *test)
 		rem -= size;
 		if (!rem)
 			break;
-
-		cond_resched();
 	}
 
 	drm_buddy_free_list(&mm, &blocks);
drivers/gpu/drm/tests/drm_mm_test.c +0 -29
index 05d5e7af6d25..7d11740ef599 100644
@@ -474,8 +474,6 @@ static void drm_test_mm_reserve(struct kunit *test)
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_reserve(test, count, size - 1));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_reserve(test, count, size));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_reserve(test, count, size + 1));
-
-		cond_resched();
 	}
 }
 
@@ -645,8 +643,6 @@ static int __drm_test_mm_insert(struct kunit *test, unsigned int count, u64 size
 		drm_mm_for_each_node_safe(node, next, &mm)
 			drm_mm_remove_node(node);
 		DRM_MM_BUG_ON(!drm_mm_clean(&mm));
-
-		cond_resched();
 	}
 
 	ret = 0;
@@ -671,8 +667,6 @@ static void drm_test_mm_insert(struct kunit *test)
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size - 1, false));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size, false));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size + 1, false));
-
-		cond_resched();
 	}
 }
 
@@ -693,8 +687,6 @@ static void drm_test_mm_replace(struct kunit *test)
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size - 1, true));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size, true));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert(test, count, size + 1, true));
-
-		cond_resched();
 	}
 }
 
@@ -882,8 +874,6 @@ static int __drm_test_mm_insert_range(struct kunit *test, unsigned int count, u6
 		drm_mm_for_each_node_safe(node, next, &mm)
 			drm_mm_remove_node(node);
 		DRM_MM_BUG_ON(!drm_mm_clean(&mm));
-
-		cond_resched();
 	}
 
 	ret = 0;
@@ -942,8 +932,6 @@ static void drm_test_mm_insert_range(struct kunit *test)
 								    max / 2, max));
 		KUNIT_ASSERT_FALSE(test, __drm_test_mm_insert_range(test, count, size,
 								    max / 4 + 1, 3 * max / 4 - 1));
-
-		cond_resched();
 	}
 }
 
@@ -1086,8 +1074,6 @@ static void drm_test_mm_align(struct kunit *test)
 		drm_mm_for_each_node_safe(node, next, &mm)
 			drm_mm_remove_node(node);
 		DRM_MM_BUG_ON(!drm_mm_clean(&mm));
-
-		cond_resched();
 	}
 
 out:
@@ -1122,8 +1108,6 @@ static void drm_test_mm_align_pot(struct kunit *test, int max)
 			KUNIT_FAIL(test, "insert failed with alignment=%llx [%d]", align, bit);
 			goto out;
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -1465,8 +1449,6 @@ static void drm_test_mm_evict(struct kunit *test)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -1547,8 +1529,6 @@ static void drm_test_mm_evict_range(struct kunit *test)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -1658,7 +1638,6 @@ static void drm_test_mm_topdown(struct kunit *test)
 		drm_mm_for_each_node_safe(node, next, &mm)
 			drm_mm_remove_node(node);
 		DRM_MM_BUG_ON(!drm_mm_clean(&mm));
-		cond_resched();
 	}
 
 out:
@@ -1750,7 +1729,6 @@ static void drm_test_mm_bottomup(struct kunit *test)
 		drm_mm_for_each_node_safe(node, next, &mm)
 			drm_mm_remove_node(node);
 		DRM_MM_BUG_ON(!drm_mm_clean(&mm));
-		cond_resched();
 	}
 
 out:
@@ -1968,8 +1946,6 @@ static void drm_test_mm_color(struct kunit *test)
 			drm_mm_remove_node(node);
 			kfree(node);
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -2038,7 +2014,6 @@ static int evict_color(struct kunit *test, struct drm_mm *mm, u64 range_start,
 		}
 	}
 
-	cond_resched();
 	return 0;
 }
 
@@ -2110,8 +2085,6 @@ static void drm_test_mm_color_evict(struct kunit *test)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 out:
@@ -2196,8 +2169,6 @@ static void drm_test_mm_color_evict_range(struct kunit *test)
 				goto out;
 			}
 		}
-
-		cond_resched();
 	}
 
 out:
Signature · 1 line
2.31.1
#208 lore raw

RFC PATCH 84/86 treewide: net: remove cond_resched()

In reply to Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

    cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

Most of the uses here are in set-1 (some right after we give up a lock, causing an explicit preemption check.)

There are some uses from set-3 where we busy wait: ex. mlx4/mlx5 drivers, mtk_mdio_busy_wait() and similar. Replaced with cond_resched_stall(). Some of those places, however, have wait-times in milliseconds, so maybe we should just be a timed-wait?

Note: there are also a few other cases, where I've replaced by cond_resched_stall() (ex mhi_net_rx_refill_work() or broadcom/b43::lo_measure_feedthrough()) where it doesn't seem like the right thing.

[1] https://lore.kernel.org/lkml/[email protected]/

Cc "David S. Miller" <[email protected]>
Cc Eric Dumazet <[email protected]>
Cc Jakub Kicinski <[email protected]>
Cc Paolo Abeni <[email protected]>
Cc Felix Fietkau <[email protected]>
Cc John Crispin <[email protected]>
Cc Sean Wang <[email protected]>
Cc Mark Lee <[email protected]>
Cc Lorenzo Bianconi <[email protected]>
Cc Matthias Brugger <[email protected]>
Cc AngeloGioacchino Del Regno <[email protected]>
Cc "Michael S. Tsirkin" <[email protected]>
Cc Jason Wang <[email protected]>
Cc "Jason A. Donenfeld" <[email protected]>
Cc Kalle Valo <[email protected]>
Cc Larry Finger <[email protected]>
Cc Ryder Lee <[email protected]>
Cc Loic Poulain <[email protected]>
Cc Sergey Ryazanov <[email protected]>
---
 drivers/net/dummy.c                                 |  1 -
 drivers/net/ethernet/broadcom/tg3.c                 |  2 +-
 drivers/net/ethernet/intel/e1000/e1000_hw.c         |  3 ---
 drivers/net/ethernet/mediatek/mtk_eth_soc.c         |  2 +-
 drivers/net/ethernet/mellanox/mlx4/catas.c          |  2 +-
 drivers/net/ethernet/mellanox/mlx4/cmd.c            | 13 ++++++-------
 .../net/ethernet/mellanox/mlx4/resource_tracker.c   |  9 ++++++++-
 drivers/net/ethernet/mellanox/mlx5/core/cmd.c       |  4 +---
 drivers/net/ethernet/mellanox/mlx5/core/fw.c        |  3 +--
 drivers/net/ethernet/mellanox/mlxsw/i2c.c           |  5 -----
 drivers/net/ethernet/mellanox/mlxsw/pci.c           |  2 --
 drivers/net/ethernet/pasemi/pasemi_mac.c            |  3 ---
 .../net/ethernet/qlogic/netxen/netxen_nic_init.c    |  2 --
 .../net/ethernet/qlogic/qlcnic/qlcnic_83xx_init.c   |  1 -
 drivers/net/ethernet/qlogic/qlcnic/qlcnic_init.c    |  1 -
 .../net/ethernet/qlogic/qlcnic/qlcnic_minidump.c    |  2 --
 drivers/net/ethernet/sfc/falcon/falcon.c            |  6 ------
 drivers/net/ifb.c                                   |  1 -
 drivers/net/ipvlan/ipvlan_core.c                    |  1 -
 drivers/net/macvlan.c                               |  2 --
 drivers/net/mhi_net.c                               |  4 ++--
 drivers/net/netdevsim/fib.c                         |  1 -
 drivers/net/virtio_net.c                            |  2 --
 drivers/net/wireguard/ratelimiter.c                 |  2 --
 drivers/net/wireguard/receive.c                     |  3 ---
 drivers/net/wireguard/send.c                        |  4 ----
 drivers/net/wireless/broadcom/b43/lo.c              |  6 +++---
 drivers/net/wireless/broadcom/b43/pio.c             |  1 -
 drivers/net/wireless/broadcom/b43legacy/phy.c       |  5 -----
 .../wireless/broadcom/brcm80211/brcmfmac/cfg80211.c |  1 -
 drivers/net/wireless/cisco/airo.c                   |  2 --
 drivers/net/wireless/intel/iwlwifi/pcie/trans.c     |  2 --
 drivers/net/wireless/marvell/mwl8k.c                |  2 --
 drivers/net/wireless/mediatek/mt76/util.c           |  1 -
 drivers/net/wwan/mhi_wwan_mbim.c                    |  2 +-
 drivers/net/wwan/t7xx/t7xx_hif_dpmaif_tx.c          |  3 ---
 drivers/net/xen-netback/netback.c                   |  1 -
 drivers/net/xen-netback/rx.c                        |  2 --
 38 files changed, 25 insertions(+), 84 deletions(-)
drivers/net/dummy.c +0 -1
index c4b1b0aa438a..dfebf6387d8a 100644
@@ -182,7 +182,6 @@ static int __init dummy_init_module(void)
 
 	for (i = 0; i < numdummies && !err; i++) {
 		err = dummy_init_one();
-		cond_resched();
 	}
 	if (err < 0)
 		__rtnl_link_unregister(&dummy_link_ops);
drivers/net/ethernet/broadcom/tg3.c +1 -1
index 14b311196b8f..ad511d721db3 100644
@@ -12040,7 +12040,7 @@ static int tg3_get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom,
 				ret = -EINTR;
 				goto eeprom_done;
 			}
-			cond_resched();
+			cond_resched_stall();
 		}
 	}
 	eeprom->len += i;
drivers/net/ethernet/intel/e1000/e1000_hw.c +0 -3
index 4542e2bc28e8..22a419bdc6b7 100644
@@ -3937,7 +3937,6 @@ static s32 e1000_do_read_eeprom(struct e1000_hw *hw, u16 offset, u16 words,
 			 */
 			data[i] = e1000_shift_in_ee_bits(hw, 16);
 			e1000_standby_eeprom(hw);
-			cond_resched();
 		}
 	}
 
@@ -4088,7 +4087,6 @@ static s32 e1000_write_eeprom_spi(struct e1000_hw *hw, u16 offset, u16 words,
 			return -E1000_ERR_EEPROM;
 
 		e1000_standby_eeprom(hw);
-		cond_resched();
 
 		/*  Send the WRITE ENABLE command (8 bit opcode )  */
 		e1000_shift_out_ee_bits(hw, EEPROM_WREN_OPCODE_SPI,
@@ -4198,7 +4196,6 @@ static s32 e1000_write_eeprom_microwire(struct e1000_hw *hw, u16 offset,
 
 		/* Recover from write */
 		e1000_standby_eeprom(hw);
-		cond_resched();
 
 		words_written++;
 	}
drivers/net/ethernet/mediatek/mtk_eth_soc.c +1 -1
index 20afe79f380a..26a9f293ed32 100644
@@ -309,7 +309,7 @@ static int mtk_mdio_busy_wait(struct mtk_eth *eth)
 			return 0;
 		if (time_after(jiffies, t_start + PHY_IAC_TIMEOUT))
 			break;
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	dev_err(eth->dev, "mdio: MDIO timeout\n");
drivers/net/ethernet/mellanox/mlx4/catas.c +1 -1
index 0d8a362c2673..f013eb3fa6f8 100644
@@ -148,7 +148,7 @@ static int mlx4_reset_slave(struct mlx4_dev *dev)
 			mlx4_warn(dev, "VF Reset succeed\n");
 			return 0;
 		}
-		cond_resched();
+		cond_resched_stall();
 	}
 	mlx4_err(dev, "Fail to send reset over the communication channel\n");
 	return -ETIMEDOUT;
drivers/net/ethernet/mellanox/mlx4/cmd.c +6 -7
index f5b1f8c7834f..259918642b50 100644
@@ -312,7 +312,8 @@ static int mlx4_comm_cmd_poll(struct mlx4_dev *dev, u8 cmd, u16 param,
 
 	end = msecs_to_jiffies(timeout) + jiffies;
 	while (comm_pending(dev) && time_before(jiffies, end))
-		cond_resched();
+		cond_resched_stall();
+
 	ret_from_pending = comm_pending(dev);
 	if (ret_from_pending) {
 		/* check if the slave is trying to boot in the middle of
@@ -387,7 +388,7 @@ static int mlx4_comm_cmd_wait(struct mlx4_dev *dev, u8 vhcr_cmd,
 	if (!(dev->persist->state & MLX4_DEVICE_STATE_INTERNAL_ERROR)) {
 		end = msecs_to_jiffies(timeout) + jiffies;
 		while (comm_pending(dev) && time_before(jiffies, end))
-			cond_resched();
+			cond_resched_stall();
 	}
 	goto out;
 
@@ -470,7 +471,7 @@ static int mlx4_cmd_post(struct mlx4_dev *dev, u64 in_param, u64 out_param,
 			mlx4_err(dev, "%s:cmd_pending failed\n", __func__);
 			goto out;
 		}
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	/*
@@ -621,8 +622,7 @@ static int mlx4_cmd_poll(struct mlx4_dev *dev, u64 in_param, u64 *out_param,
 			err = mlx4_internal_err_ret_value(dev, op, op_modifier);
 			goto out;
 		}
-
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	if (cmd_pending(dev)) {
@@ -2324,8 +2324,7 @@ static int sync_toggles(struct mlx4_dev *dev)
 			priv->cmd.comm_toggle = rd_toggle >> 31;
 			return 0;
 		}
-
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	/*
drivers/net/ethernet/mellanox/mlx4/resource_tracker.c +8 -1
index 771b92019af1..c8127acea986 100644
@@ -4649,7 +4649,14 @@ static int move_all_busy(struct mlx4_dev *dev, int slave,
 		if (time_after(jiffies, begin + 5 * HZ))
 			break;
 		if (busy)
-			cond_resched();
+			/*
+			 * Giving up the spinlock in _move_all_busy() will
+			 * reschedule if needed.
+			 * Add a cpu_relax() here to ensure that we give
+			 * others a chance to acquire the lock.
+			 */
+			cpu_relax();
+
 	} while (busy);
 
 	if (busy)
drivers/net/ethernet/mellanox/mlx5/core/cmd.c +1 -3
index c22b0ad0c870..3c5bfa8eda00 100644
@@ -285,7 +285,7 @@ static void poll_timeout(struct mlx5_cmd_work_ent *ent)
 			ent->ret = 0;
 			return;
 		}
-		cond_resched();
+		cond_resched_stall();
 	} while (time_before(jiffies, poll_end));
 
 	ent->ret = -ETIMEDOUT;
@@ -1773,13 +1773,11 @@ void mlx5_cmd_flush(struct mlx5_core_dev *dev)
 	for (i = 0; i < cmd->vars.max_reg_cmds; i++) {
 		while (down_trylock(&cmd->vars.sem)) {
 			mlx5_cmd_trigger_completions(dev);
-			cond_resched();
 		}
 	}
 
 	while (down_trylock(&cmd->vars.pages_sem)) {
 		mlx5_cmd_trigger_completions(dev);
-		cond_resched();
 	}
 
 	/* Unlock cmdif */
drivers/net/ethernet/mellanox/mlx5/core/fw.c +1 -2
index 58f4c0d0fafa..a08ca20ceeda 100644
@@ -373,8 +373,7 @@ int mlx5_cmd_fast_teardown_hca(struct mlx5_core_dev *dev)
 	do {
 		if (mlx5_get_nic_state(dev) == MLX5_NIC_IFC_DISABLED)
 			break;
-
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after(jiffies, end));
 
 	if (mlx5_get_nic_state(dev) != MLX5_NIC_IFC_DISABLED) {
drivers/net/ethernet/mellanox/mlxsw/i2c.c +0 -5
index d23f293e285c..1a11f8cd6bb9 100644
@@ -180,7 +180,6 @@ static int mlxsw_i2c_wait_go_bit(struct i2c_client *client,
 				break;
 			}
 		}
-		cond_resched();
 	} while ((time_before(jiffies, end)) || (i++ < MLXSW_I2C_RETRY));
 
 	if (wait_done) {
@@ -361,8 +360,6 @@ mlxsw_i2c_write(struct device *dev, size_t in_mbox_size, u8 *in_mbox, int num,
 			err = i2c_transfer(client->adapter, &write_tran, 1);
 			if (err == 1)
 				break;
-
-			cond_resched();
 		} while ((time_before(jiffies, end)) ||
 			 (j++ < MLXSW_I2C_RETRY));
 
@@ -473,8 +470,6 @@ mlxsw_i2c_cmd(struct device *dev, u16 opcode, u32 in_mod, size_t in_mbox_size,
 					   ARRAY_SIZE(read_tran));
 			if (err == ARRAY_SIZE(read_tran))
 				break;
-
-			cond_resched();
 		} while ((time_before(jiffies, end)) ||
 			 (j++ < MLXSW_I2C_RETRY));
 
drivers/net/ethernet/mellanox/mlxsw/pci.c +0 -2
index 51eea1f0529c..8124b27d0eaa 100644
@@ -1455,7 +1455,6 @@ static int mlxsw_pci_sys_ready_wait(struct mlxsw_pci *mlxsw_pci,
 		val = mlxsw_pci_read32(mlxsw_pci, FW_READY);
 		if ((val & MLXSW_PCI_FW_READY_MASK) == MLXSW_PCI_FW_READY_MAGIC)
 			return 0;
-		cond_resched();
 	} while (time_before(jiffies, end));
 
 	*p_sys_status = val & MLXSW_PCI_FW_READY_MASK;
@@ -1824,7 +1823,6 @@ static int mlxsw_pci_cmd_exec(void *bus_priv, u16 opcode, u8 opcode_mod,
 				*p_status = ctrl >> MLXSW_PCI_CIR_CTRL_STATUS_SHIFT;
 				break;
 			}
-			cond_resched();
 		} while (time_before(jiffies, end));
 	} else {
 		wait_event_timeout(mlxsw_pci->cmd.wait, *p_wait_done, timeout);
drivers/net/ethernet/pasemi/pasemi_mac.c +0 -3
index ed7dd0a04235..3ec6ac758878 100644
@@ -1225,7 +1225,6 @@ static void pasemi_mac_pause_txchan(struct pasemi_mac *mac)
 		sta = read_dma_reg(PAS_DMA_TXCHAN_TCMDSTA(txch));
 		if (!(sta & PAS_DMA_TXCHAN_TCMDSTA_ACT))
 			break;
-		cond_resched();
 	}
 
 	if (sta & PAS_DMA_TXCHAN_TCMDSTA_ACT)
@@ -1246,7 +1245,6 @@ static void pasemi_mac_pause_rxchan(struct pasemi_mac *mac)
 		sta = read_dma_reg(PAS_DMA_RXCHAN_CCMDSTA(rxch));
 		if (!(sta & PAS_DMA_RXCHAN_CCMDSTA_ACT))
 			break;
-		cond_resched();
 	}
 
 	if (sta & PAS_DMA_RXCHAN_CCMDSTA_ACT)
@@ -1265,7 +1263,6 @@ static void pasemi_mac_pause_rxint(struct pasemi_mac *mac)
 		sta = read_dma_reg(PAS_DMA_RXINT_RCMDSTA(mac->dma_if));
 		if (!(sta & PAS_DMA_RXINT_RCMDSTA_ACT))
 			break;
-		cond_resched();
 	}
 
 	if (sta & PAS_DMA_RXINT_RCMDSTA_ACT)
drivers/net/ethernet/qlogic/netxen/netxen_nic_init.c +0 -2
index 35ec9aab3dc7..c26c43a7a83c 100644
@@ -326,8 +326,6 @@ static int netxen_wait_rom_done(struct netxen_adapter *adapter)
 	long timeout = 0;
 	long done = 0;
 
-	cond_resched();
-
 	while (done == 0) {
 		done = NXRD32(adapter, NETXEN_ROMUSB_GLB_STATUS);
 		done &= 2;
drivers/net/ethernet/qlogic/qlcnic/qlcnic_83xx_init.c +0 -1
index c95d56e56c59..359db1fa500f 100644
@@ -2023,7 +2023,6 @@ static void qlcnic_83xx_exec_template_cmd(struct qlcnic_adapter *p_dev,
 			break;
 		}
 		entry += p_hdr->size;
-		cond_resched();
 	}
 	p_dev->ahw->reset.seq_index = index;
 }
drivers/net/ethernet/qlogic/qlcnic/qlcnic_init.c +0 -1
index 09f20c794754..110b1ea921e5 100644
@@ -295,7 +295,6 @@ static int qlcnic_wait_rom_done(struct qlcnic_adapter *adapter)
 	long done = 0;
 	int err = 0;
 
-	cond_resched();
 	while (done == 0) {
 		done = QLCRD32(adapter, QLCNIC_ROMUSB_GLB_STATUS, &err);
 		done &= 2;
drivers/net/ethernet/qlogic/qlcnic/qlcnic_minidump.c +0 -2
index 7ecb3dfe30bd..38b4f56fc464 100644
@@ -702,7 +702,6 @@ static u32 qlcnic_read_memory_test_agent(struct qlcnic_adapter *adapter,
 		addr += 16;
 		reg_read -= 16;
 		ret += 16;
-		cond_resched();
 	}
 out:
 	mutex_unlock(&adapter->ahw->mem_lock);
@@ -1383,7 +1382,6 @@ int qlcnic_dump_fw(struct qlcnic_adapter *adapter)
 		buf_offset += entry->hdr.cap_size;
 		entry_offset += entry->hdr.offset;
 		buffer = fw_dump->data + buf_offset;
-		cond_resched();
 	}
 
 	fw_dump->clr = 1;
drivers/net/ethernet/sfc/falcon/falcon.c +0 -6
index 7a1c9337081b..44cc6e1bef57 100644
@@ -630,8 +630,6 @@ falcon_spi_read(struct ef4_nic *efx, const struct falcon_spi_device *spi,
 			break;
 		pos += block_len;
 
-		/* Avoid locking up the system */
-		cond_resched();
 		if (signal_pending(current)) {
 			rc = -EINTR;
 			break;
@@ -723,8 +721,6 @@ falcon_spi_write(struct ef4_nic *efx, const struct falcon_spi_device *spi,
 
 		pos += block_len;
 
-		/* Avoid locking up the system */
-		cond_resched();
 		if (signal_pending(current)) {
 			rc = -EINTR;
 			break;
@@ -839,8 +835,6 @@ falcon_spi_erase(struct falcon_mtd_partition *part, loff_t start, size_t len)
 		if (memcmp(empty, buffer, block_len))
 			return -EIO;
 
-		/* Avoid locking up the system */
-		cond_resched();
 		if (signal_pending(current))
 			return -EINTR;
 	}
drivers/net/ifb.c +0 -1
index 78253ad57b2e..ffd23d862967 100644
@@ -434,7 +434,6 @@ static int __init ifb_init_module(void)
 
 	for (i = 0; i < numifbs && !err; i++) {
 		err = ifb_init_one(i);
-		cond_resched();
 	}
 	if (err)
 		__rtnl_link_unregister(&ifb_link_ops);
drivers/net/ipvlan/ipvlan_core.c +0 -1
index c0c49f181367..91a4d1bda8a0 100644
@@ -292,7 +292,6 @@ void ipvlan_process_multicast(struct work_struct *work)
 				kfree_skb(skb);
 		}
 		dev_put(dev);
-		cond_resched();
 	}
 }
 
drivers/net/macvlan.c +0 -2
index 02bd201bc7e5..120af3235f4d 100644
@@ -341,8 +341,6 @@ static void macvlan_process_broadcast(struct work_struct *w)
 		if (src)
 			dev_put(src->dev);
 		consume_skb(skb);
-
-		cond_resched();
 	}
 }
 
drivers/net/mhi_net.c +2 -2
index ae169929a9d8..cbb59a94b083 100644
@@ -291,9 +291,9 @@ static void mhi_net_rx_refill_work(struct work_struct *work)
 		}
 
 		/* Do not hog the CPU if rx buffers are consumed faster than
-		 * queued (unlikely).
+		 * queued (uhlikely).
 		 */
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	/* If we're still starved of rx buffers, reschedule later */
drivers/net/netdevsim/fib.c +0 -1
index a1f91ff8ec56..7b7a37b247d1 100644
@@ -1492,7 +1492,6 @@ static void nsim_fib_event_work(struct work_struct *work)
 		nsim_fib_event(fib_event);
 		list_del(&fib_event->list);
 		kfree(fib_event);
-		cond_resched();
 	}
 	mutex_unlock(&data->fib_lock);
 }
drivers/net/virtio_net.c +0 -2
index d67f742fbd4c..d0d7cd077a85 100644
@@ -4015,7 +4015,6 @@ static void free_unused_bufs(struct virtnet_info *vi)
 		struct virtqueue *vq = vi->sq[i].vq;
 		while ((buf = virtqueue_detach_unused_buf(vq)) != NULL)
 			virtnet_sq_free_unused_buf(vq, buf);
-		cond_resched();
 	}
 
 	for (i = 0; i < vi->max_queue_pairs; i++) {
@@ -4023,7 +4022,6 @@ static void free_unused_bufs(struct virtnet_info *vi)
 
 		while ((buf = virtnet_rq_detach_unused_buf(rq)) != NULL)
 			virtnet_rq_free_unused_buf(rq->vq, buf);
-		cond_resched();
 	}
 }
 
drivers/net/wireguard/ratelimiter.c +0 -2
index dd55e5c26f46..c9c411ec377a 100644
@@ -74,8 +74,6 @@ static void wg_ratelimiter_gc_entries(struct work_struct *work)
 		}
 #endif
 		spin_unlock(&table_lock);
-		if (likely(work))
-			cond_resched();
 	}
 	if (likely(work))
 		queue_delayed_work(system_power_efficient_wq, &gc_work, HZ);
drivers/net/wireguard/receive.c +0 -3
index 0b3f0c843550..8468b041e786 100644
@@ -213,7 +213,6 @@ void wg_packet_handshake_receive_worker(struct work_struct *work)
 		wg_receive_handshake_packet(wg, skb);
 		dev_kfree_skb(skb);
 		atomic_dec(&wg->handshake_queue_len);
-		cond_resched();
 	}
 }
 
@@ -501,8 +500,6 @@ void wg_packet_decrypt_worker(struct work_struct *work)
 			likely(decrypt_packet(skb, PACKET_CB(skb)->keypair)) ?
 				PACKET_STATE_CRYPTED : PACKET_STATE_DEAD;
 		wg_queue_enqueue_per_peer_rx(skb, state);
-		if (need_resched())
-			cond_resched();
 	}
 }
 
drivers/net/wireguard/send.c +0 -4
index 95c853b59e1d..aa122729d802 100644
@@ -279,8 +279,6 @@ void wg_packet_tx_worker(struct work_struct *work)
 
 		wg_noise_keypair_put(keypair, false);
 		wg_peer_put(peer);
-		if (need_resched())
-			cond_resched();
 	}
 }
 
@@ -303,8 +301,6 @@ void wg_packet_encrypt_worker(struct work_struct *work)
 			}
 		}
 		wg_queue_enqueue_per_peer_tx(first, state);
-		if (need_resched())
-			cond_resched();
 	}
 }
 
drivers/net/wireless/broadcom/b43/lo.c +3 -3
index 338b6545a1e7..0fc018a706f3 100644
@@ -112,10 +112,10 @@ static u16 lo_measure_feedthrough(struct b43_wldev *dev,
 	udelay(21);
 	feedthrough = b43_phy_read(dev, B43_PHY_LO_LEAKAGE);
 
-	/* This is a good place to check if we need to relax a bit,
+	/* This is a good place to check if we need to relax a bit
 	 * as this is the main function called regularly
-	 * in the LO calibration. */
-	cond_resched();
+	 * in the L0 calibration. */
+	cond_resched_stall();
 
 	return feedthrough;
 }
drivers/net/wireless/broadcom/b43/pio.c +0 -1
index 8c28a9250cd1..44f5920ab6ff 100644
@@ -768,7 +768,6 @@ void b43_pio_rx(struct b43_pio_rxqueue *q)
 		stop = !pio_rx_frame(q);
 		if (stop)
 			break;
-		cond_resched();
 		if (WARN_ON_ONCE(++count > 10000))
 			break;
 	}
drivers/net/wireless/broadcom/b43legacy/phy.c +0 -5
index c1395e622759..d6d2cf2a38fe 100644
@@ -1113,7 +1113,6 @@ static u16 b43legacy_phy_lo_b_r15_loop(struct b43legacy_wldev *dev)
 		ret += b43legacy_phy_read(dev, 0x002C);
 	}
 	local_irq_restore(flags);
-	cond_resched();
 
 	return ret;
 }
@@ -1242,7 +1241,6 @@ u16 b43legacy_phy_lo_g_deviation_subval(struct b43legacy_wldev *dev,
 	}
 	ret = b43legacy_phy_read(dev, 0x002D);
 	local_irq_restore(flags);
-	cond_resched();
 
 	return ret;
 }
@@ -1580,7 +1578,6 @@ void b43legacy_phy_lo_g_measure(struct b43legacy_wldev *dev)
 			b43legacy_radio_write16(dev, 0x43, i);
 			b43legacy_radio_write16(dev, 0x52, phy->txctl2);
 			udelay(10);
-			cond_resched();
 
 			b43legacy_phy_set_baseband_attenuation(dev, j * 2);
 
@@ -1631,7 +1628,6 @@ void b43legacy_phy_lo_g_measure(struct b43legacy_wldev *dev)
 					      phy->txctl2
 					      | (3/*txctl1*/ << 4));
 			udelay(10);
-			cond_resched();
 
 			b43legacy_phy_set_baseband_attenuation(dev, j * 2);
 
@@ -1654,7 +1650,6 @@ void b43legacy_phy_lo_g_measure(struct b43legacy_wldev *dev)
 		b43legacy_phy_write(dev, 0x0812, (r27 << 8) | 0xA2);
 		udelay(2);
 		b43legacy_phy_write(dev, 0x0812, (r27 << 8) | 0xA3);
-		cond_resched();
 	} else
 		b43legacy_phy_write(dev, 0x0015, r27 | 0xEFA0);
 	b43legacy_phy_lo_adjust(dev, is_initializing);
drivers/net/wireless/broadcom/brcm80211/brcmfmac/cfg80211.c +0 -1
index 2a90bb24ba77..3cc5476c529d 100644
@@ -3979,7 +3979,6 @@ static int brcmf_cfg80211_sched_scan_stop(struct wiphy *wiphy,
 static __always_inline void brcmf_delay(u32 ms)
 {
 	if (ms < 1000 / HZ) {
-		cond_resched();
 		mdelay(ms);
 	} else {
 		msleep(ms);
drivers/net/wireless/cisco/airo.c +0 -2
index dbd13f7aa3e6..f15a55138dd9 100644
@@ -3988,8 +3988,6 @@ static u16 issuecommand(struct airo_info *ai, Cmd *pCmd, Resp *pRsp,
 		if ((IN4500(ai, COMMAND)) == pCmd->cmd)
 			// PC4500 didn't notice command, try again
 			OUT4500(ai, COMMAND, pCmd->cmd);
-		if (may_sleep && (max_tries & 255) == 0)
-			cond_resched();
 	}
 
 	if (max_tries == -1) {
drivers/net/wireless/intel/iwlwifi/pcie/trans.c +0 -2
index 198933f853c5..9ab63ff0b6aa 100644
@@ -2309,8 +2309,6 @@ static int iwl_trans_pcie_read_mem(struct iwl_trans *trans, u32 addr,
 			}
 			iwl_trans_release_nic_access(trans);
 
-			if (resched)
-				cond_resched();
 		} else {
 			return -EBUSY;
 		}
drivers/net/wireless/marvell/mwl8k.c +0 -2
index 13bcb123d122..9b4341da3163 100644
@@ -632,7 +632,6 @@ mwl8k_send_fw_load_cmd(struct mwl8k_priv *priv, void *data, int length)
 				break;
 			}
 		}
-		cond_resched();
 		udelay(1);
 	} while (--loops);
 
@@ -795,7 +794,6 @@ static int mwl8k_load_firmware(struct ieee80211_hw *hw)
 			break;
 		}
 
-		cond_resched();
 		udelay(1);
 	} while (--loops);
 
drivers/net/wireless/mediatek/mt76/util.c +0 -1
index fc76c66ff1a5..54ffe67d1365 100644
@@ -130,7 +130,6 @@ int __mt76_worker_fn(void *ptr)
 		set_bit(MT76_WORKER_RUNNING, &w->state);
 		set_current_state(TASK_RUNNING);
 		w->fn(w);
-		cond_resched();
 		clear_bit(MT76_WORKER_RUNNING, &w->state);
 	}
 
drivers/net/wwan/mhi_wwan_mbim.c +1 -1
index 3f72ae943b29..d8aaf476f25d 100644
@@ -400,7 +400,7 @@ static void mhi_net_rx_refill_work(struct work_struct *work)
 		/* Do not hog the CPU if rx buffers are consumed faster than
 		 * queued (unlikely).
 		 */
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	/* If we're still starved of rx buffers, reschedule later */
drivers/net/wwan/t7xx/t7xx_hif_dpmaif_tx.c +0 -3
index 8dab025a088a..52420b1f3669 100644
@@ -423,7 +423,6 @@ static void t7xx_do_tx_hw_push(struct dpmaif_ctrl *dpmaif_ctrl)
 		drb_send_cnt = t7xx_txq_burst_send_skb(txq);
 		if (drb_send_cnt <= 0) {
 			usleep_range(10, 20);
-			cond_resched();
 			continue;
 		}
 
@@ -437,8 +436,6 @@ static void t7xx_do_tx_hw_push(struct dpmaif_ctrl *dpmaif_ctrl)
 
 		t7xx_dpmaif_ul_update_hw_drb_cnt(&dpmaif_ctrl->hw_info, txq->index,
 						 drb_send_cnt * DPMAIF_UL_DRB_SIZE_WORD);
-
-		cond_resched();
 	} while (!t7xx_tx_lists_are_all_empty(dpmaif_ctrl) && !kthread_should_stop() &&
 		 (dpmaif_ctrl->state == DPMAIF_STATE_PWRON));
 }
drivers/net/xen-netback/netback.c +0 -1
index 88f760a7cbc3..a540e95ba58f 100644
@@ -1571,7 +1571,6 @@ int xenvif_dealloc_kthread(void *data)
 			break;
 
 		xenvif_tx_dealloc_action(queue);
-		cond_resched();
 	}
 
 	/* Unmap anything remaining*/
drivers/net/xen-netback/rx.c +0 -2
index 0ba754ebc5ba..bccefaec5312 100644
@@ -669,8 +669,6 @@ int xenvif_kthread_guest_rx(void *data)
 		 * slots.
 		 */
 		xenvif_rx_queue_drop_expired(queue);
-
-		cond_resched();
 	}
 
 	/* Bin any remaining skbs */
Signature · 1 line
2.31.1
#209 lore raw

RFC PATCH 85/86 treewide: drivers: remove cond_resched()

In reply to Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

    cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

The cond_resched() calls here are all kinds. Those from set-1 or set-2 are quite straight-forward to handle.

There are quite a few from set-3, where as noted above, we use cond_resched() as if it were a amulent. Which I supppose it is, in that it wards off softlockup or RCU splats.

Those are now cond_resched_stall(), but in most cases, given that the timeouts are in milliseconds, they could be easily timed waits.

[1] https://lore.kernel.org/lkml/[email protected]/

Cc Oded Gabbay <[email protected]>
Cc Miguel Ojeda <[email protected]>
Cc Jens Axboe <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Sergey Senozhatsky <[email protected]>
Cc Sudip Mukherjee <[email protected]>
Cc "Theodore Ts'o" <[email protected]>
Cc "Jason A. Donenfeld" <[email protected]>
Cc Amit Shah <[email protected]>
Cc Gonglei <[email protected]>
Cc "Michael S. Tsirkin" <[email protected]>
Cc Jason Wang <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Davidlohr Bueso <[email protected]>
Cc Jonathan Cameron <[email protected]>
Cc Dave Jiang <[email protected]>
Cc Alison Schofield <[email protected]>
Cc Vishal Verma <[email protected]>
Cc Ira Weiny <[email protected]>
Cc Dan Williams <[email protected]>
Cc Sumit Semwal <[email protected]>
Cc "Christian König" <[email protected]>
Cc Andi Shyti <[email protected]>
Cc Ray Jui <[email protected]>
Cc Scott Branden <[email protected]>
Cc Chris Packham <[email protected]>
Cc Shawn Guo <[email protected]>
Cc Sascha Hauer <[email protected]>
Cc Junxian Huang <[email protected]>
Cc Dmitry Torokhov <[email protected]>
Cc Will Deacon <[email protected]>
Cc Joerg Roedel <[email protected]>
Cc Mauro Carvalho Chehab <[email protected]>
Cc Srinivas Pandruvada <[email protected]>
Cc Hans de Goede <[email protected]>
Cc "Ilpo Järvinen" <[email protected]>
Cc Mark Gross <[email protected]>
Cc Finn Thain <[email protected]>
Cc Michael Schmitz <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc "Martin K. Petersen" <[email protected]>
Cc Kashyap Desai <[email protected]>
Cc Sumit Saxena <[email protected]>
Cc Shivasharan S <[email protected]>
Cc Mark Brown <[email protected]>
Cc Neil Armstrong <[email protected]>
Cc Jens Wiklander <[email protected]>
Cc Alex Williamson <[email protected]>
Cc Helge Deller <[email protected]>
Cc David Hildenbrand <[email protected]>
---
 drivers/accel/ivpu/ivpu_drv.c                      |  2 --
 drivers/accel/ivpu/ivpu_gem.c                      |  1 -
 drivers/accel/ivpu/ivpu_pm.c                       |  8 ++++++--
 drivers/accel/qaic/qaic_data.c                     |  2 --
 drivers/auxdisplay/charlcd.c                       | 11 -----------
 drivers/base/power/domain.c                        |  1 -
 drivers/block/aoe/aoecmd.c                         |  3 +--
 drivers/block/brd.c                                |  1 -
 drivers/block/drbd/drbd_bitmap.c                   |  4 ----
 drivers/block/drbd/drbd_debugfs.c                  |  1 -
 drivers/block/loop.c                               |  3 ---
 drivers/block/xen-blkback/blkback.c                |  3 ---
 drivers/block/zram/zram_drv.c                      |  2 --
 drivers/bluetooth/virtio_bt.c                      |  1 -
 drivers/char/hw_random/arm_smccc_trng.c            |  1 -
 drivers/char/lp.c                                  |  2 --
 drivers/char/mem.c                                 |  4 ----
 drivers/char/mwave/3780i.c                         |  4 +---
 drivers/char/ppdev.c                               |  4 ----
 drivers/char/random.c                              |  2 --
 drivers/char/virtio_console.c                      |  1 -
 drivers/crypto/virtio/virtio_crypto_core.c         |  1 -
 drivers/cxl/pci.c                                  |  1 -
 drivers/dma-buf/selftest.c                         |  1 -
 drivers/dma-buf/st-dma-fence-chain.c               |  1 -
 drivers/fsi/fsi-sbefifo.c                          | 14 ++++++++++++--
 drivers/i2c/busses/i2c-bcm-iproc.c                 |  9 +++++++--
 drivers/i2c/busses/i2c-highlander.c                |  9 +++++++--
 drivers/i2c/busses/i2c-ibm_iic.c                   | 11 +++++++----
 drivers/i2c/busses/i2c-mpc.c                       |  2 +-
 drivers/i2c/busses/i2c-mxs.c                       |  9 ++++++++-
 drivers/i2c/busses/scx200_acb.c                    |  9 +++++++--
 drivers/infiniband/core/umem.c                     |  1 -
 drivers/infiniband/hw/hfi1/driver.c                |  1 -
 drivers/infiniband/hw/hfi1/firmware.c              |  2 +-
 drivers/infiniband/hw/hfi1/init.c                  |  1 -
 drivers/infiniband/hw/hfi1/ruc.c                   |  1 -
 drivers/infiniband/hw/hns/hns_roce_hw_v2.c         |  5 ++++-
 drivers/infiniband/hw/qib/qib_init.c               |  1 -
 drivers/infiniband/sw/rxe/rxe_qp.c                 |  3 +--
 drivers/infiniband/sw/rxe/rxe_task.c               |  4 ++--
 drivers/input/evdev.c                              |  1 -
 drivers/input/keyboard/clps711x-keypad.c           |  2 +-
 drivers/input/misc/uinput.c                        |  1 -
 drivers/input/mousedev.c                           |  1 -
 drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c        |  2 --
 drivers/media/i2c/vpx3220.c                        |  3 ---
 drivers/media/pci/cobalt/cobalt-i2c.c              |  4 ++--
 drivers/misc/bcm-vk/bcm_vk_dev.c                   |  3 +--
 drivers/misc/bcm-vk/bcm_vk_msg.c                   |  3 +--
 drivers/misc/genwqe/card_base.c                    |  3 +--
 drivers/misc/genwqe/card_ddcb.c                    |  6 ------
 drivers/misc/genwqe/card_dev.c                     |  2 --
 drivers/misc/vmw_balloon.c                         |  4 ----
 drivers/mmc/host/mmc_spi.c                         |  3 ---
 drivers/nvdimm/btt.c                               |  2 --
 drivers/nvme/target/zns.c                          |  2 --
 drivers/parport/parport_ip32.c                     |  1 -
 drivers/parport/parport_pc.c                       |  4 ----
 drivers/pci/pci-sysfs.c                            |  1 -
 drivers/pci/proc.c                                 |  1 -
 .../x86/intel/speed_select_if/isst_if_mbox_pci.c   |  4 ++--
 drivers/s390/cio/css.c                             |  8 --------
 drivers/scsi/NCR5380.c                             |  2 --
 drivers/scsi/megaraid.c                            |  1 -
 drivers/scsi/qedi/qedi_main.c                      |  1 -
 drivers/scsi/qla2xxx/qla_nx.c                      |  2 --
 drivers/scsi/qla2xxx/qla_sup.c                     |  5 -----
 drivers/scsi/qla4xxx/ql4_nx.c                      |  1 -
 drivers/scsi/xen-scsifront.c                       |  2 +-
 drivers/spi/spi-lantiq-ssc.c                       |  3 +--
 drivers/spi/spi-meson-spifc.c                      |  2 +-
 drivers/spi/spi.c                                  |  2 +-
 drivers/staging/rtl8723bs/core/rtw_mlme_ext.c      |  2 +-
 drivers/staging/rtl8723bs/core/rtw_pwrctrl.c       |  2 --
 drivers/tee/optee/ffa_abi.c                        |  1 -
 drivers/tee/optee/smc_abi.c                        |  1 -
 drivers/tty/hvc/hvc_console.c                      |  6 ++----
 drivers/tty/tty_buffer.c                           |  3 ---
 drivers/tty/tty_io.c                               |  1 -
 drivers/usb/gadget/udc/max3420_udc.c               |  1 -
 drivers/usb/host/max3421-hcd.c                     |  2 +-
 drivers/usb/host/xen-hcd.c                         |  2 +-
 drivers/vfio/vfio_iommu_spapr_tce.c                |  2 --
 drivers/vfio/vfio_iommu_type1.c                    |  7 -------
 drivers/vhost/vhost.c                              |  1 -
 drivers/video/console/vgacon.c                     |  4 ----
 drivers/virtio/virtio_mem.c                        |  8 --------
 88 files changed, 82 insertions(+), 190 deletions(-)
drivers/accel/ivpu/ivpu_drv.c +0 -2
index 7e9359611d69..479801a1d961 100644
@@ -314,8 +314,6 @@ static int ivpu_wait_for_ready(struct ivpu_device *vdev)
 		ret = ivpu_ipc_receive(vdev, &cons, &ipc_hdr, NULL, 0);
 		if (ret != -ETIMEDOUT || time_after_eq(jiffies, timeout))
 			break;
-
-		cond_resched();
 	}
 
 	ivpu_ipc_consumer_del(vdev, &cons);
drivers/accel/ivpu/ivpu_gem.c +0 -1
index d09f13b35902..06e4c1eceae8 100644
@@ -156,7 +156,6 @@ static int __must_check internal_alloc_pages_locked(struct ivpu_bo *bo)
 			ret = -ENOMEM;
 			goto err_free_pages;
 		}
-		cond_resched();
 	}
 
 	bo->pages = pages;
drivers/accel/ivpu/ivpu_pm.c +6 -2
index ffff2496e8e8..aa9cc4a1903c 100644
@@ -105,7 +105,7 @@ static void ivpu_pm_recovery_work(struct work_struct *work)
 retry:
 	ret = pci_try_reset_function(to_pci_dev(vdev->drm.dev));
 	if (ret == -EAGAIN && !drm_dev_is_unplugged(&vdev->drm)) {
-		cond_resched();
+		cond_resched_stall();
 		goto retry;
 	}
 
@@ -146,7 +146,11 @@ int ivpu_pm_suspend_cb(struct device *dev)
 
 	timeout = jiffies + msecs_to_jiffies(vdev->timeout.tdr);
 	while (!ivpu_hw_is_idle(vdev)) {
-		cond_resched();
+
+		/* The timeout is in thousands of msecs. Maybe this should be a
+		 * timed wait instead?
+		 */
+		cond_resched_stall();
 		if (time_after_eq(jiffies, timeout)) {
 			ivpu_err(vdev, "Failed to enter idle on system suspend\n");
 			return -EBUSY;
drivers/accel/qaic/qaic_data.c +0 -2
index f4b06792c6f1..d06fd9d765f2 100644
@@ -1516,7 +1516,6 @@ void irq_polling_work(struct work_struct *work)
 			return;
 		}
 
-		cond_resched();
 		usleep_range(datapath_poll_interval_us, 2 * datapath_poll_interval_us);
 	}
 }
@@ -1547,7 +1546,6 @@ irqreturn_t dbc_irq_threaded_fn(int irq, void *data)
 
 	if (!event_count) {
 		event_count = NUM_EVENTS;
-		cond_resched();
 	}
 
 	/*
drivers/auxdisplay/charlcd.c +0 -11
index 6d309e4971b6..cb1213e292f4 100644
@@ -470,14 +470,6 @@ static ssize_t charlcd_write(struct file *file, const char __user *buf,
 	char c;
 
 	for (; count-- > 0; (*ppos)++, tmp++) {
-		if (((count + 1) & 0x1f) == 0) {
-			/*
-			 * charlcd_write() is invoked as a VFS->write() callback
-			 * and as such it is always invoked from preemptible
-			 * context and may sleep.
-			 */
-			cond_resched();
-		}
 
 		if (get_user(c, tmp))
 			return -EFAULT;
@@ -539,9 +531,6 @@ static void charlcd_puts(struct charlcd *lcd, const char *s)
 	int count = strlen(s);
 
 	for (; count-- > 0; tmp++) {
-		if (((count + 1) & 0x1f) == 0)
-			cond_resched();
-
 		charlcd_write_char(lcd, *tmp);
 	}
 }
drivers/base/power/domain.c +0 -1
index 5cb2023581d4..6b77bdfe1de9 100644
@@ -2696,7 +2696,6 @@ static void genpd_dev_pm_detach(struct device *dev, bool power_off)
 			break;
 
 		mdelay(i);
-		cond_resched();
 	}
 
 	if (ret < 0) {
drivers/block/aoe/aoecmd.c +1 -2
index d7317425be51..d212b0df661f 100644
@@ -1235,8 +1235,7 @@ kthread(void *vp)
 		if (!more) {
 			schedule();
 			remove_wait_queue(k->waitq, &wait);
-		} else
-			cond_resched();
+		}
 	} while (!kthread_should_stop());
 	complete(&k->rendez);	/* tell spawner we're stopping */
 	return 0;
drivers/block/brd.c +0 -1
index 970bd6ff38c4..be1577cd4d4b 100644
@@ -111,7 +111,6 @@ static void brd_free_pages(struct brd_device *brd)
 
 	xa_for_each(&brd->brd_pages, idx, page) {
 		__free_page(page);
-		cond_resched();
 	}
 
 	xa_destroy(&brd->brd_pages);
drivers/block/drbd/drbd_bitmap.c +0 -4
index 85ca000a0564..f12de044c540 100644
@@ -563,7 +563,6 @@ static unsigned long bm_count_bits(struct drbd_bitmap *b)
 		p_addr = __bm_map_pidx(b, idx);
 		bits += bitmap_weight(p_addr, BITS_PER_PAGE);
 		__bm_unmap(p_addr);
-		cond_resched();
 	}
 	/* last (or only) page */
 	last_word = ((b->bm_bits - 1) & BITS_PER_PAGE_MASK) >> LN2_BPL;
@@ -1118,7 +1117,6 @@ static int bm_rw(struct drbd_device *device, const unsigned int flags, unsigned
 			atomic_inc(&ctx->in_flight);
 			bm_page_io_async(ctx, i);
 			++count;
-			cond_resched();
 		}
 	} else if (flags & BM_AIO_WRITE_HINTED) {
 		/* ASSERT: BM_AIO_WRITE_ALL_PAGES is not set. */
@@ -1158,7 +1156,6 @@ static int bm_rw(struct drbd_device *device, const unsigned int flags, unsigned
 			atomic_inc(&ctx->in_flight);
 			bm_page_io_async(ctx, i);
 			++count;
-			cond_resched();
 		}
 	}
 
@@ -1545,7 +1542,6 @@ void _drbd_bm_set_bits(struct drbd_device *device, const unsigned long s, const
 	for (page_nr = first_page; page_nr < last_page; page_nr++) {
 		bm_set_full_words_within_one_page(device->bitmap, page_nr, first_word, last_word);
 		spin_unlock_irq(&b->bm_lock);
-		cond_resched();
 		first_word = 0;
 		spin_lock_irq(&b->bm_lock);
 	}
drivers/block/drbd/drbd_debugfs.c +0 -1
index 12460b584bcb..48a85882dfc4 100644
@@ -318,7 +318,6 @@ static void seq_print_resource_transfer_log_summary(struct seq_file *m,
 			struct drbd_request *req_next;
 			kref_get(&req->kref);
 			spin_unlock_irq(&resource->req_lock);
-			cond_resched();
 			spin_lock_irq(&resource->req_lock);
 			req_next = list_next_entry(req, tl_requests);
 			if (kref_put(&req->kref, drbd_req_destroy))
drivers/block/loop.c +0 -3
index 9f2d412fc560..0ea0d37b2f28 100644
@@ -271,7 +271,6 @@ static int lo_write_simple(struct loop_device *lo, struct request *rq,
 		ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
 		if (ret < 0)
 			break;
-		cond_resched();
 	}
 
 	return ret;
@@ -300,7 +299,6 @@ static int lo_read_simple(struct loop_device *lo, struct request *rq,
 				zero_fill_bio(bio);
 			break;
 		}
-		cond_resched();
 	}
 
 	return 0;
@@ -1948,7 +1946,6 @@ static void loop_process_work(struct loop_worker *worker,
 		spin_unlock_irq(&lo->lo_work_lock);
 
 		loop_handle_cmd(cmd);
-		cond_resched();
 
 		spin_lock_irq(&lo->lo_work_lock);
 	}
drivers/block/xen-blkback/blkback.c +0 -3
index c362f4ad80ab..9bcef880df30 100644
@@ -1259,9 +1259,6 @@ __do_block_io_op(struct xen_blkif_ring *ring, unsigned int *eoi_flags)
 				goto done;
 			break;
 		}
-
-		/* Yield point for this unbounded loop. */
-		cond_resched();
 	}
 done:
 	return more_to_do;
drivers/block/zram/zram_drv.c +0 -2
index 06673c6ca255..b1f9312e7905 100644
@@ -1819,8 +1819,6 @@ static ssize_t recompress_store(struct device *dev,
 			ret = err;
 			break;
 		}
-
-		cond_resched();
 	}
 
 	__free_page(page);
drivers/bluetooth/virtio_bt.c +0 -1
index 2ac70b560c46..c570c45d1480 100644
@@ -79,7 +79,6 @@ static int virtbt_close_vdev(struct virtio_bluetooth *vbt)
 
 		while ((skb = virtqueue_detach_unused_buf(vq)))
 			kfree_skb(skb);
-		cond_resched();
 	}
 
 	return 0;
drivers/char/hw_random/arm_smccc_trng.c +0 -1
index 7e954341b09f..f60d101920e4 100644
@@ -84,7 +84,6 @@ static int smccc_trng_read(struct hwrng *rng, void *data, size_t max, bool wait)
 			tries++;
 			if (tries >= SMCCC_TRNG_MAX_TRIES)
 				return copied;
-			cond_resched();
 			break;
 		default:
 			return -EIO;
drivers/char/lp.c +0 -2
index 2f171d14b9b5..1d58105112b5 100644
@@ -478,8 +478,6 @@ static ssize_t lp_read(struct file *file, char __user *buf,
 			retval = -ERESTARTSYS;
 			break;
 		}
-
-		cond_resched();
 	}
 	parport_negotiate(lp_table[minor].dev->port, IEEE1284_MODE_COMPAT);
  out:
drivers/char/mem.c +0 -4
index 1052b0f2d4cf..6f97ab7004d9 100644
@@ -92,8 +92,6 @@ static inline int range_is_allowed(unsigned long pfn, unsigned long size)
 
 static inline bool should_stop_iteration(void)
 {
-	if (need_resched())
-		cond_resched();
 	return signal_pending(current);
 }
 
@@ -497,7 +495,6 @@ static ssize_t read_iter_zero(struct kiocb *iocb, struct iov_iter *iter)
 			continue;
 		if (iocb->ki_flags & IOCB_NOWAIT)
 			return written ? written : -EAGAIN;
-		cond_resched();
 	}
 	return written;
 }
@@ -523,7 +520,6 @@ static ssize_t read_zero(struct file *file, char __user *buf,
 
 		if (signal_pending(current))
 			break;
-		cond_resched();
 	}
 
 	return cleared;
drivers/char/mwave/3780i.c +1 -3
index 4a8937f80570..927a1cca1168 100644
@@ -51,7 +51,7 @@
 #include <linux/delay.h>
 #include <linux/ioport.h>
 #include <linux/bitops.h>
-#include <linux/sched.h>	/* cond_resched() */
+#include <linux/sched.h>
 
 #include <asm/io.h>
 #include <linux/uaccess.h>
@@ -64,9 +64,7 @@ static DEFINE_SPINLOCK(dsp_lock);
 
 static void PaceMsaAccess(unsigned short usDspBaseIO)
 {
-	cond_resched();
 	udelay(100);
-	cond_resched();
 }
 
 unsigned short dsp3780I_ReadMsaCfg(unsigned short usDspBaseIO,
drivers/char/ppdev.c +0 -4
index 4c188e9e477c..7463228ba9bf 100644
@@ -176,8 +176,6 @@ static ssize_t pp_read(struct file *file, char __user *buf, size_t count,
 			bytes_read = -ERESTARTSYS;
 			break;
 		}
-
-		cond_resched();
 	}
 
 	parport_set_timeout(pp->pdev, pp->default_inactivity);
@@ -256,8 +254,6 @@ static ssize_t pp_write(struct file *file, const char __user *buf,
 
 		if (signal_pending(current))
 			break;
-
-		cond_resched();
 	}
 
 	parport_set_timeout(pp->pdev, pp->default_inactivity);
drivers/char/random.c +0 -2
index 3cb37760dfec..9e25f3a5c83d 100644
@@ -457,7 +457,6 @@ static ssize_t get_random_bytes_user(struct iov_iter *iter)
 		if (ret % PAGE_SIZE == 0) {
 			if (signal_pending(current))
 				break;
-			cond_resched();
 		}
 	}
 
@@ -1417,7 +1416,6 @@ static ssize_t write_pool_user(struct iov_iter *iter)
 		if (ret % PAGE_SIZE == 0) {
 			if (signal_pending(current))
 				break;
-			cond_resched();
 		}
 	}
 
drivers/char/virtio_console.c +0 -1
index 680d1ef2a217..1f8da0a71ce9 100644
@@ -1936,7 +1936,6 @@ static void remove_vqs(struct ports_device *portdev)
 		flush_bufs(vq, true);
 		while ((buf = virtqueue_detach_unused_buf(vq)))
 			free_buf(buf, true);
-		cond_resched();
 	}
 	portdev->vdev->config->del_vqs(portdev->vdev);
 	kfree(portdev->in_vqs);
drivers/crypto/virtio/virtio_crypto_core.c +0 -1
index 43a0838d31ff..3842915ea743 100644
@@ -490,7 +490,6 @@ static void virtcrypto_free_unused_reqs(struct virtio_crypto *vcrypto)
 			kfree(vc_req->req_data);
 			kfree(vc_req->sgs);
 		}
-		cond_resched();
 	}
 }
 
drivers/cxl/pci.c +0 -1
index 44a21ab7add5..2c7e670d9a91 100644
@@ -634,7 +634,6 @@ static irqreturn_t cxl_event_thread(int irq, void *id)
 		if (!status)
 			break;
 		cxl_mem_get_event_records(mds, status);
-		cond_resched();
 	} while (status);
 
 	return IRQ_HANDLED;
drivers/dma-buf/selftest.c +0 -1
index c60b6944b4bd..ddf94da3d412 100644
@@ -93,7 +93,6 @@ __subtests(const char *caller, const struct subtest *st, int count, void *data)
 	int err;
 
 	for (; count--; st++) {
-		cond_resched();
 		if (signal_pending(current))
 			return -EINTR;
 
drivers/dma-buf/st-dma-fence-chain.c +0 -1
index c0979c8049b5..cde69fadb4f4 100644
@@ -431,7 +431,6 @@ static int __find_race(void *arg)
 signal:
 		seqno = get_random_u32_below(data->fc.chain_length - 1);
 		dma_fence_signal(data->fc.fences[seqno]);
-		cond_resched();
 	}
 
 	if (atomic_dec_and_test(&data->children))
drivers/fsi/fsi-sbefifo.c +12 -2
index 0a98517f3959..0e58ebae0130 100644
@@ -372,7 +372,13 @@ static int sbefifo_request_reset(struct sbefifo *sbefifo)
 			return 0;
 		}
 
-		cond_resched();
+		/*
+		 * Use cond_resched_stall() to avoid spinning in a
+		 * tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should be a timed or event wait?
+		 */
+		cond_resched_stall();
 	}
 	dev_err(dev, "FIFO reset timed out\n");
 
@@ -462,7 +468,11 @@ static int sbefifo_wait(struct sbefifo *sbefifo, bool up,
 
 	end_time = jiffies + timeout;
 	while (!time_after(jiffies, end_time)) {
-		cond_resched();
+		/*
+		 * As above, maybe this should be a timed or event wait?
+		 */
+		cond_resched_stall();
+
 		rc = sbefifo_regr(sbefifo, addr, &sts);
 		if (rc < 0) {
 			dev_err(dev, "FSI error %d reading status register\n", rc);
drivers/i2c/busses/i2c-bcm-iproc.c +7 -2
index 51aab662050b..6efe6d18d859 100644
@@ -788,8 +788,13 @@ static int bcm_iproc_i2c_xfer_wait(struct bcm_iproc_i2c_dev *iproc_i2c,
 				break;
 			}
 
-			cpu_relax();
-			cond_resched();
+			/*
+			 * Use cond_resched_stall() to avoid spinning in a
+			 * tight loop.
+			 * Though, given that the timeout is in milliseconds,
+			 * maybe this should be a timed or event wait?
+			 */
+			cond_resched_stall();
 		} while (!iproc_i2c->xfer_is_done);
 	}
 
drivers/i2c/busses/i2c-highlander.c +7 -2
index 7922bc917c33..06eed7e1c4f3 100644
@@ -187,8 +187,13 @@ static void highlander_i2c_poll(struct highlander_i2c_dev *dev)
 		if (time_after(jiffies, timeout))
 			break;
 
-		cpu_relax();
-		cond_resched();
+		/*
+		 * Use cond_resched_stall() to avoid spinning in a
+		 * tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should be a timed or event wait?
+		 */
+		cond_resched_stall();
 	}
 
 	dev_err(dev->dev, "polling timed out\n");
drivers/i2c/busses/i2c-ibm_iic.c +7 -4
index 408820319ec4..b486d8b9636b 100644
@@ -207,9 +207,6 @@ static void iic_dev_reset(struct ibm_iic_private* dev)
 			udelay(10);
 			dc ^= DIRCNTL_SCC;
 			out_8(&iic->directcntl, dc);
-
-			/* be nice */
-			cond_resched();
 		}
 	}
 
@@ -231,7 +228,13 @@ static int iic_dc_wait(volatile struct iic_regs __iomem *iic, u8 mask)
 	while ((in_8(&iic->directcntl) & mask) != mask){
 		if (unlikely(time_after(jiffies, x)))
 			return -1;
-		cond_resched();
+		/*
+		 * Use cond_resched_stall() to avoid spinning in a
+		 * tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should be a timed or event wait?
+		 */
+		cond_resched_stall();
 	}
 	return 0;
 }
drivers/i2c/busses/i2c-mpc.c +1 -1
index e4e4995ab224..82d24523c6a7 100644
@@ -712,7 +712,7 @@ static int mpc_i2c_execute_msg(struct mpc_i2c *i2c)
 			}
 			return -EIO;
 		}
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	return i2c->rc;
drivers/i2c/busses/i2c-mxs.c +8 -1
index 36def0a9c95c..d4d69cd7ef46 100644
@@ -310,7 +310,14 @@ static int mxs_i2c_pio_wait_xfer_end(struct mxs_i2c_dev *i2c)
 			return -ENXIO;
 		if (time_after(jiffies, timeout))
 			return -ETIMEDOUT;
-		cond_resched();
+
+		/*
+		 * Use cond_resched_stall() to avoid spinning in a
+		 * tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should be a timed or event wait?
+		 */
+		cond_resched_stall();
 	}
 
 	return 0;
drivers/i2c/busses/scx200_acb.c +7 -2
index 83c1db610f54..5646130c003f 100644
@@ -232,8 +232,13 @@ static void scx200_acb_poll(struct scx200_acb_iface *iface)
 		}
 		if (time_after(jiffies, timeout))
 			break;
-		cpu_relax();
-		cond_resched();
+		/*
+		 * Use cond_resched_stall() to avoid spinning in a
+		 * tight loop.
+		 * Though, given that the timeout is in milliseconds,
+		 * maybe this should timeout or event wait?
+		 */
+		cond_resched_stall();
 	}
 
 	dev_err(&iface->adapter.dev, "timeout in state %s\n",
drivers/infiniband/core/umem.c +0 -1
index f9ab671c8eda..6b4d3d3193a2 100644
@@ -215,7 +215,6 @@ struct ib_umem *ib_umem_get(struct ib_device *device, unsigned long addr,
 		gup_flags |= FOLL_WRITE;
 
 	while (npages) {
-		cond_resched();
 		pinned = pin_user_pages_fast(cur_base,
 					  min_t(unsigned long, npages,
 						PAGE_SIZE /
drivers/infiniband/hw/hfi1/driver.c +0 -1
index f4492fa407e0..b390eb169a60 100644
@@ -668,7 +668,6 @@ static noinline int max_packet_exceeded(struct hfi1_packet *packet, int thread)
 		if ((packet->numpkt & (MAX_PKT_RECV_THREAD - 1)) == 0)
 			/* allow defered processing */
 			process_rcv_qp_work(packet);
-		cond_resched();
 		return RCV_PKT_OK;
 	} else {
 		this_cpu_inc(*packet->rcd->dd->rcv_limit);
drivers/infiniband/hw/hfi1/firmware.c +1 -1
index 0c0cef5b1e0e..717ccb0e69b4 100644
@@ -560,7 +560,7 @@ static void __obtain_firmware(struct hfi1_devdata *dd)
 		 * something that holds for 30 seconds.  If we do that twice
 		 * in a row it triggers task blocked warning.
 		 */
-		cond_resched();
+		cond_resched_stall();
 		if (fw_8051_load)
 			dispose_one_firmware(&fw_8051);
 		if (fw_fabric_serdes_load)
drivers/infiniband/hw/hfi1/init.c +0 -1
index 6de37c5d7d27..3b5abcd72660 100644
@@ -1958,7 +1958,6 @@ int hfi1_setup_eagerbufs(struct hfi1_ctxtdata *rcd)
 	for (idx = 0; idx < rcd->egrbufs.alloced; idx++) {
 		hfi1_put_tid(dd, rcd->eager_base + idx, PT_EAGER,
 			     rcd->egrbufs.rcvtids[idx].dma, order);
-		cond_resched();
 	}
 
 	return 0;
drivers/infiniband/hw/hfi1/ruc.c +0 -1
index b0151b7293f5..35fa25211351 100644
@@ -459,7 +459,6 @@ bool hfi1_schedule_send_yield(struct rvt_qp *qp, struct hfi1_pkt_state *ps,
 			return true;
 		}
 
-		cond_resched();
 		this_cpu_inc(*ps->ppd->dd->send_schedule);
 		ps->timeout = jiffies + ps->timeout_int;
 	}
drivers/infiniband/hw/hns/hns_roce_hw_v2.c +4 -1
index d82daff2d9bd..c76610422255 100644
@@ -2985,7 +2985,10 @@ static int v2_wait_mbox_complete(struct hns_roce_dev *hr_dev, u32 timeout,
 			return -ETIMEDOUT;
 		}
 
-		cond_resched();
+		/* The timeout is in hundreds of msecs. Maybe this should be a
+		 * timed wait instead?
+		 */
+		cond_resched_stall();
 		ret = -EBUSY;
 	}
 
drivers/infiniband/hw/qib/qib_init.c +0 -1
index 33667becd52b..0d8e0abb5090 100644
@@ -1674,7 +1674,6 @@ int qib_setup_eagerbufs(struct qib_ctxtdata *rcd)
 					  RCVHQ_RCV_TYPE_EAGER, pa);
 			pa += egrsize;
 		}
-		cond_resched(); /* don't hog the cpu */
 	}
 
 	return 0;
drivers/infiniband/sw/rxe/rxe_qp.c +1 -2
index 28e379c108bc..b0fb5a993bae 100644
@@ -778,12 +778,11 @@ int rxe_qp_to_attr(struct rxe_qp *qp, struct ib_qp_attr *attr, int mask)
 	rxe_av_to_attr(&qp->alt_av, &attr->alt_ah_attr);
 
 	/* Applications that get this state typically spin on it.
-	 * Yield the processor
+	 * Giving up the spinlock will reschedule if needed.
 	 */
 	spin_lock_irqsave(&qp->state_lock, flags);
 	if (qp->attr.sq_draining) {
 		spin_unlock_irqrestore(&qp->state_lock, flags);
-		cond_resched();
 	} else {
 		spin_unlock_irqrestore(&qp->state_lock, flags);
 	}
drivers/infiniband/sw/rxe/rxe_task.c +2 -2
index 1501120d4f52..692f57fdfdc9 100644
@@ -227,7 +227,7 @@ void rxe_cleanup_task(struct rxe_task *task)
 	 * for the previously scheduled tasks to finish.
 	 */
 	while (!is_done(task))
-		cond_resched();
+		cond_resched_stall();
 
 	spin_lock_irqsave(&task->lock, flags);
 	task->state = TASK_STATE_INVALID;
@@ -289,7 +289,7 @@ void rxe_disable_task(struct rxe_task *task)
 	spin_unlock_irqrestore(&task->lock, flags);
 
 	while (!is_done(task))
-		cond_resched();
+		cond_resched_stall();
 
 	spin_lock_irqsave(&task->lock, flags);
 	task->state = TASK_STATE_DRAINED;
drivers/input/evdev.c +0 -1
index 95f90699d2b1..effbc991be41 100644
@@ -529,7 +529,6 @@ static ssize_t evdev_write(struct file *file, const char __user *buffer,
 
 		input_inject_event(&evdev->handle,
 				   event.type, event.code, event.value);
-		cond_resched();
 	}
 
  out:
drivers/input/keyboard/clps711x-keypad.c +1 -1
index 4c1a3e611edd..e02f6d35ed51 100644
@@ -52,7 +52,7 @@ static void clps711x_keypad_poll(struct input_dev *input)
 			/* Read twice for protection against fluctuations */
 			do {
 				state = gpiod_get_value_cansleep(data->desc);
-				cond_resched();
+				cond_resched_stall();
 				state1 = gpiod_get_value_cansleep(data->desc);
 			} while (state != state1);
 
drivers/input/misc/uinput.c +0 -1
index d98212d55108..a6c95916ac7e 100644
@@ -624,7 +624,6 @@ static ssize_t uinput_inject_events(struct uinput_device *udev,
 
 		input_event(udev->dev, ev.type, ev.code, ev.value);
 		bytes += input_event_size();
-		cond_resched();
 	}
 
 	return bytes;
drivers/input/mousedev.c +0 -1
index 505c562a5daa..7ce9ffca6d12 100644
@@ -704,7 +704,6 @@ static ssize_t mousedev_write(struct file *file, const char __user *buffer,
 		mousedev_generate_response(client, c);
 
 		spin_unlock_irq(&client->packet_lock);
-		cond_resched();
 	}
 
 	kill_fasync(&client->fasync, SIGIO, POLL_IN);
drivers/iommu/arm/arm-smmu-v3/arm-smmu-v3.c +0 -2
index bd0a596f9863..8f517a80a831 100644
@@ -1582,8 +1582,6 @@ static irqreturn_t arm_smmu_evtq_thread(int irq, void *dev)
 			for (i = 0; i < ARRAY_SIZE(evt); ++i)
 				dev_info(smmu->dev, "\t0x%016llx\n",
 					 (unsigned long long)evt[i]);
-
-			cond_resched();
 		}
 
 		/*
drivers/media/i2c/vpx3220.c +0 -3
index 1eaae886f217..c673dba9a592 100644
@@ -81,9 +81,6 @@ static int vpx3220_fp_status(struct v4l2_subdev *sd)
 			return 0;
 
 		udelay(10);
-
-		if (need_resched())
-			cond_resched();
 	}
 
 	return -1;
drivers/media/pci/cobalt/cobalt-i2c.c +2 -2
index 10c9ee33f73e..2a11dd49559a 100644
@@ -140,7 +140,7 @@ static int cobalt_tx_bytes(struct cobalt_i2c_regs __iomem *regs,
 		while (status & M00018_SR_BITMAP_TIP_MSK) {
 			if (time_after(jiffies, start_time + adap->timeout))
 				return -ETIMEDOUT;
-			cond_resched();
+			cond_resched_stall();
 			status = ioread8(&regs->cr_sr);
 		}
 
@@ -199,7 +199,7 @@ static int cobalt_rx_bytes(struct cobalt_i2c_regs __iomem *regs,
 		while (status & M00018_SR_BITMAP_TIP_MSK) {
 			if (time_after(jiffies, start_time + adap->timeout))
 				return -ETIMEDOUT;
-			cond_resched();
+			cond_resched_stall();
 			status = ioread8(&regs->cr_sr);
 		}
 
drivers/misc/bcm-vk/bcm_vk_dev.c +1 -2
index d4a96137728d..d262e4c5b4e3 100644
@@ -364,8 +364,7 @@ static inline int bcm_vk_wait(struct bcm_vk *vk, enum pci_barno bar,
 		if (time_after(jiffies, timeout))
 			return -ETIMEDOUT;
 
-		cpu_relax();
-		cond_resched();
+		cond_resched_stall();
 	} while ((rd_val & mask) != value);
 
 	return 0;
drivers/misc/bcm-vk/bcm_vk_msg.c +1 -2
index e17d81231ea6..1b5a71382e76 100644
@@ -1295,8 +1295,7 @@ int bcm_vk_release(struct inode *inode, struct file *p_file)
 			break;
 		}
 		dma_cnt = atomic_read(&ctx->dma_cnt);
-		cpu_relax();
-		cond_resched();
+		cond_resched_stall();
 	} while (dma_cnt);
 	dev_dbg(dev, "Draining for [fd-%d] pid %d - delay %d ms\n",
 		ctx->idx, pid, jiffies_to_msecs(jiffies - start_time));
drivers/misc/genwqe/card_base.c +1 -2
index 224a7e97cbea..03ed8a426d49 100644
@@ -1004,7 +1004,6 @@ static int genwqe_health_thread(void *data)
 		}
 
 		cd->last_gfir = gfir;
-		cond_resched();
 	}
 
 	return 0;
@@ -1041,7 +1040,7 @@ static int genwqe_health_thread(void *data)
 
 	/* genwqe_bus_reset failed(). Now wait for genwqe_remove(). */
 	while (!kthread_should_stop())
-		cond_resched();
+		cond_resched_stall();
 
 	return -EIO;
 }
drivers/misc/genwqe/card_ddcb.c +0 -6
index 500b1feaf1f6..793faf4bdc06 100644
@@ -1207,12 +1207,6 @@ static int genwqe_card_thread(void *data)
 		}
 		if (should_stop)
 			break;
-
-		/*
-		 * Avoid soft lockups on heavy loads; we do not want
-		 * to disable our interrupts.
-		 */
-		cond_resched();
 	}
 	return 0;
 }
drivers/misc/genwqe/card_dev.c +0 -2
index 55fc5b80e649..ec1112dc7d5a 100644
@@ -1322,7 +1322,6 @@ static int genwqe_inform_and_stop_processes(struct genwqe_dev *cd)
 			     genwqe_open_files(cd); i++) {
 			dev_info(&pci_dev->dev, "  %d sec ...", i);
 
-			cond_resched();
 			msleep(1000);
 		}
 
@@ -1340,7 +1339,6 @@ static int genwqe_inform_and_stop_processes(struct genwqe_dev *cd)
 				     genwqe_open_files(cd); i++) {
 				dev_warn(&pci_dev->dev, "  %d sec ...", i);
 
-				cond_resched();
 				msleep(1000);
 			}
 		}
drivers/misc/vmw_balloon.c +0 -4
index 9ce9b9e0e9b6..7cf977e70935 100644
@@ -1158,8 +1158,6 @@ static void vmballoon_inflate(struct vmballoon *b)
 			vmballoon_split_refused_pages(&ctl);
 			ctl.page_size--;
 		}
-
-		cond_resched();
 	}
 
 	/*
@@ -1282,8 +1280,6 @@ static unsigned long vmballoon_deflate(struct vmballoon *b, uint64_t n_frames,
 				break;
 			ctl.page_size++;
 		}
-
-		cond_resched();
 	}
 
 	return deflated_frames;
drivers/mmc/host/mmc_spi.c +0 -3
index cc333ad67cac..e05d99437547 100644
@@ -192,9 +192,6 @@ static int mmc_spi_skip(struct mmc_spi_host *host, unsigned long timeout,
 			if (cp[i] != byte)
 				return cp[i];
 		}
-
-		/* If we need long timeouts, we may release the CPU */
-		cond_resched();
 	} while (time_is_after_jiffies(start + timeout));
 	return -ETIMEDOUT;
 }
drivers/nvdimm/btt.c +0 -2
index d5593b0dc700..5e97555db441 100644
@@ -435,7 +435,6 @@ static int btt_map_init(struct arena_info *arena)
 
 		offset += size;
 		mapsize -= size;
-		cond_resched();
 	}
 
  free:
@@ -479,7 +478,6 @@ static int btt_log_init(struct arena_info *arena)
 
 		offset += size;
 		logsize -= size;
-		cond_resched();
 	}
 
 	for (i = 0; i < arena->nfree; i++) {
drivers/nvme/target/zns.c +0 -2
index 5b5c1e481722..12eee9a87e42 100644
@@ -432,8 +432,6 @@ static u16 nvmet_bdev_zone_mgmt_emulate_all(struct nvmet_req *req)
 				zsa_req_op(req->cmd->zms.zsa) | REQ_SYNC,
 				GFP_KERNEL);
 			bio->bi_iter.bi_sector = sector;
-			/* This may take a while, so be nice to others */
-			cond_resched();
 		}
 		sector += bdev_zone_sectors(bdev);
 	}
drivers/parport/parport_ip32.c +0 -1
index 0919ed99ba94..8c52008bbb7c 100644
@@ -1238,7 +1238,6 @@ static size_t parport_ip32_epp_write_addr(struct parport *p, const void *buf,
 static unsigned int parport_ip32_fifo_wait_break(struct parport *p,
 						 unsigned long expire)
 {
-	cond_resched();
 	if (time_after(jiffies, expire)) {
 		pr_debug1(PPIP32 "%s: FIFO write timed out\n", p->name);
 		return 1;
drivers/parport/parport_pc.c +0 -4
index 1f236aaf7867..a482b5b835ec 100644
@@ -663,8 +663,6 @@ static size_t parport_pc_fifo_write_block_dma(struct parport *port,
 		}
 		/* Is serviceIntr set? */
 		if (!(inb(ECONTROL(port)) & (1<<2))) {
-			cond_resched();
-
 			goto false_alarm;
 		}
 
@@ -674,8 +672,6 @@ static size_t parport_pc_fifo_write_block_dma(struct parport *port,
 		count = get_dma_residue(port->dma);
 		release_dma_lock(dmaflag);
 
-		cond_resched(); /* Can't yield the port. */
-
 		/* Anyone else waiting for the port? */
 		if (port->waithead) {
 			printk(KERN_DEBUG "Somebody wants the port\n");
drivers/pci/pci-sysfs.c +0 -1
index d9eede2dbc0e..e7bb03c3c148 100644
@@ -719,7 +719,6 @@ static ssize_t pci_read_config(struct file *filp, struct kobject *kobj,
 		data[off - init_off + 3] = (val >> 24) & 0xff;
 		off += 4;
 		size -= 4;
-		cond_resched();
 	}
 
 	if (size >= 2) {
drivers/pci/proc.c +0 -1
index f967709082d6..7d3cd2201e64 100644
@@ -83,7 +83,6 @@ static ssize_t proc_bus_pci_read(struct file *file, char __user *buf,
 		buf += 4;
 		pos += 4;
 		cnt -= 4;
-		cond_resched();
 	}
 
 	if (cnt >= 2) {
drivers/platform/x86/intel/speed_select_if/isst_if_mbox_pci.c +2 -2
index df1fc6c719f3..c202ae0d0656 100644
@@ -56,7 +56,7 @@ static int isst_if_mbox_cmd(struct pci_dev *pdev,
 			ret = -EBUSY;
 			tm_delta = ktime_us_delta(ktime_get(), tm);
 			if (tm_delta > OS_MAILBOX_TIMEOUT_AVG_US)
-				cond_resched();
+				cond_resched_stall();
 			continue;
 		}
 		ret = 0;
@@ -95,7 +95,7 @@ static int isst_if_mbox_cmd(struct pci_dev *pdev,
 			ret = -EBUSY;
 			tm_delta = ktime_us_delta(ktime_get(), tm);
 			if (tm_delta > OS_MAILBOX_TIMEOUT_AVG_US)
-				cond_resched();
+				cond_resched_stall();
 			continue;
 		}
 
drivers/s390/cio/css.c +0 -8
index 3ff46fc694f8..6122a4a057fa 100644
@@ -659,11 +659,6 @@ static int slow_eval_known_fn(struct subchannel *sch, void *data)
 		rc = css_evaluate_known_subchannel(sch, 1);
 		if (rc == -EAGAIN)
 			css_schedule_eval(sch->schid);
-		/*
-		 * The loop might take long time for platforms with lots of
-		 * known devices. Allow scheduling here.
-		 */
-		cond_resched();
 	}
 	return 0;
 }
@@ -695,9 +690,6 @@ static int slow_eval_unknown_fn(struct subchannel_id schid, void *data)
 		default:
 			rc = 0;
 		}
-		/* Allow scheduling here since the containing loop might
-		 * take a while.  */
-		cond_resched();
 	}
 	return rc;
 }
drivers/scsi/NCR5380.c +0 -2
index cea3a79d538e..40e66afd77cf 100644
@@ -738,8 +738,6 @@ static void NCR5380_main(struct work_struct *work)
 			maybe_release_dma_irq(instance);
 		}
 		spin_unlock_irq(&hostdata->lock);
-		if (!done)
-			cond_resched();
 	} while (!done);
 }
 
drivers/scsi/megaraid.c +0 -1
index e92f1a73cc9b..675504f8149a 100644
@@ -1696,7 +1696,6 @@ __mega_busywait_mbox (adapter_t *adapter)
 		if (!mbox->m_in.busy)
 			return 0;
 		udelay(100);
-		cond_resched();
 	}
 	return -1;		/* give up after 1 second */
 }
drivers/scsi/qedi/qedi_main.c +0 -1
index cd0180b1f5b9..9e2596199458 100644
@@ -1943,7 +1943,6 @@ static int qedi_percpu_io_thread(void *arg)
 				if (!work->is_solicited)
 					kfree(work);
 			}
-			cond_resched();
 			spin_lock_irqsave(&p->p_work_lock, flags);
 		}
 		set_current_state(TASK_INTERRUPTIBLE);
drivers/scsi/qla2xxx/qla_nx.c +0 -2
index 6dfb70edb9a6..e1a5c2dbe134 100644
@@ -972,7 +972,6 @@ qla82xx_flash_wait_write_finish(struct qla_hw_data *ha)
 		if (ret < 0 || (val & 1) == 0)
 			return ret;
 		udelay(10);
-		cond_resched();
 	}
 	ql_log(ql_log_warn, vha, 0xb00d,
 	       "Timeout reached waiting for write finish.\n");
@@ -1037,7 +1036,6 @@ ql82xx_rom_lock_d(struct qla_hw_data *ha)
 
 	while ((qla82xx_rom_lock(ha) != 0) && (loops < 50000)) {
 		udelay(100);
-		cond_resched();
 		loops++;
 	}
 	if (loops >= 50000) {
drivers/scsi/qla2xxx/qla_sup.c +0 -5
index c092a6b1ced4..40fc521ba89f 100644
@@ -463,7 +463,6 @@ qla24xx_read_flash_dword(struct qla_hw_data *ha, uint32_t addr, uint32_t *data)
 			return QLA_SUCCESS;
 		}
 		udelay(10);
-		cond_resched();
 	}
 
 	ql_log(ql_log_warn, pci_get_drvdata(ha->pdev), 0x7090,
@@ -505,7 +504,6 @@ qla24xx_write_flash_dword(struct qla_hw_data *ha, uint32_t addr, uint32_t data)
 		if (!(rd_reg_dword(&reg->flash_addr) & FARX_DATA_FLAG))
 			return QLA_SUCCESS;
 		udelay(10);
-		cond_resched();
 	}
 
 	ql_log(ql_log_warn, pci_get_drvdata(ha->pdev), 0x7090,
@@ -2151,7 +2149,6 @@ qla2x00_poll_flash(struct qla_hw_data *ha, uint32_t addr, uint8_t poll_data,
 		}
 		udelay(10);
 		barrier();
-		cond_resched();
 	}
 	return status;
 }
@@ -2301,7 +2298,6 @@ qla2x00_read_flash_data(struct qla_hw_data *ha, uint8_t *tmp_buf,
 		if (saddr % 100)
 			udelay(10);
 		*tmp_buf = data;
-		cond_resched();
 	}
 }
 
@@ -2589,7 +2585,6 @@ qla2x00_write_optrom_data(struct scsi_qla_host *vha, void *buf,
 				rval = QLA_FUNCTION_FAILED;
 				break;
 			}
-			cond_resched();
 		}
 	} while (0);
 	qla2x00_flash_disable(ha);
drivers/scsi/qla4xxx/ql4_nx.c +0 -1
index 47adff9f0506..e40a525a2202 100644
@@ -3643,7 +3643,6 @@ qla4_82xx_read_flash_data(struct scsi_qla_host *ha, uint32_t *dwptr,
 	int loops = 0;
 	while ((qla4_82xx_rom_lock(ha) != 0) && (loops < 50000)) {
 		udelay(100);
-		cond_resched();
 		loops++;
 	}
 	if (loops >= 50000) {
drivers/scsi/xen-scsifront.c +1 -1
index 9ec55ddc1204..6f8e0c69f832 100644
@@ -442,7 +442,7 @@ static irqreturn_t scsifront_irq_fn(int irq, void *dev_id)
 
 	while (scsifront_cmd_done(info, &eoiflag))
 		/* Yield point for this unbounded loop. */
-		cond_resched();
+		cond_resched_stall();
 
 	xen_irq_lateeoi(irq, eoiflag);
 
drivers/spi/spi-lantiq-ssc.c +1 -2
index 938e9e577e4f..151b381fc098 100644
@@ -775,8 +775,7 @@ static void lantiq_ssc_bussy_work(struct work_struct *work)
 			spi_finalize_current_transfer(spi->host);
 			return;
 		}
-
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after_eq(jiffies, end));
 
 	if (spi->host->cur_msg)
drivers/spi/spi-meson-spifc.c +1 -1
index 06626f406f68..ff3550ebb22b 100644
@@ -100,7 +100,7 @@ static int meson_spifc_wait_ready(struct meson_spifc *spifc)
 		regmap_read(spifc->regmap, REG_SLAVE, &data);
 		if (data & SLAVE_TRST_DONE)
 			return 0;
-		cond_resched();
+		cond_resched_stall();
 	} while (!time_after(jiffies, deadline));
 
 	return -ETIMEDOUT;
drivers/spi/spi.c +1 -1
index 8d6304cb061e..3ddbfa9babdc 100644
@@ -1808,7 +1808,7 @@ static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
 
 	/* Prod the scheduler in case transfer_one() was busy waiting */
 	if (!ret)
-		cond_resched();
+		cond_resched_stall();
 	return;
 
 out_unlock:
drivers/staging/rtl8723bs/core/rtw_mlme_ext.c +1 -1
index 985683767a40..2a2ebdf12a45 100644
@@ -3775,7 +3775,7 @@ unsigned int send_beacon(struct adapter *padapter)
 		issue_beacon(padapter, 100);
 		issue++;
 		do {
-			cond_resched();
+			cond_resched_stall();
 			rtw_hal_get_hwreg(padapter, HW_VAR_BCN_VALID, (u8 *)(&bxmitok));
 			poll++;
 		} while ((poll%10) != 0 && false == bxmitok && !padapter->bSurpriseRemoved && !padapter->bDriverStopped);
drivers/staging/rtl8723bs/core/rtw_pwrctrl.c +0 -2
index a392d5b4caf2..c263fbc71201 100644
@@ -576,8 +576,6 @@ void LPS_Leave_check(struct adapter *padapter)
 	bReady = false;
 	start_time = jiffies;
 
-	cond_resched();
-
 	while (1) {
 		mutex_lock(&pwrpriv->lock);
 
drivers/tee/optee/ffa_abi.c +0 -1
index 0828240f27e6..49f55c051d71 100644
@@ -581,7 +581,6 @@ static int optee_ffa_yielding_call(struct tee_context *ctx,
 		 * filled in by ffa_mem_ops->sync_send_receive() returning
 		 * above.
 		 */
-		cond_resched();
 		optee_handle_ffa_rpc(ctx, optee, data->data1, rpc_arg);
 		cmd = OPTEE_FFA_YIELDING_CALL_RESUME;
 		data->data0 = cmd;
drivers/tee/optee/smc_abi.c +0 -1
index d5b28fd35d66..86e01454422c 100644
@@ -943,7 +943,6 @@ static int optee_smc_do_call_with_arg(struct tee_context *ctx,
 			 */
 			optee_cq_wait_for_completion(&optee->call_queue, &w);
 		} else if (OPTEE_SMC_RETURN_IS_RPC(res.a0)) {
-			cond_resched();
 			param.a0 = res.a0;
 			param.a1 = res.a1;
 			param.a2 = res.a2;
drivers/tty/hvc/hvc_console.c +2 -4
index 959fae54ca39..11bb4204b78d 100644
@@ -538,7 +538,6 @@ static ssize_t hvc_write(struct tty_struct *tty, const u8 *buf, size_t count)
 		if (count) {
 			if (hp->n_outbuf > 0)
 				hvc_flush(hp);
-			cond_resched();
 		}
 	}
 
@@ -653,7 +652,7 @@ static int __hvc_poll(struct hvc_struct *hp, bool may_sleep)
 
 	if (may_sleep) {
 		spin_unlock_irqrestore(&hp->lock, flags);
-		cond_resched();
+
 		spin_lock_irqsave(&hp->lock, flags);
 	}
 
@@ -725,7 +724,7 @@ static int __hvc_poll(struct hvc_struct *hp, bool may_sleep)
 	if (may_sleep) {
 		/* Keep going until the flip is full */
 		spin_unlock_irqrestore(&hp->lock, flags);
-		cond_resched();
+
 		spin_lock_irqsave(&hp->lock, flags);
 		goto read_again;
 	} else if (read_total < HVC_ATOMIC_READ_MAX) {
@@ -802,7 +801,6 @@ static int khvcd(void *unused)
 			mutex_lock(&hvc_structs_mutex);
 			list_for_each_entry(hp, &hvc_structs, next) {
 				poll_mask |= __hvc_poll(hp, true);
-				cond_resched();
 			}
 			mutex_unlock(&hvc_structs_mutex);
 		} else
drivers/tty/tty_buffer.c +0 -3
index 5f6d0cf67571..c70d695ed69d 100644
@@ -498,9 +498,6 @@ static void flush_to_ldisc(struct work_struct *work)
 			lookahead_bufs(port, head);
 		if (!rcvd)
 			break;
-
-		if (need_resched())
-			cond_resched();
 	}
 
 	mutex_unlock(&buf->lock);
drivers/tty/tty_io.c +0 -1
index 8a94e5a43c6d..0221ff17a4bf 100644
@@ -1032,7 +1032,6 @@ static ssize_t iterate_tty_write(struct tty_ldisc *ld, struct tty_struct *tty,
 		ret = -ERESTARTSYS;
 		if (signal_pending(current))
 			break;
-		cond_resched();
 	}
 	if (written) {
 		tty_update_time(tty, true);
drivers/usb/gadget/udc/max3420_udc.c +0 -1
index 2d57786d3db7..b9051c341b10 100644
@@ -451,7 +451,6 @@ static void __max3420_start(struct max3420_udc *udc)
 		val = spi_rd8(udc, MAX3420_REG_USBIRQ);
 		if (val & OSCOKIRQ)
 			break;
-		cond_resched();
 	}
 
 	/* Enable PULL-UP only when Vbus detected */
drivers/usb/host/max3421-hcd.c +1 -1
index d152d72de126..64f12f5113a2 100644
@@ -1294,7 +1294,7 @@ max3421_reset_hcd(struct usb_hcd *hcd)
 				"timed out waiting for oscillator OK signal");
 			return 1;
 		}
-		cond_resched();
+		cond_resched_stall();
 	}
 
 	/*
drivers/usb/host/xen-hcd.c +1 -1
index 46fdab940092..0b78f371c30a 100644
@@ -1086,7 +1086,7 @@ static irqreturn_t xenhcd_int(int irq, void *dev_id)
 	while (xenhcd_urb_request_done(info, &eoiflag) |
 	       xenhcd_conn_notify(info, &eoiflag))
 		/* Yield point for this unbounded loop. */
-		cond_resched();
+		cond_resched_stall();
 
 	xen_irq_lateeoi(irq, eoiflag);
 	return IRQ_HANDLED;
drivers/vfio/vfio_iommu_spapr_tce.c +0 -2
index a94ec6225d31..523c6685818d 100644
@@ -457,8 +457,6 @@ static int tce_iommu_clear(struct tce_container *container,
 			}
 		}
 
-		cond_resched();
-
 		direction = DMA_NONE;
 		oldhpa = 0;
 		ret = iommu_tce_xchg_no_kill(container->mm, tbl, entry, &oldhpa,
drivers/vfio/vfio_iommu_type1.c +0 -7
index eacd6ec04de5..afc9724051ce 100644
@@ -962,8 +962,6 @@ static long vfio_sync_unpin(struct vfio_dma *dma, struct vfio_domain *domain,
 		kfree(entry);
 	}
 
-	cond_resched();
-
 	return unlocked;
 }
 
@@ -1029,7 +1027,6 @@ static size_t unmap_unpin_slow(struct vfio_domain *domain,
 						     unmapped >> PAGE_SHIFT,
 						     false);
 		*iova += unmapped;
-		cond_resched();
 	}
 	return unmapped;
 }
@@ -1062,7 +1059,6 @@ static long vfio_unmap_unpin(struct vfio_iommu *iommu, struct vfio_dma *dma,
 
 	list_for_each_entry_continue(d, &iommu->domain_list, next) {
 		iommu_unmap(d->domain, dma->iova, dma->size);
-		cond_resched();
 	}
 
 	iommu_iotlb_gather_init(&iotlb_gather);
@@ -1439,8 +1435,6 @@ static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
 				GFP_KERNEL);
 		if (ret)
 			goto unwind;
-
-		cond_resched();
 	}
 
 	return 0;
@@ -1448,7 +1442,6 @@ static int vfio_iommu_map(struct vfio_iommu *iommu, dma_addr_t iova,
 unwind:
 	list_for_each_entry_continue_reverse(d, &iommu->domain_list, next) {
 		iommu_unmap(d->domain, iova, npage << PAGE_SHIFT);
-		cond_resched();
 	}
 
 	return ret;
drivers/vhost/vhost.c +0 -1
index e0c181ad17e3..8939be49c47d 100644
@@ -410,7 +410,6 @@ static bool vhost_worker(void *data)
 			kcov_remote_start_common(worker->kcov_handle);
 			work->fn(work);
 			kcov_remote_stop();
-			cond_resched();
 		}
 	}
 
drivers/video/console/vgacon.c +0 -4
index 7ad047bcae17..e17e7937e11d 100644
@@ -870,12 +870,10 @@ static int vgacon_do_font_op(struct vgastate *state, char *arg, int set,
 		if (set)
 			for (i = 0; i < cmapsz; i++) {
 				vga_writeb(arg[i], charmap + i);
-				cond_resched();
 			}
 		else
 			for (i = 0; i < cmapsz; i++) {
 				arg[i] = vga_readb(charmap + i);
-				cond_resched();
 			}
 
 		/*
@@ -889,12 +887,10 @@ static int vgacon_do_font_op(struct vgastate *state, char *arg, int set,
 			if (set)
 				for (i = 0; i < cmapsz; i++) {
 					vga_writeb(arg[i], charmap + i);
-					cond_resched();
 				}
 			else
 				for (i = 0; i < cmapsz; i++) {
 					arg[i] = vga_readb(charmap + i);
-					cond_resched();
 				}
 		}
 	}
drivers/virtio/virtio_mem.c +0 -8
index fa5226c198cc..c9c66aac49ca 100644
@@ -1754,7 +1754,6 @@ static int virtio_mem_sbm_plug_request(struct virtio_mem *vm, uint64_t diff)
 			rc = virtio_mem_sbm_plug_any_sb(vm, mb_id, &nb_sb);
 			if (rc || !nb_sb)
 				goto out_unlock;
-			cond_resched();
 		}
 	}
 
@@ -1772,7 +1771,6 @@ static int virtio_mem_sbm_plug_request(struct virtio_mem *vm, uint64_t diff)
 		rc = virtio_mem_sbm_plug_and_add_mb(vm, mb_id, &nb_sb);
 		if (rc || !nb_sb)
 			return rc;
-		cond_resched();
 	}
 
 	/* Try to prepare, plug and add new blocks */
@@ -1786,7 +1784,6 @@ static int virtio_mem_sbm_plug_request(struct virtio_mem *vm, uint64_t diff)
 		rc = virtio_mem_sbm_plug_and_add_mb(vm, mb_id, &nb_sb);
 		if (rc)
 			return rc;
-		cond_resched();
 	}
 
 	return 0;
@@ -1869,7 +1866,6 @@ static int virtio_mem_bbm_plug_request(struct virtio_mem *vm, uint64_t diff)
 			nb_bb--;
 		if (rc || !nb_bb)
 			return rc;
-		cond_resched();
 	}
 
 	/* Try to prepare, plug and add new big blocks */
@@ -1885,7 +1881,6 @@ static int virtio_mem_bbm_plug_request(struct virtio_mem *vm, uint64_t diff)
 			nb_bb--;
 		if (rc)
 			return rc;
-		cond_resched();
 	}
 
 	return 0;
@@ -2107,7 +2102,6 @@ static int virtio_mem_sbm_unplug_request(struct virtio_mem *vm, uint64_t diff)
 			if (rc || !nb_sb)
 				goto out_unlock;
 			mutex_unlock(&vm->hotplug_mutex);
-			cond_resched();
 			mutex_lock(&vm->hotplug_mutex);
 		}
 		if (!unplug_online && i == 1) {
@@ -2250,8 +2244,6 @@ static int virtio_mem_bbm_unplug_request(struct virtio_mem *vm, uint64_t diff)
 	 */
 	for (i = 0; i < 3; i++) {
 		virtio_mem_bbm_for_each_bb_rev(vm, bb_id, VIRTIO_MEM_BBM_BB_ADDED) {
-			cond_resched();
-
 			/*
 			 * As we're holding no locks, these checks are racy,
 			 * but we don't care.
Signature · 1 line
2.31.1
maintainer Reviewed-by on v1 85/86
#210 lore raw

Re: [RFC PATCH 85/86] treewide: drivers: remove cond_resched()

Quoted 36 lines · Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

     cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

The cond_resched() calls here are all kinds. Those from set-1 or set-2 are quite straight-forward to handle.

Quoted 7 lines

There are quite a few from set-3, where as noted above, we use cond_resched() as if it were a amulent. Which I supppose it is, in that it wards off softlockup or RCU splats.

Those are now cond_resched_stall(), but in most cases, given that the timeouts are in milliseconds, they could be easily timed waits.

For i2c-mpc.c:

It looks as the code in question could probably be converted to readb_poll_timeout(). If I find sufficient round-tuits I might look at that. Regardless in the context of the tree-wide change ...

#211 lore raw

Re: [RFC PATCH 85/86] treewide: drivers: remove cond_resched()

Quoted 45 lines · Chris Packham
Quoted 36 lines · Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

2. Open coded variants of cond_resched_lock() which call

     cond_resched().

3. Retry or error handling loops, where cond_resched() is used as a quick alternative to spinning in a tight-loop.

When running under a full preemption model, the cond_resched() reduces to a NOP (not even a barrier) so removing it obviously cannot matter.

But considering only voluntary preemption models (for say code that has been mostly tested under those), for set-1 and set-2 the scheduler can now preempt kernel tasks running beyond their time quanta anywhere they are preemptible() [1]. Which removes any need for these explicitly placed scheduling points.

The cond_resched() calls in set-3 are a little more difficult. To start with, given it's NOP character under full preemption, it never actually saved us from a tight loop.
With voluntary preemption, it's not a NOP, but it might as well be -- for most workloads the scheduler does not have an interminable supply of runnable tasks on the runqueue.

So, cond_resched() is useful to not get softlockup splats, but not terribly good for error handling. Ideally, these should be replaced with some kind of timed or event wait.
For now we use cond_resched_stall(), which tries to schedule if possible, and executes a cpu_relax() if not.

The cond_resched() calls here are all kinds. Those from set-1 or set-2 are quite straight-forward to handle.

Quoted 7 lines

There are quite a few from set-3, where as noted above, we use cond_resched() as if it were a amulent. Which I supppose it is, in that it wards off softlockup or RCU splats.

Those are now cond_resched_stall(), but in most cases, given that the timeouts are in milliseconds, they could be easily timed waits.

Quoted 7 lines

For i2c-mpc.c:

It looks as the code in question could probably be converted to readb_poll_timeout(). If I find sufficient round-tuits I might look at that. Regardless in the context of the tree-wide change ...

Thanks Chris. This'll take a while before this lands. I'll see if I can send a patch with cond_resched_stall() or similar separately.

Meanwhile please feel free to make the readb_poll_timeout() change.

--
ankur

maintainer
#212 lore raw

Re: [RFC PATCH 85/86] treewide: drivers: remove cond_resched()

In reply to Ankur Arora

Hi Anhur,

Quoted 4 lines · Ankur Arora

There are broadly three sets of uses of cond_resched():

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

...

What about RCU stalls? The calls to cond_resched() in evdev.c and mousedev.c were added specifically to allow RCU to run in cases when userspace passes a large buffer and the kernel is not fully preemptable.

Thanks.

Signature · 1 line
Dmitry
maintainer
#213 lore raw

Re: [RFC PATCH 85/86] treewide: drivers: remove cond_resched()

Quoted 5 lines · On Thu, 9 Nov 2023 15:25:54 -0800 Dmitry Torokhov <[email protected]>…

Hi Anhur,

Quoted 2 lines · Ankur Arora

There are broadly three sets of uses of cond_resched():

Quoted 9 lines
Quoted 2 lines

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

...

What about RCU stalls? The calls to cond_resched() in evdev.c and mousedev.c were added specifically to allow RCU to run in cases when userspace passes a large buffer and the kernel is not fully preemptable.

First, this patch is being sent out premature as it depends on acceptance of the previous patches.

When the previous patches are finished, then we don't need cond_resched() to protect against RCU stalls, because even "PREEMPT_NONE" will allow preemption inside the kernel.

What the earlier patches do is introduce a concept of NEED_RESCHED_LAZY. Then when the scheduler wants to resched the task, it will set that bit instead of NEED_RESCHED (for the old PREEMPT_NONE version). For VOLUNTARY, it sets the LAZY bit of SCHED_OTHER but NEED_RESCHED for RT/DL tasks. For PREEMPT, it will always set NEED_RESCHED.

NEED_RESCHED will always schedule, but NEED_RESCHED_LAZY only schedules when going to user space.

Now after on tick (depending on HZ it can be 1ms, 3.3ms, 4ms 10ms) if NEED_RESCHED_LAZY is set, then it will set NEED_RESCHED, forcing a preemption at the next available moment (when preempt count is zero).

This will be done even with the old PREEMPT_NONE configuration.

That way we will no longer play whack-a-mole to get rid of all he long running kernel paths by inserting cond_resched() in them.

-- Steve

#214 lore raw

Re: [RFC PATCH 85/86] treewide: drivers: remove cond_resched()

In reply to Dmitry Torokhov
Quoted 5 lines · Dmitry Torokhov

Hi Anhur,

Quoted 2 lines · Ankur Arora

There are broadly three sets of uses of cond_resched():

Quoted 8 lines
Quoted 2 lines

1. Calls to cond_resched() out of the goodness of our heart, otherwise known as avoiding lockup splats.

...

What about RCU stalls? The calls to cond_resched() in evdev.c and mousedev.c were added specifically to allow RCU to run in cases when userspace passes a large buffer and the kernel is not fully preemptable.

Hi Dmitry

The short answer is that even if the kernel isn't fully preemptible, it will always have preempt-count which means that RCU will always know when a read-side critical section gets over.

Long version: cond_resched_rcu() is defined as:

static inline void cond_resched_rcu(void)
{

 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) || !defined(CONFIG_PREEMPT_RCU)
        rcu_read_unlock();
        cond_resched();
        rcu_read_lock();

#endif
}

So the relevant case is PREEMPT_RCU=n.

Now, currently PREEMPT_RCU=n, also implies PREEMPT_COUNT=n. And so the rcu_read_lock()/_unlock() reduce to a barrier. And, that's why we need the explicit cond_resched() there.

The reason we can remove the cond_resched() after patch 43, and 47 is because rcu_read_lock()/_unlock() will modify the preempt count and so RCU will have visibility into when RCU read-side critical sections finish.

That said, this series in this form isn't really going anywhere in the short-term so none of this is imminent.

On the calls to cond_resched(), if the kernel is fully preemptible they are a NOP. And then the code would be polling in a tight loop.

Would it make sense to do something like this instead?

     if (!cond_resched())
        msleep()/usleep()/cpu_relax();

--
ankur

#215 lore raw

RFC PATCH 86/86 sched: remove cond_resched()

In reply to Ankur Arora

Now that we don't have any users of cond_resched() in the tree, we can finally remove it.

Cc Ingo Molnar <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Juri Lelli <[email protected]>
Cc Vincent Guittot <[email protected]>
---
 include/linux/sched.h | 16 ++++------------
 kernel/sched/core.c   | 13 -------------
 2 files changed, 4 insertions(+), 25 deletions(-)
include/linux/sched.h +4 -12
index bae6eed534dd..bbb981c1a142 100644
@@ -2083,19 +2083,11 @@ static inline bool test_tsk_need_resched_any(struct task_struct *tsk)
 }
 
 /*
- * cond_resched() and cond_resched_lock(): latency reduction via
- * explicit rescheduling in places that are safe. The return
- * value indicates whether a reschedule was done in fact.
- * cond_resched_lock() will drop the spinlock before scheduling,
+ * cond_resched_lock(): latency reduction via explicit rescheduling
+ * in places that are safe. The return value indicates whether a
+ * reschedule was done in fact.  cond_resched_lock() will drop the
+ * spinlock before scheduling.
  */
-#ifdef CONFIG_PREEMPTION
-static inline int _cond_resched(void) { return 0; }
-#endif
-
-#define cond_resched() ({			\
-	__might_resched(__FILE__, __LINE__, 0);	\
-	_cond_resched();			\
-})
 
 extern int __cond_resched_lock(spinlock_t *lock);
 extern int __cond_resched_rwlock_read(rwlock_t *lock);
kernel/sched/core.c +0 -13
index 691b50791e04..6940893e3930 100644
@@ -8580,19 +8580,6 @@ SYSCALL_DEFINE0(sched_yield)
 	return 0;
 }
 
-#ifndef CONFIG_PREEMPTION
-int __sched _cond_resched(void)
-{
-	if (should_resched(0)) {
-		preempt_schedule_common();
-		return 1;
-	}
-
-	return 0;
-}
-EXPORT_SYMBOL(_cond_resched);
-#endif
-
 /*
  * __cond_resched_lock() - if a reschedule is pending, drop the given lock
  * (implicitly calling schedule), and reacquire the lock.
Signature · 1 line
2.31.1
maintainer
#216 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

In reply to Ankur Arora
Quoted 48 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

Cc Julia Lawall <[email protected]>
Cc Nicolas Palix <[email protected]>
---
 scripts/coccinelle/api/cond_resched.cocci | 53 +++++++++++++++++++++++
 1 file changed, 53 insertions(+)
 create mode 100644 scripts/coccinelle/api/cond_resched.cocci
scripts/coccinelle/api/cond_resched.cocci new file +16 -0
new file mode 100644
index 000000000000..bf43768a8f8c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/// Remove naked cond_resched() statements
+///
+//# Remove cond_resched() statements when:
+//#   - executing at the same control flow level as the previous or the
+//#     next statement (this lets us avoid complicated conditionals in
+//#     the neighbourhood.)
+//#   - they are of the form "if (need_resched()) cond_resched()" which
+//#     is always safe.
+//#
+//# Coccinelle generally takes care of comments in the immediate neighbourhood
+//# but might need to handle other comments alluding to rescheduling.
+//#
+virtual patch
+virtual context
+

scripts/coccinelle/api/cond_resched.cocci line 26

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+@ r1 @
+identifier r;
+@@
+
+(
+ r = cond_resched();
+|
+-if (need_resched())
+-	cond_resched();
+)

This rule doesn't make sense. The first branch of the disjunction will never match a a place where the second branch matches. Anyway, in the second branch there is no assignment, so I don't see what the first branch is protecting against.

The disjunction is just useless. Whether it is there or or whether only the second brancha is there, doesn't have any impact on the result.

scripts/coccinelle/api/cond_resched.cocci line 35

Quoted 9 lines
scripts/coccinelle/api/cond_resched.cocci new file +9 -0
+
+@ r2 @
+expression E;
+statement S,T;
+@@
+(
+ E;
+|
+ if (E) S

This case is not needed. It will be matched by the next case.

Quoted 5 lines
scripts/coccinelle/api/cond_resched.cocci new file +5 -0
+|
+ if (E) S else T
+|
+)
+-cond_resched();

scripts/coccinelle/api/cond_resched.cocci line 50

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+
+@ r3 @
+expression E;
+statement S,T;
+@@
+-cond_resched();
+(
+ E;
+|
+ if (E) S

As above.

scripts/coccinelle/api/cond_resched.cocci line 39

Quoted 3 lines
scripts/coccinelle/api/cond_resched.cocci new file +3 -0
+|
+ if (E) S else T
+)

I have the impression that you are trying to retain some cond_rescheds. Could you send an example of one that you are trying to keep? Overall, the above rules seem a bit ad hoc. You may be keeping some cases you don't want to, or removing some cases that you want to keep.

Of course, if you are confident that the job is done with this semantic patch as it is, then that's fine too.

julia

#217 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

Quoted 99 lines · Julia Lawall
Quoted 48 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

Cc Julia Lawall <[email protected]>
Cc Nicolas Palix <[email protected]>
---
 scripts/coccinelle/api/cond_resched.cocci | 53 +++++++++++++++++++++++
 1 file changed, 53 insertions(+)
 create mode 100644 scripts/coccinelle/api/cond_resched.cocci
scripts/coccinelle/api/cond_resched.cocci new file +16 -0
new file mode 100644
index 000000000000..bf43768a8f8c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/// Remove naked cond_resched() statements
+///
+//# Remove cond_resched() statements when:
+//#   - executing at the same control flow level as the previous or the
+//#     next statement (this lets us avoid complicated conditionals in
+//#     the neighbourhood.)
+//#   - they are of the form "if (need_resched()) cond_resched()" which
+//#     is always safe.
+//#
+//# Coccinelle generally takes care of comments in the immediate neighbourhood
+//# but might need to handle other comments alluding to rescheduling.
+//#
+virtual patch
+virtual context
+

scripts/coccinelle/api/cond_resched.cocci line 26

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+@ r1 @
+identifier r;
+@@
+
+(
+ r = cond_resched();
+|
+-if (need_resched())
+-	cond_resched();
+)

This rule doesn't make sense. The first branch of the disjunction will never match a a place where the second branch matches. Anyway, in the second branch there is no assignment, so I don't see what the first branch is protecting against.

The disjunction is just useless. Whether it is there or or whether only the second brancha is there, doesn't have any impact on the result.

scripts/coccinelle/api/cond_resched.cocci line 35

Quoted 9 lines
scripts/coccinelle/api/cond_resched.cocci new file +9 -0
+
+@ r2 @
+expression E;
+statement S,T;
+@@
+(
+ E;
+|
+ if (E) S

This case is not needed. It will be matched by the next case.

Quoted 5 lines
scripts/coccinelle/api/cond_resched.cocci new file +5 -0
+|
+ if (E) S else T
+|
+)
+-cond_resched();

scripts/coccinelle/api/cond_resched.cocci line 50

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+
+@ r3 @
+expression E;
+statement S,T;
+@@
+-cond_resched();
+(
+ E;
+|
+ if (E) S

As above.

Quoted 8 lines

scripts/coccinelle/api/cond_resched.cocci line 39

Quoted 3 lines
scripts/coccinelle/api/cond_resched.cocci new file +3 -0
+|
+ if (E) S else T
+)

I have the impression that you are trying to retain some cond_rescheds. Could you send an example of one that you are trying to keep? Overall, the above rules seem a bit ad hoc. You may be keeping some cases you don't want to, or removing some cases that you want to keep.

Right. I was trying to ensure that the script only handled the cases that didn't have any "interesting" connections to the surrounding code.

Just to give you an example of the kind of constructs that I wanted to avoid:

mm/memoy.c::zap_pmd_range():

                if (addr != next)
                        pmd--;
        } while (pmd++, cond_resched(), addr != end);

mm/backing-dev.c::cleanup_offline_cgwbs_workfn()

                while (cleanup_offline_cgwb(wb))
                        cond_resched();


                while (cleanup_offline_cgwb(wb))
                        cond_resched();

But from a quick check the simplest coccinelle script does a much better job than my overly complex (and incorrect) one:

@r1@
@@
- cond_resched();

It avoids the first one. And transforms the second to:

                while (cleanup_offline_cgwb(wb))
                        {}

which is exactly what I wanted.

Quoted 2 lines

Of course, if you are confident that the job is done with this semantic patch as it is, then that's fine too.

Not at all. Thanks for pointing out the mistakes.

--
ankur

maintainer
#218 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

Quoted 139 lines · Ankur Arora
Quoted 99 lines · Julia Lawall
Quoted 48 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

Cc Julia Lawall <[email protected]>
Cc Nicolas Palix <[email protected]>
---
 scripts/coccinelle/api/cond_resched.cocci | 53 +++++++++++++++++++++++
 1 file changed, 53 insertions(+)
 create mode 100644 scripts/coccinelle/api/cond_resched.cocci
scripts/coccinelle/api/cond_resched.cocci new file +16 -0
new file mode 100644
index 000000000000..bf43768a8f8c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/// Remove naked cond_resched() statements
+///
+//# Remove cond_resched() statements when:
+//#   - executing at the same control flow level as the previous or the
+//#     next statement (this lets us avoid complicated conditionals in
+//#     the neighbourhood.)
+//#   - they are of the form "if (need_resched()) cond_resched()" which
+//#     is always safe.
+//#
+//# Coccinelle generally takes care of comments in the immediate neighbourhood
+//# but might need to handle other comments alluding to rescheduling.
+//#
+virtual patch
+virtual context
+

scripts/coccinelle/api/cond_resched.cocci line 26

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+@ r1 @
+identifier r;
+@@
+
+(
+ r = cond_resched();
+|
+-if (need_resched())
+-	cond_resched();
+)

This rule doesn't make sense. The first branch of the disjunction will never match a a place where the second branch matches. Anyway, in the second branch there is no assignment, so I don't see what the first branch is protecting against.

The disjunction is just useless. Whether it is there or or whether only the second brancha is there, doesn't have any impact on the result.

scripts/coccinelle/api/cond_resched.cocci line 35

Quoted 9 lines
scripts/coccinelle/api/cond_resched.cocci new file +9 -0
+
+@ r2 @
+expression E;
+statement S,T;
+@@
+(
+ E;
+|
+ if (E) S

This case is not needed. It will be matched by the next case.

Quoted 5 lines
scripts/coccinelle/api/cond_resched.cocci new file +5 -0
+|
+ if (E) S else T
+|
+)
+-cond_resched();

scripts/coccinelle/api/cond_resched.cocci line 50

Quoted 10 lines
scripts/coccinelle/api/cond_resched.cocci new file +10 -0
+
+@ r3 @
+expression E;
+statement S,T;
+@@
+-cond_resched();
+(
+ E;
+|
+ if (E) S

As above.

Quoted 8 lines

scripts/coccinelle/api/cond_resched.cocci line 39

Quoted 3 lines
scripts/coccinelle/api/cond_resched.cocci new file +3 -0
+|
+ if (E) S else T
+)

I have the impression that you are trying to retain some cond_rescheds. Could you send an example of one that you are trying to keep? Overall, the above rules seem a bit ad hoc. You may be keeping some cases you don't want to, or removing some cases that you want to keep.

Right. I was trying to ensure that the script only handled the cases that didn't have any "interesting" connections to the surrounding code.

Just to give you an example of the kind of constructs that I wanted to avoid:

mm/memoy.c::zap_pmd_range():

                if (addr != next)
                        pmd--;
        } while (pmd++, cond_resched(), addr != end);

mm/backing-dev.c::cleanup_offline_cgwbs_workfn()

                while (cleanup_offline_cgwb(wb))
                        cond_resched();


                while (cleanup_offline_cgwb(wb))
                        cond_resched();

But from a quick check the simplest coccinelle script does a much better job than my overly complex (and incorrect) one:

@r1@
@@
- cond_resched();

Quoted 6 lines

It avoids the first one. And transforms the second to:

                while (cleanup_offline_cgwb(wb))
                        {}

which is exactly what I wanted.

Perfect!

It could be good to run both scripts and compare the results.

julia

Quoted 11 lines
Quoted 3 lines

Of course, if you are confident that the job is done with this semantic patch as it is, then that's fine too.

Not at all. Thanks for pointing out the mistakes.

--
ankur

maintainer
#219 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

In reply to Ankur Arora
Quoted 9 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */
Quoted 8 lines

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

This series looks to get rid of stall warnings for long in-kernel preempt-enabled code paths, which is of course a very good thing. But removing all of the cond_resched() calls can actually increase scheduling latency compared to the current CONFIG_PREEMPT_NONE=y state, correct?

If so, it would be good to take a measured approach. For example, it is clear that a loop that does a cond_resched() every (say) ten jiffies can remove that cond_resched() without penalty, at least in kernels built with either CONFIG_NO_HZ_FULL=n or CONFIG_PREEMPT=y. But this is not so clear for a loop that does a cond_resched() every (say) ten microseconds.

Or am I missing something here?

Thanx, Paul

Quoted 70 lines
Cc Julia Lawall <[email protected]>
Cc Nicolas Palix <[email protected]>
---
 scripts/coccinelle/api/cond_resched.cocci | 53 +++++++++++++++++++++++
 1 file changed, 53 insertions(+)
 create mode 100644 scripts/coccinelle/api/cond_resched.cocci
scripts/coccinelle/api/cond_resched.cocci new file +53 -0
new file mode 100644
index 000000000000..bf43768a8f8c
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/// Remove naked cond_resched() statements
+///
+//# Remove cond_resched() statements when:
+//#   - executing at the same control flow level as the previous or the
+//#     next statement (this lets us avoid complicated conditionals in
+//#     the neighbourhood.)
+//#   - they are of the form "if (need_resched()) cond_resched()" which
+//#     is always safe.
+//#
+//# Coccinelle generally takes care of comments in the immediate neighbourhood
+//# but might need to handle other comments alluding to rescheduling.
+//#
+virtual patch
+virtual context
+
+@ r1 @
+identifier r;
+@@
+
+(
+ r = cond_resched();
+|
+-if (need_resched())
+-	cond_resched();
+)
+
+@ r2 @
+expression E;
+statement S,T;
+@@
+(
+ E;
+|
+ if (E) S
+|
+ if (E) S else T
+|
+)
+-cond_resched();
+
+@ r3 @
+expression E;
+statement S,T;
+@@
+-cond_resched();
+(
+ E;
+|
+ if (E) S
+|
+ if (E) S else T
+)
Signature · 1 line
2.31.1
#220 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

Quoted 19 lines · Paul E. McKenney
Quoted 9 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */
Quoted 8 lines

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

Quoted 5 lines

This series looks to get rid of stall warnings for long in-kernel preempt-enabled code paths, which is of course a very good thing. But removing all of the cond_resched() calls can actually increase scheduling latency compared to the current CONFIG_PREEMPT_NONE=y state, correct?

Not necessarily.

If TIF_NEED_RESCHED_LAZY is set, then we let the current task finish before preempting. If that task runs for arbitrarily long (what Thomas calls the hog problem) -- currently we allow them to run for upto one extra tick (which might shorten/become a tunable.)

If TIF_NEED_RESCHED is set, then it gets folded the same it does now and preemption happens at the next safe preemption point.

So, I guess the scheduling latency would always be bounded but how much latency a task would incur would be scheduler policy dependent.

This is early days, so the policy (or really the rest of it) isn't set in stone but having two levels of preemption -- immediate and deferred -- does seem to give the scheduler greater freedom of policy.

Btw, are you concerned about the scheduling latencies in general or the scheduling latency of a particular set of tasks?

Quoted 5 lines

If so, it would be good to take a measured approach. For example, it is clear that a loop that does a cond_resched() every (say) ten jiffies can remove that cond_resched() without penalty, at least in kernels built with either CONFIG_NO_HZ_FULL=n or CONFIG_PREEMPT=y. But this is not so clear for a loop that does a cond_resched() every (say) ten microseconds.

True. Though both of those loops sound bad :).

Yeah, and as we were discussing offlist, the question is the comparative density of preempt_dec_and_test() is true vs calls to cond_resched().

And if they are similar then we could replace cond_resched() quiescence reporting with ones in preempt_enable() (as you mention elsewhere in the thread.)

Thanks

--
ankur

maintainer
#221 lore raw

Re: [RFC PATCH 57/86] coccinelle: script to remove cond_resched()

Quoted 28 lines · Ankur Arora
Quoted 19 lines · Paul E. McKenney
Quoted 9 lines · Ankur Arora

Rudimentary script to remove the straight-forward subset of cond_resched() and allies:

1) if (need_resched())
cond_resched()

2)  expression*;
    cond_resched();  /* or in the reverse order */
Quoted 8 lines

3) if (expression)

	statement
    cond_resched();  /* or in the reverse order */

The last two patterns depend on the control flow level to ensure that the complex cond_resched() patterns (ex. conditioned ones) are left alone and we only pick up ones which are only minimally related the neighbouring code.

Quoted 5 lines

This series looks to get rid of stall warnings for long in-kernel preempt-enabled code paths, which is of course a very good thing. But removing all of the cond_resched() calls can actually increase scheduling latency compared to the current CONFIG_PREEMPT_NONE=y state, correct?

Quoted 6 lines

Not necessarily.

If TIF_NEED_RESCHED_LAZY is set, then we let the current task finish before preempting. If that task runs for arbitrarily long (what Thomas calls the hog problem) -- currently we allow them to run for upto one extra tick (which might shorten/become a tunable.)

Agreed, and that is the easy case. But getting rid of the cond_resched() calls really can increase scheduling latency of this patchset compared to status-quo mainline.

Quoted 9 lines

If TIF_NEED_RESCHED is set, then it gets folded the same it does now and preemption happens at the next safe preemption point.

So, I guess the scheduling latency would always be bounded but how much latency a task would incur would be scheduler policy dependent.

This is early days, so the policy (or really the rest of it) isn't set in stone but having two levels of preemption -- immediate and deferred -- does seem to give the scheduler greater freedom of policy.

"Give the scheduler freedom!" is a wonderful slogan, but not necessarily a useful one-size-fits-all design principle. The scheduler does not and cannot know everything, after all.

Quoted 2 lines

Btw, are you concerned about the scheduling latencies in general or the scheduling latency of a particular set of tasks?

There are a lot of workloads out there with a lot of objective functions and constraints, but it is safe to say that both will be important, as will other things, depending on the workload.

But you knew that already, right? ;-)

Quoted 7 lines
Quoted 5 lines

If so, it would be good to take a measured approach. For example, it is clear that a loop that does a cond_resched() every (say) ten jiffies can remove that cond_resched() without penalty, at least in kernels built with either CONFIG_NO_HZ_FULL=n or CONFIG_PREEMPT=y. But this is not so clear for a loop that does a cond_resched() every (say) ten microseconds.

True. Though both of those loops sound bad :).

Yes, but do they sound bad enough to be useful in the real world? ;-)

Quoted 6 lines

Yeah, and as we were discussing offlist, the question is the comparative density of preempt_dec_and_test() is true vs calls to cond_resched().

And if they are similar then we could replace cond_resched() quiescence reporting with ones in preempt_enable() (as you mention elsewhere in the thread.)

Here is hoping that something like that can help.

I am quite happy with the thought of reducing the number of cond_resched() invocations, but not at the expense of the Linux kernel failing to do its job.

Thanx, Paul

#222 lore raw
In reply to Ankur Arora

The kernel is not preemptible???? What are you smoking?

Quoted 3 lines · Ankur Arora

In voluntary models, the scheduler's job is to match the demand side of preemption points (a task that needs to be scheduled) with the supply side (a task which calls cond_resched().)

Voluntary preemption models are important for code optimization because the code can rely on the scheduler not changing the cpu we are running on. This allows removing code for preempt_enable/disable to be removed from the code and allows better code generation. The best performing code is generated with defined preemption points when we have a guarantee that the code is not being rescheduled on a different processor. This is f.e. important for consistent access to PER CPU areas.

Quoted 4 lines

To do this add a new flag, TIF_NEED_RESCHED_LAZY which allows the scheduler to mark that a reschedule is needed, but is deferred until the task finishes executing in the kernel -- voluntary preemption as it were.

That is different from the current no preemption model? Seems to be the same.

Quoted 3 lines

There's just one remaining issue: now that explicit preemption points are gone, processes that spread a long time in the kernel have no way to give up the CPU.

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

#223 lore raw
Quoted 1 line · Christoph Lameter

The kernel is not preemptible???? What are you smoking?

The title admittedly is a little tongue in check but the point was that a kernel under a voluntary preemption model isn't preemptible. That's what this series attempts to do. Essentially enable PREEMPT_COUNT and PREEMPTION for all preemption models.

PREEMPT_COUNT is always enabled with PREEMPT_DYNAMIC as well. There the approach is to toggle which preemption points are used dynamically. Here the idea is to not have statically placed preemption points and let the scheduler decide when preemption is warranted.
And the only way to safely do that is by having PREEMPT_COUNT=y.

Quoted 11 lines
Quoted 3 lines

In voluntary models, the scheduler's job is to match the demand side of preemption points (a task that needs to be scheduled) with the supply side (a task which calls cond_resched().)

Voluntary preemption models are important for code optimization because the code can rely on the scheduler not changing the cpu we are running on. This allows removing code for preempt_enable/disable to be removed from the code and allows better code generation. The best performing code is generated with defined preemption points when we have a guarantee that the code is not being rescheduled on a different processor. This is f.e. important for consistent access to PER CPU areas.

Right. This necessitates preempt_enable/preempt_disable() so you get consistent access to the CPU.

This came up in an earlier discussion (See
https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/) and Thomas mentioned that preempt_enable/_disable() overhead was relatively minimal.

Is your point that always-on preempt_count is far too expensive?

Quoted 6 lines
Quoted 4 lines

To do this add a new flag, TIF_NEED_RESCHED_LAZY which allows the scheduler to mark that a reschedule is needed, but is deferred until the task finishes executing in the kernel -- voluntary preemption as it were.

That is different from the current no preemption model? Seems to be the same.

Quoted 8 lines
Quoted 3 lines

There's just one remaining issue: now that explicit preemption points are gone, processes that spread a long time in the kernel have no way to give up the CPU.

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

I'm afraid I don't understand why you would need to change any synchronization primitives. The code that does preempt_enable/_disable() is compiled out because CONFIG_PREEMPT_NONE/_VOLUNTARY don't define CONFIG_PREEMPT_COUNT.

The intent here is to always have CONFIG_PREEMPT_COUNT=y.

--
ankur

#224 lore raw
Quoted 5 lines · Ankur Arora

This came up in an earlier discussion (See
https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/) and Thomas mentioned that preempt_enable/_disable() overhead was relatively minimal.

Is your point that always-on preempt_count is far too expensive?

Yes over the years distros have traditionally delivered their kernels by default without preemption because of these issues. If the overhead has been minimized then that may have changed. Even if so there is still a lot of code being generated that has questionable benefit and just bloats the kernel.

Quoted 9 lines
Quoted 4 lines

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

I'm afraid I don't understand why you would need to change any synchronization primitives. The code that does preempt_enable/_disable() is compiled out because CONFIG_PREEMPT_NONE/_VOLUNTARY don't define CONFIG_PREEMPT_COUNT.

In the trivial cases it is simple like that. But look f.e.
in the slub allocator at the #ifdef CONFIG_PREEMPTION section. There is a overhead added to be able to allow the cpu to change under us. There are likely other examples in the source.

And the whole business of local data access via per cpu areas suffers if we cannot rely on two accesses in a section being able to see consistent values.

Quoted 1 line

The intent here is to always have CONFIG_PREEMPT_COUNT=y.

Just for fun? Code is most efficient if it does not have to consider too many side conditions like suddenly running on a different processor. This introduces needless complexity into the code. It would be better to remove PREEMPT_COUNT for good to just rely on voluntary preemption. We could probably reduce the complexity of the kernel source significantly.

I have never noticed a need to preemption at every instruction in the kernel (if that would be possible at all... Locks etc prevent that ideal scenario frequently). Preemption like that is more like a pipe dream.

High performance kernel solution usually disable overhead like that.

maintainer
#225 lore raw
Quoted 24 lines · On Tue, 7 Nov 2023 20:52:39 -0800 (PST) Christoph Lameter <[email protected]> wrote:
Quoted 5 lines · Ankur Arora

This came up in an earlier discussion (See
https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/) and Thomas mentioned that preempt_enable/_disable() overhead was relatively minimal.

Is your point that always-on preempt_count is far too expensive?

Yes over the years distros have traditionally delivered their kernels by default without preemption because of these issues. If the overhead has been minimized then that may have changed. Even if so there is still a lot of code being generated that has questionable benefit and just bloats the kernel.

Quoted 9 lines
Quoted 4 lines

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

I'm afraid I don't understand why you would need to change any synchronization primitives. The code that does preempt_enable/_disable() is compiled out because CONFIG_PREEMPT_NONE/_VOLUNTARY don't define CONFIG_PREEMPT_COUNT.

Quoted 5 lines

In the trivial cases it is simple like that. But look f.e.
in the slub allocator at the #ifdef CONFIG_PREEMPTION section. There is a overhead added to be able to allow the cpu to change under us. There are likely other examples in the source.

preempt_disable() and preempt_enable() are much lower overhead today than it use to be.

If you are worried about changing CPUs, there's also migrate_disable() too.

Quoted 11 lines

And the whole business of local data
access via per cpu areas suffers if we cannot rely on two accesses in a section being able to see consistent values.

Quoted 1 line

The intent here is to always have CONFIG_PREEMPT_COUNT=y.

Just for fun? Code is most efficient if it does not have to consider too many side conditions like suddenly running on a different processor. This introduces needless complexity into the code. It would be better to remove PREEMPT_COUNT for good to just rely on voluntary preemption. We could probably reduce the complexity of the kernel source significantly.

That is what caused this thread in the first place. Randomly scattered "preemption points" does not scale!

And I'm sorry, we have latency sensitive use cases that require full preemption.

Quoted 8 lines

I have never noticed a need to preemption at every instruction in the kernel (if that would be possible at all... Locks etc prevent that ideal scenario frequently). Preemption like that is more like a pipe dream.

High performance kernel solution usually disable
overhead like that.

Please read the email from Thomas:

https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/

This is not technically getting rid of PREEMPT_NONE. It is adding a new NEED_RESCHED_LAZY flag, that will have the kernel preempt only when entering or in user space. It will behave the same as PREEMPT_NONE, but without the need for all the cond_resched() scattered randomly throughout the kernel.

If the task is in the kernel for more than one tick (1ms at 1000Hz, 4ms at 250Hz and 10ms at 100Hz), it will then set NEED_RESCHED, and you will preempt at the next available location (preempt_count == 0).

But yes, all locations that do not explicitly disable preemption, will now possibly preempt (due to long running kernel threads).

-- Steve

#226 lore raw
Quoted 50 lines · Steven Rostedt
Quoted 24 lines · On Tue, 7 Nov 2023 20:52:39 -0800 (PST) Christoph Lameter <[email protected]> wrote:
Quoted 5 lines · Ankur Arora

This came up in an earlier discussion (See
https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/) and Thomas mentioned that preempt_enable/_disable() overhead was relatively minimal.

Is your point that always-on preempt_count is far too expensive?

Yes over the years distros have traditionally delivered their kernels by default without preemption because of these issues. If the overhead has been minimized then that may have changed. Even if so there is still a lot of code being generated that has questionable benefit and just bloats the kernel.

Quoted 9 lines
Quoted 4 lines

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

I'm afraid I don't understand why you would need to change any synchronization primitives. The code that does preempt_enable/_disable() is compiled out because CONFIG_PREEMPT_NONE/_VOLUNTARY don't define CONFIG_PREEMPT_COUNT.

Quoted 5 lines

In the trivial cases it is simple like that. But look f.e.
in the slub allocator at the #ifdef CONFIG_PREEMPTION section. There is a overhead added to be able to allow the cpu to change under us. There are likely other examples in the source.

preempt_disable() and preempt_enable() are much lower overhead today than it use to be.

If you are worried about changing CPUs, there's also migrate_disable() too.

Quoted 11 lines

And the whole business of local data
access via per cpu areas suffers if we cannot rely on two accesses in a section being able to see consistent values.

Quoted 1 line

The intent here is to always have CONFIG_PREEMPT_COUNT=y.

Just for fun? Code is most efficient if it does not have to consider too many side conditions like suddenly running on a different processor. This introduces needless complexity into the code. It would be better to remove PREEMPT_COUNT for good to just rely on voluntary preemption. We could probably reduce the complexity of the kernel source significantly.

Quoted 10 lines

That is what caused this thread in the first place. Randomly scattered "preemption points" does not scale!

And I'm sorry, we have latency sensitive use cases that require full preemption.

Quoted 4 lines

I have never noticed a need to preemption at every instruction in the kernel (if that would be possible at all... Locks etc prevent that ideal scenario frequently). Preemption like that is more like a pipe dream.

The intent isn't to preempt at every other instruction in the kernel.

As Thomas describes, the idea is that for voluntary preemption kernels resched happens at cond_resched() points which have been distributed heuristically. As a consequence you might get both too little preemption and too much preemption.

The intent is to bring preemption in control of the scheduler which can do a better job than randomly placed cond_resched() points.

Quoted 2 lines
Quoted 2 lines

High performance kernel solution usually disable
overhead like that.

You are also missing all the ways in which voluntary preemption points are responsible for poor performance. For instance, if you look atq clear_huge_page() it does page by page copy with a cond_resched() call after clearing each page.

But if you can expose the full extent to the CPU, it can optimize differently (for the 1GB page it can now elide cacheline allocation):

*Milan* mm/clear_huge_page x86/clear_huge_page change
(GB/s) (GB/s)

  pg-sz=2MB                14.55                 19.29    +32.5%
  pg-sz=1GB                19.34                 49.60   +156.4%

(See https://lore.kernel.org/all/[email protected]/)

Quoted 9 lines

Please read the email from Thomas:

   https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/

This is not technically getting rid of PREEMPT_NONE. It is adding a new NEED_RESCHED_LAZY flag, that will have the kernel preempt only when entering or in user space. It will behave the same as PREEMPT_NONE, but without the need for all the cond_resched() scattered randomly throughout the kernel.

And a corollary of that is that with a scheduler controlled PREEMPT_NONE a task might end up running to completion where earlier it could have been preempted early because it crossed a cond_resched().

Quoted 6 lines

If the task is in the kernel for more than one tick (1ms at 1000Hz, 4ms at 250Hz and 10ms at 100Hz), it will then set NEED_RESCHED, and you will preempt at the next available location (preempt_count == 0).

But yes, all locations that do not explicitly disable preemption, will now possibly preempt (due to long running kernel threads).

--
ankur

#227 lore raw
In reply to Steven Rostedt
Quoted 33 lines · Steven Rostedt
Quoted 24 lines · On Tue, 7 Nov 2023 20:52:39 -0800 (PST) Christoph Lameter <[email protected]> wrote:
Quoted 5 lines · Ankur Arora

This came up in an earlier discussion (See
https://lore.kernel.org/lkml/87cyyfxd4k.ffs@tglx/) and Thomas mentioned that preempt_enable/_disable() overhead was relatively minimal.

Is your point that always-on preempt_count is far too expensive?

Yes over the years distros have traditionally delivered their kernels by default without preemption because of these issues. If the overhead has been minimized then that may have changed. Even if so there is still a lot of code being generated that has questionable benefit and just bloats the kernel.

Quoted 9 lines
Quoted 4 lines

These are needed to avoid adding preempt_enable/disable to a lot of primitives that are used for synchronization. You cannot remove those without changing a lot of synchronization primitives to always have to consider being preempted while operating.

I'm afraid I don't understand why you would need to change any synchronization primitives. The code that does preempt_enable/_disable() is compiled out because CONFIG_PREEMPT_NONE/_VOLUNTARY don't define CONFIG_PREEMPT_COUNT.

Quoted 5 lines

In the trivial cases it is simple like that. But look f.e.
in the slub allocator at the #ifdef CONFIG_PREEMPTION section. There is a overhead added to be able to allow the cpu to change under us. There are likely other examples in the source.

Quoted 4 lines

preempt_disable() and preempt_enable() are much lower overhead today than it use to be.

If you are worried about changing CPUs, there's also migrate_disable() too.

Note that while migrate_disable() would be often sufficient, the implementation of it has actually more overhead (function call, does preempt_disable()/enable() as part of it) than just preempt_disable(). See for example the pcpu_task_pin() definition in mm/page_alloc.c

maintainer
#228 lore raw
In reply to Ankur Arora
Quoted 382 lines · Ankur Arora

Hi,

We have two models of preemption: voluntary and full (and RT which is a fuller form of full preemption.) In this series -- which is based on Thomas' PoC (see [1]), we try to unify the two by letting the scheduler enforce policy for the voluntary preemption models as well.

(Note that this is about preemption when executing in the kernel. Userspace is always preemptible.)

Background
==

Why?: both of these preemption mechanisms are almost entirely disjoint. There are four main sets of preemption points in the kernel:

1. return to user
2. explicit preemption points (cond_resched() and its ilk)
3. return to kernel (tick/IPI/irq at irqexit)
4. end of non-preemptible sections at (preempt_count() == preempt_offset)

Voluntary preemption uses mechanisms 1 and 2. Full preemption uses 1, 3 and 4. In addition both use cond_resched_{rcu,lock,rwlock*} which can be all things to all people because they internally contain 2, and 4.

Now since there's no ideal placement of explicit preemption points, they tend to be randomly spread over code and accumulate over time, as they are are added when latency problems are seen. Plus fear of regressions makes them difficult to remove.
(Presumably, asymptotically they would spead out evenly across the instruction stream!)

In voluntary models, the scheduler's job is to match the demand side of preemption points (a task that needs to be scheduled) with the supply side (a task which calls cond_resched().)

Full preemption models track preemption count so the scheduler can always knows if it is safe to preempt and can drive preemption itself (ex. via dynamic preemption points in 3.)

Design
==

As Thomas outlines in [1], to unify the preemption models we want to: always have the preempt_count enabled and allow the scheduler to drive preemption policy based on the model in effect.

Policies:

- preemption=none: run to completion
- preemption=voluntary: run to completion, unless a task of higher sched-class awaits
- preemption=full: optimized for low-latency. Preempt whenever a higher priority task awaits.

To do this add a new flag, TIF_NEED_RESCHED_LAZY which allows the scheduler to mark that a reschedule is needed, but is deferred until the task finishes executing in the kernel -- voluntary preemption as it were.

The TIF_NEED_RESCHED flag is evaluated at all three of the preemption points. TIF_NEED_RESCHED_LAZY only needs to be evaluated at ret-to-user.

ret-to-user ret-to-kernel preempt_count()

none           Y              N                N
voluntary      Y              Y                Y
full           Y              Y                Y

There's just one remaining issue: now that explicit preemption points are gone, processes that spread a long time in the kernel have no way to give up the CPU.

For full preemption, that is a non-issue as we always use TIF_NEED_RESCHED.

For none/voluntary preemption, we handle that by upgrading to TIF_NEED_RESCHED if a task marked TIF_NEED_RESCHED_LAZY hasn't preempted away by the next tick. (This would cause preemption either at ret-to-kernel, or if the task is in a non-preemptible section, when it exits that section.)

Arguably this provides for much more consistent maximum latency (~2 tick lengths + length of non-preemptible section) as compared to the old model where the maximum latency depended on the dynamic distribution of cond_resched() points.

(As a bonus it handles code that is preemptible but cannot call cond_resched()
completely trivially: ex. long running Xen hypercalls, or this series which started this discussion:
https://lore.kernel.org/all/[email protected]/)

Status
==

What works:
- The system seems to keep ticking over with the normal scheduling policies (SCHED_OTHER). The support for the realtime policies is somewhat more half baked.)
- The basic performance numbers seem pretty close to 6.6-rc7 baseline

What's broken:
- ARCH_NO_PREEMPT (See patch-45 "preempt: ARCH_NO_PREEMPT only preempts lazily")
- Non-x86 architectures. It's trivial to support other archs (only need to add TIF_NEED_RESCHED_LAZY) but wanted to hold off until I got some comments on the series.
(From some testing on arm64, didn't find any surprises.)
- livepatch: livepatch depends on using _cond_resched() to provide low-latency patching. That is obviously difficult with cond_resched() gone. We could get a similar effect by using a static_key in preempt_enable() but at least with inline locks, that might be end up bloating the kernel quite a bit.
- Documentation/ and comments mention cond_resched()
- ftrace support for need-resched-lazy is incomplete

What needs more discussion:
- Should cond_resched_lock() etc be scheduling out for TIF_NEED_RESCHED only or both TIF_NEED_RESCHED_LAZY as well? (See patch 35 "thread_info:
change to tif_need_resched(resched_t)")
- Tracking whether a task in userspace or in the kernel (See patch-40 "context_tracking: add ct_state_cpu()")
- The right model for preempt=voluntary. (See patch 44 "sched: voluntary preemption")

Performance
==

Expectation:

* perf sched bench pipe

preemption full none

6.6-rc7              6.68 +- 0.10   6.69 +- 0.07
+series              6.69 +- 0.12   6.67 +- 0.10

This is rescheduling out of idle which should and does perform identically.

* schbench, preempt=none

* 1 group, 16 threads each

                  6.6-rc7      +series
                  (usecs)      (usecs)
      50.0th:         6            6
      90.0th:         8            7
      99.0th:        11           11
      99.9th:        15           14

* 8 groups, 16 threads each

                 6.6-rc7       +series
                  (usecs)      (usecs)
      50.0th:         6            6
      90.0th:         8            8
      99.0th:        12           11
      99.9th:        20           21

* schbench, preempt=full

* 1 group, 16 threads each

                 6.6-rc7       +series
                 (usecs)       (usecs)
      50.0th:         6            6
      90.0th:         8            7
      99.0th:        11           11
      99.9th:        14           14

* 8 groups, 16 threads each

                 6.6-rc7       +series
                 (usecs)       (usecs)
      50.0th:         7            7
      90.0th:         9            9
      99.0th:        12           12
      99.9th:        21           22

Not much in it either way.

* kernbench, preempt=full

   * half-load (-j 128)

            6.6-rc7                                    +series

   wall        149.2  +-     27.2             wall        132.8  +-     0.4
   utime      8097.1  +-     57.4             utime      8088.5  +-    14.1
   stime      1165.5  +-      9.4             stime      1159.2  +-     1.9
   %cpu       6337.6  +-   1072.8             %cpu       6959.6  +-    22.8
   csw      237618    +-   2190.6             %csw     240343    +-  1386.8


   * optimal-load (-j 1024)

            6.6-rc7                                    +series

   wall        137.8 +-       0.0             wall       137.7  +-       0.8
   utime     11115.0 +-    3306.1             utime    11041.7  +-    3235.0
   stime      1340.0 +-     191.3             stime     1323.1  +-     179.5
   %cpu       8846.3 +-    2830.6             %cpu      9101.3  +-    2346.7
   csw     2099910   +- 2040080.0             csw    2068210    +- 2002450.0


   The preempt=full path should effectively not see any change in
   behaviour. The optimal-loads are pretty much identical.
   For the half-load, however, the +series version does much better but that
   seems to be because of much higher run to run variability in the 6.6-rc7 load.

* kernbench, preempt=none

   * half-load (-j 128)

            6.6-rc7                                    +series

   wall        134.5  +-      4.2             wall        133.6  +-     2.7
   utime      8093.3  +-     39.3             utime      8099.0  +-    38.9
   stime      1175.7  +-     10.6             stime      1169.1  +-     8.4
   %cpu       6893.3  +-    233.2             %cpu       6936.3  +-   142.8
   csw      240723    +-    423.0             %csw     173152    +-  1126.8
                                              

   * optimal-load (-j 1024)

            6.6-rc7                                    +series

   wall        139.2 +-       0.3             wall       138.8  +-       0.2
   utime     11161.0 +-    3360.4             utime    11061.2  +-    3244.9
   stime      1357.6 +-     199.3             stime     1366.6  +-     216.3
   %cpu       9108.8 +-    2431.4             %cpu      9081.0  +-    2351.1
   csw     2078599   +- 2013320.0             csw    1970610    +- 1969030.0


   For both of these the wallclock, utime, stime etc are pretty much
   identical. The one interesting difference is that the number of
   context switches are fewer. This intuitively makes sense given that
   we reschedule threads lazily rather than rescheduling if we encounter
   a cond_resched() and there's a thread wanting to be scheduled.

   The max-load numbers (not posted here) also behave similarly.

Series
==

With that, this is how he series is laid out:

- Patches 01-30: revert the PREEMPT_DYNAMIC code. Most of the infrastructure used by that is via static_calls() and this is a simpler approach which doesn't need any of that (and does away with cond_resched().)

Some of the commits will be resurrected.
089c02ae2771 ("ftrace: Use preemption model accessors for trace header printout") cfe43f478b79 ("preempt/dynamic: Introduce preemption model accessors") 5693fa74f98a ("kcsan: Use preemption model accessors")

- Patches 31-45: contain the scheduler changes to do this. Of these the critical ones are:
patch 35 "thread_info: change to tif_need_resched(resched_t)" patch 41 "sched: handle resched policy in resched_curr()"
patch 43 "sched: enable PREEMPT_COUNT, PREEMPTION for all preemption models" patch 44 "sched: voluntary preemption"
(this needs more work to decide when a higher sched-policy task
should preempt a lower sched-policy task)
patch 45 "preempt: ARCH_NO_PREEMPT only preempts lazily"

- Patches 47-50: contain RCU related changes. RCU now works in both PREEMPT_RCU=y and PREEMPT_RCU=n modes with CONFIG_PREEMPTION. (Until now PREEMPTION=y => PREEMPT_RCU)

- Patches 51-56,86: contain cond_resched() related cleanups. patch 54 "sched: add cond_resched_stall()" adds a new cond_resched() interface. Pitchforks?

- Patches 57-86: remove cond_resched() from the tree.

Also at: github.com/terminus/linux preemption-rfc

Please review.

Thanks
Ankur

[1] https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

Ankur Arora (86):
Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "sched/core: Make sched_dynamic_mutex static" Revert "ftrace: Use preemption model accessors for trace header
printout"
Revert "preempt/dynamic: Introduce preemption model accessors" Revert "kcsan: Use preemption model accessors" Revert "entry: Fix compile error in
dynamic_irqentry_exit_cond_resched()"
Revert "livepatch,sched: Add livepatch task switching to

     cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys" Revert "sched/preempt: Decouple HAVE_PREEMPT_DYNAMIC from
GENERIC_ENTRY"
Revert "sched/preempt: Simplify irqentry_exit_cond_resched() callers" Revert "sched/preempt: Refactor sched_dynamic_update()" Revert "sched/preempt: Move PREEMPT_DYNAMIC logic later" Revert "preempt/dynamic: Fix setup_preempt_mode() return value" Revert "preempt: Restore preemption model selection configs" Revert "sched: Provide Kconfig support for default dynamic preempt
mode"
sched/preempt: remove PREEMPT_DYNAMIC from the build version Revert "preempt/dynamic: Fix typo in macro conditional statement" Revert "sched,preempt: Move preempt_dynamic to debug.c" Revert "static_call: Relax static_call_update() function argument
type"
Revert "sched/core: Use -EINVAL in sched_dynamic_mode()" Revert "sched/core: Stop using magic values in sched_dynamic_mode()" Revert "sched,x86: Allow !PREEMPT_DYNAMIC"
Revert "sched: Harden PREEMPT_DYNAMIC"
Revert "sched: Add /debug/sched_preempt"
Revert "preempt/dynamic: Support dynamic preempt with preempt= boot
option"
Revert "preempt/dynamic: Provide irqentry_exit_cond_resched() static
call"
Revert "preempt/dynamic: Provide preempt_schedule[_notrace]() static
calls"
Revert "preempt/dynamic: Provide cond_resched() and might_resched()
static calls"
Revert "preempt: Introduce CONFIG_PREEMPT_DYNAMIC" x86/thread_info: add TIF_NEED_RESCHED_LAZY
entry: handle TIF_NEED_RESCHED_LAZY
entry/kvm: handle TIF_NEED_RESCHED_LAZY
thread_info: accessors for TIF_NEED_RESCHED*
thread_info: change to tif_need_resched(resched_t)
entry: irqentry_exit only preempts TIF_NEED_RESCHED
sched: make test_*_tsk_thread_flag() return bool
sched: *_tsk_need_resched() now takes resched_t
sched: handle lazy resched in set_nr_*_polling()
context_tracking: add ct_state_cpu()
sched: handle resched policy in resched_curr()
sched: force preemption on tick expiration
sched: enable PREEMPT_COUNT, PREEMPTION for all preemption models
sched: voluntary preemption
preempt: ARCH_NO_PREEMPT only preempts lazily
tracing: handle lazy resched
rcu: select PREEMPT_RCU if PREEMPT
rcu: handle quiescent states for PREEMPT_RCU=n
osnoise: handle quiescent states directly
rcu: TASKS_RCU does not need to depend on PREEMPTION
preempt: disallow !PREEMPT_COUNT or !PREEMPTION
sched: remove CONFIG_PREEMPTION from *_needbreak()
sched: fixup __cond_resched_*()
sched: add cond_resched_stall()
xarray: add cond_resched_xas_rcu() and cond_resched_xas_lock_irq()
xarray: use cond_resched_xas*()
coccinelle: script to remove cond_resched()
treewide: x86: remove cond_resched()
treewide: rcu: remove cond_resched()
treewide: torture: remove cond_resched()
treewide: bpf: remove cond_resched()
treewide: trace: remove cond_resched()
treewide: futex: remove cond_resched()
treewide: printk: remove cond_resched()
treewide: task_work: remove cond_resched()
treewide: kernel: remove cond_resched()
treewide: kernel: remove cond_reshed()
treewide: mm: remove cond_resched()
treewide: io_uring: remove cond_resched()
treewide: ipc: remove cond_resched()
treewide: lib: remove cond_resched()
treewide: crypto: remove cond_resched()
treewide: security: remove cond_resched()
treewide: fs: remove cond_resched()
treewide: virt: remove cond_resched()
treewide: block: remove cond_resched()
treewide: netfilter: remove cond_resched()
treewide: net: remove cond_resched()

Quoted 8 lines

treewide: net: remove cond_resched()
treewide: sound: remove cond_resched()
treewide: md: remove cond_resched()
treewide: mtd: remove cond_resched()
treewide: drm: remove cond_resched()
treewide: net: remove cond_resched()
treewide: drivers: remove cond_resched()
sched: remove cond_resched()

I'm missing the removal of the Xen parts, which were one of the reasons to start this whole work (xen_in_preemptible_hcall etc.).

Juergen

maintainer NAK
#229 lore raw
In reply to Ankur Arora
Quoted 3 lines · Ankur Arora

Hi,

We have two models of preemption: voluntary and full

3, also none (RT is not actually a preemption model).

Quoted 2 lines

(and RT which is
a fuller form of full preemption.)

It is not in fact a different preemption model, it is the same full preemption, the difference with RT is that it makes a lot more stuff preemptible, but the fundamental preemption model is the same -- full.

Quoted 3 lines

In this series -- which is based
on Thomas' PoC (see [1]), we try to unify the two by letting the scheduler enforce policy for the voluntary preemption models as well.

Well, you've also taken out preempt_dynamic for some obscure reason :/

Quoted 35 lines

Please review.

Ankur Arora (86):
Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "sched/core: Make sched_dynamic_mutex static" Revert "ftrace: Use preemption model accessors for trace header
printout"
Revert "preempt/dynamic: Introduce preemption model accessors" Revert "kcsan: Use preemption model accessors"
Revert "entry: Fix compile error in
dynamic_irqentry_exit_cond_resched()"
Revert "livepatch,sched: Add livepatch task switching to

    cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys" Revert "sched/preempt: Decouple HAVE_PREEMPT_DYNAMIC from
GENERIC_ENTRY"
Revert "sched/preempt: Simplify irqentry_exit_cond_resched() callers" Revert "sched/preempt: Refactor sched_dynamic_update()" Revert "sched/preempt: Move PREEMPT_DYNAMIC logic later" Revert "preempt/dynamic: Fix setup_preempt_mode() return value" Revert "preempt: Restore preemption model selection configs" Revert "sched: Provide Kconfig support for default dynamic preempt
mode"
sched/preempt: remove PREEMPT_DYNAMIC from the build version Revert "preempt/dynamic: Fix typo in macro conditional statement" Revert "sched,preempt: Move preempt_dynamic to debug.c" Revert "static_call: Relax static_call_update() function argument
type"
Revert "sched/core: Use -EINVAL in sched_dynamic_mode()" Revert "sched/core: Stop using magic values in sched_dynamic_mode()" Revert "sched,x86: Allow !PREEMPT_DYNAMIC"
Revert "sched: Harden PREEMPT_DYNAMIC"
Revert "sched: Add /debug/sched_preempt"
Revert "preempt/dynamic: Support dynamic preempt with preempt= boot

Quoted 8 lines

option"
Revert "preempt/dynamic: Provide irqentry_exit_cond_resched() static
call"
Revert "preempt/dynamic: Provide preempt_schedule[_notrace]() static
calls"
Revert "preempt/dynamic: Provide cond_resched() and might_resched()
static calls"
Revert "preempt: Introduce CONFIG_PREEMPT_DYNAMIC"

NAK

Even if you were to remove PREEMPT_NONE, which should be a separate series, but that isn't on the table at all afaict, removing preempt_dynamic doesn't make sense.

You still want the preempt= boot time argument and the /debug/sched/preempt things to dynamically switch between the models.

Please, focus on the voluntary thing, gut that and then replace it with the lazy thing, but leave everything else in place.

Re dynamic preempt, gutting the current voluntary preemption model means getting rid of the cond_resched and might_resched toggles but you'll gain a switch to kill the lazy stuff.

#230 lore raw
Quoted 11 lines · Peter Zijlstra
Quoted 3 lines · Ankur Arora

Hi,

We have two models of preemption: voluntary and full

3, also none (RT is not actually a preemption model).

Quoted 2 lines

(and RT which is
a fuller form of full preemption.)

It is not in fact a different preemption model, it is the same full preemption, the difference with RT is that it makes a lot more stuff preemptible, but the fundamental preemption model is the same -- full.

+1

-- Daniel

#231 lore raw
In reply to Peter Zijlstra
Quoted 6 lines · Peter Zijlstra
Quoted 3 lines · Ankur Arora

Hi,

We have two models of preemption: voluntary and full

3, also none (RT is not actually a preemption model).

I think we are just using preemption models differently.

I was trying to distinguish between how preemption happens: thus voluntary (based on voluntary preemption points), and full (based on preemption state.)

Quoted 7 lines
Quoted 2 lines

(and RT which is
a fuller form of full preemption.)

It is not in fact a different preemption model, it is the same full preemption, the difference with RT is that it makes a lot more stuff preemptible, but the fundamental preemption model is the same -- full.

Quoted 5 lines
Quoted 3 lines

In this series -- which is based
on Thomas' PoC (see [1]), we try to unify the two by letting the scheduler enforce policy for the voluntary preemption models as well.

Well, you've also taken out preempt_dynamic for some obscure reason :/

Sorry about that :). I didn't mention it because I was using preemption model in the sense I describe above. And to my mind preempt_dynamic is a clever mechanism that switches between other preemption models.

Quoted 44 lines
Quoted 35 lines

Please review.

Ankur Arora (86):
Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "sched/core: Make sched_dynamic_mutex static" Revert "ftrace: Use preemption model accessors for trace header
printout"
Revert "preempt/dynamic: Introduce preemption model accessors" Revert "kcsan: Use preemption model accessors"
Revert "entry: Fix compile error in
dynamic_irqentry_exit_cond_resched()"
Revert "livepatch,sched: Add livepatch task switching to

    cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys" Revert "sched/preempt: Decouple HAVE_PREEMPT_DYNAMIC from
GENERIC_ENTRY"
Revert "sched/preempt: Simplify irqentry_exit_cond_resched() callers" Revert "sched/preempt: Refactor sched_dynamic_update()" Revert "sched/preempt: Move PREEMPT_DYNAMIC logic later" Revert "preempt/dynamic: Fix setup_preempt_mode() return value" Revert "preempt: Restore preemption model selection configs" Revert "sched: Provide Kconfig support for default dynamic preempt
mode"
sched/preempt: remove PREEMPT_DYNAMIC from the build version Revert "preempt/dynamic: Fix typo in macro conditional statement" Revert "sched,preempt: Move preempt_dynamic to debug.c" Revert "static_call: Relax static_call_update() function argument
type"
Revert "sched/core: Use -EINVAL in sched_dynamic_mode()" Revert "sched/core: Stop using magic values in sched_dynamic_mode()" Revert "sched,x86: Allow !PREEMPT_DYNAMIC"
Revert "sched: Harden PREEMPT_DYNAMIC"
Revert "sched: Add /debug/sched_preempt"
Revert "preempt/dynamic: Support dynamic preempt with preempt= boot

Quoted 8 lines

option"
Revert "preempt/dynamic: Provide irqentry_exit_cond_resched() static
call"
Revert "preempt/dynamic: Provide preempt_schedule[_notrace]() static
calls"
Revert "preempt/dynamic: Provide cond_resched() and might_resched()
static calls"
Revert "preempt: Introduce CONFIG_PREEMPT_DYNAMIC"

Quoted 5 lines

NAK

Even if you were to remove PREEMPT_NONE, which should be a separate series, but that isn't on the table at all afaict, removing preempt_dynamic doesn't make sense.

Agreed. I don't intend to remove PREEMPT_NONE. And, obviously you do want preempt_dynamic like toggling abilities.

Quoted 2 lines

You still want the preempt= boot time argument and the /debug/sched/preempt things to dynamically switch between the models.

Also, yes.

Quoted 6 lines

Please, focus on the voluntary thing, gut that and then replace it with the lazy thing, but leave everything else in place.

Re dynamic preempt, gutting the current voluntary preemption model means getting rid of the cond_resched and might_resched toggles but you'll gain a switch to kill the lazy stuff.

Yes. I think I mostly agree with you.

And, I should have thought this whole revert thing through. Reverting it wasn't really the plan. The plan was to revert these patches temporarily, put in the changes you see in this series, and then pull in the relevant bits of the preempt_dynamic.

Only I decided to push that to later. Sigh.

On your NAK, what about these patches for instance:

Quoted 5 lines
Quoted 5 lines

Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "livepatch,sched: Add livepatch task switching to

    cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys"

What's the best way to handle these? With the lazy bit, cond_resched() and might_resched() are gone. So we don't need all of the static key inftrastructure for toggling etc.

The part of preempt_dynamic that makes sense to me is the one that switches dynamically between none/voluntary/full. Here it would need to be wired onto controls of the lazy bit.
(Right now the preemption policy is controlled by sched_feat in patches 43, and 44 but sched/preempt is a much better interface.)

--
ankur

maintainer
#232 lore raw
Quoted 10 lines · Ankur Arora
Quoted 5 lines
Quoted 5 lines

Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "livepatch,sched: Add livepatch task switching to

    cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys"

What's the best way to handle these? With the lazy bit, cond_resched() and might_resched() are gone. So we don't need all of the static key inftrastructure for toggling etc.

Quoted 5 lines

The part of preempt_dynamic that makes sense to me is the one that switches dynamically between none/voluntary/full. Here it would need to be wired onto controls of the lazy bit.
(Right now the preemption policy is controlled by sched_feat in patches 43, and 44 but sched/preempt is a much better interface.)

I'm not understanding, those should stay obviously.

The current preempt_dynamic stuff has 5 toggles:

/*
* SC:cond_resched
* SC:might_resched
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   cond_resched               <- __cond_resched
 *   might_resched              <- __cond_resched
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * FULL:
 *   cond_resched               <- RET0
 *   might_resched              <- RET0
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched

*/

If you kill voluntary as we know it today, you can remove cond_resched and might_resched, but the remaining 3 are still needed to switch between NONE and FULL.

Additionally, you'll get one new state to enable/disable the LAZY stuff. Neither NONE nor FULL want the LAZY thing on.

You'll then end up with something like:

/*
* SK:preempt_lazy
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   preempt_lazy		<- OFF
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   preempt_lazy		<- ON
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
 *
 * FULL:
 *   preempt_lazy		<- OFF
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched

*/

For the architectures that do not have static_call but instead use static_key for everything, the SC's are obviously static_key based wrappers around the function calls -- like now.

#233 lore raw
Quoted 50 lines · Peter Zijlstra
Quoted 10 lines · Ankur Arora
Quoted 5 lines
Quoted 5 lines

Revert "riscv: support PREEMPT_DYNAMIC with static keys" Revert "livepatch,sched: Add livepatch task switching to

    cond_resched()"

Revert "arm64: Support PREEMPT_DYNAMIC"
Revert "sched/preempt: Add PREEMPT_DYNAMIC using static keys"

What's the best way to handle these? With the lazy bit, cond_resched() and might_resched() are gone. So we don't need all of the static key inftrastructure for toggling etc.

Quoted 5 lines

The part of preempt_dynamic that makes sense to me is the one that switches dynamically between none/voluntary/full. Here it would need to be wired onto controls of the lazy bit.
(Right now the preemption policy is controlled by sched_feat in patches 43, and 44 but sched/preempt is a much better interface.)

I'm not understanding, those should stay obviously.

The current preempt_dynamic stuff has 5 toggles:

/*
* SC:cond_resched
* SC:might_resched
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   cond_resched               <- __cond_resched
 *   might_resched              <- __cond_resched
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * FULL:
 *   cond_resched               <- RET0
 *   might_resched              <- RET0
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
Quoted 5 lines

*/

If you kill voluntary as we know it today, you can remove cond_resched and might_resched, but the remaining 3 are still needed to switch between NONE and FULL.

Ah now I see what you are saying.

Quick thought: even if we were running under NONE, eventually you'll want to forcibly preempt out a CPU hog. So we will need to have at least this one enabled always:

Quoted 1 line

* irqentry_exit_cond_resched <- irqentry_exit_cond_resched

These two, it might make sense to toggle them based on model.

Quoted 2 lines
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace

Anyway let me think about this more and respond tomorrow.

For now, time for bed.

Thanks for clarifying btw.

Ankur

Quoted 34 lines

Additionally, you'll get one new state to enable/disable the LAZY stuff. Neither NONE nor FULL want the LAZY thing on.

You'll then end up with something like:

/*
* SK:preempt_lazy
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   preempt_lazy		<- OFF
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   preempt_lazy		<- ON
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
 *
 * FULL:
 *   preempt_lazy		<- OFF
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched

*/

For the architectures that do not have static_call but instead use static_key for everything, the SC's are obviously static_key based wrappers around the function calls -- like now.

maintainer
#234 lore raw
Quoted 3 lines · Ankur Arora

Ah now I see what you are saying.

Quick thought: even if we were running under NONE, eventually you'll

Well, NONE, you get what you pay for etc..

Quoted 11 lines

want to forcibly preempt out a CPU hog. So we will need to have at least this one enabled always:

Quoted 1 line

* irqentry_exit_cond_resched <- irqentry_exit_cond_resched

These two, it might make sense to toggle them based on model.

Quoted 2 lines
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace

Anyway let me think about this more and respond tomorrow.

That's more or less killing NONE. At that point there's really no point in having it.

I would really suggest you start with transforming VOLUNTARY into the LAZY thing, keep it as simple and narrow as possible.

Once you've got that done, then you can try and argue that NONE makes no sense and try and take it out.

Smaller step etc..

maintainer
#235 lore raw
Quoted 2 lines · Peter Zijlstra

I would really suggest you start with transforming VOLUNTARY into the LAZY thing, keep it as simple and narrow as possible.

Possibly make it worse first, add LAZY as a fourth option, then show it makes VOLUNTARY redundant, kill that.

Quoted 2 lines

Once you've got that done, then you can try and argue that NONE makes no sense and try and take it out.

This also pushes out having to deal with the !PREEMPT archs until the very last moment.

And once you're here, cond_resched() should be an obvious no-op function and you can go delete them.

Anyway, as said, smaller steps more better. Nobody likes 86 patches in their inbox in the morning (or at any time really).

#236 lore raw
In reply to Peter Zijlstra
Quoted 33 lines · Peter Zijlstra

On Wed, Nov 08, 2023 at 02:04:02AM -0800, Ankur Arora wrote:
I'm not understanding, those should stay obviously.

The current preempt_dynamic stuff has 5 toggles:

/*
* SC:cond_resched
* SC:might_resched
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   cond_resched               <- __cond_resched
 *   might_resched              <- __cond_resched
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * FULL:
 *   cond_resched               <- RET0
 *   might_resched              <- RET0
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
Quoted 5 lines

*/

If you kill voluntary as we know it today, you can remove cond_resched and might_resched, but the remaining 3 are still needed to switch between NONE and FULL.

No. The whole point of LAZY is to keep preempt_schedule(), preempt_schedule_notrace(), irqentry_exit_cond_resched() always enabled.

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

The idea is to always enable preempt count and keep _all_ preemption points enabled.

For NONE/VOLUNTARY mode let the scheduler set TIF_NEED_RESCHED_LAZY instead of TIF_NEED_RESCHED. In full mode set TIF_NEED_RESCHED.

Here is where the regular and the lazy flags are evaluated:

Ret2user Ret2kernel PreemptCnt=0 need_resched()

NEED_RESCHED       Y                Y               Y         Y
LAZY_RESCHED       Y                N               N         Y

The trick is that LAZY is not folded into preempt_count so a 1->0 counter transition won't cause preempt_schedule() to be invoked because the topmost bit (NEED_RESCHED) is set.

The scheduler can still decide to set TIF_NEED_RESCHED which will cause an immediate preemption at the next preemption point.

This allows to force out a task which loops, e.g. in a massive copy or clear operation, as it did not reach a point where TIF_NEED_RESCHED_LAZY is evaluated after a time which is defined by the scheduler itself.

For my PoC I did:

1) Set TIF_NEED_RESCHED_LAZY

2) Set TIF_NEED_RESCHED when the task did not react on TIF_NEED_RESCHED_LAZY within a tick

I know that's crude but it just works and obviously requires quite some refinement.

So the way how you switch between preemption modes is to select when the scheduler sets TIF_NEED_RESCHED/TIF_NEED_RESCHED_LAZY. No static call switching at all.

In full preemption mode it sets always TIF_NEED_RESCHED and otherwise it uses the LAZY bit first, grants some time and then gets out the hammer and sets TIF_NEED_RESCHED when the task did not reach a LAZY preemption point.

Which means once the whole thing is in place then the whole PREEMPT_DYNAMIC along with NONE, VOLUNTARY, FULL can go away along with the cond_resched() hackery.

So I think this series is backwards.

It should add the LAZY muck with a Kconfig switch like I did in my PoC _first_. Once that is working and agreed on, the existing muck can be removed.

Thanks,

tglx

maintainer
#237 lore raw
Quoted 2 lines · Thomas Gleixner

No. The whole point of LAZY is to keep preempt_schedule(), preempt_schedule_notrace(), irqentry_exit_cond_resched() always enabled.

Yeah, I got that. What wasn't at all clear is that it also wanted to replace NONE.

0/n didn't even mention none.

maintainer
#238 lore raw
In reply to Thomas Gleixner
Quoted 36 lines · On Wed, 08 Nov 2023 16:38:11 +0100 Thomas Gleixner <[email protected]> wrote:
Quoted 35 lines · Peter Zijlstra

On Wed, Nov 08, 2023 at 02:04:02AM -0800, Ankur Arora wrote:
I'm not understanding, those should stay obviously.

The current preempt_dynamic stuff has 5 toggles:

/*
* SC:cond_resched
* SC:might_resched
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   cond_resched               <- __cond_resched
 *   might_resched              <- __cond_resched
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * FULL:
 *   cond_resched               <- RET0
 *   might_resched              <- RET0
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched

*/

Quoted 6 lines
Quoted 3 lines

If you kill voluntary as we know it today, you can remove cond_resched and might_resched, but the remaining 3 are still needed to switch between NONE and FULL.

No. The whole point of LAZY is to keep preempt_schedule(), preempt_schedule_notrace(), irqentry_exit_cond_resched() always enabled.

Right.

* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP

Peter, how can you say we can get rid of cond_resched() in NONE when you show that NONE still uses it? I thought the entire point of this was to get rid of all the cond_resched() and they are there for PREEMPT_NONE as well as VOLUNTARY. As you showed above, the only difference between NONE and VOLUNTARY was the might_sleep.

Quoted 2 lines

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

And I've been saying that many times already ;-)

Thanks Thomas for reiterating it.

-- Steve

maintainer
#239 lore raw
Quoted 1 line · Steven Rostedt

Peter, how can you say we can get rid of cond_resched() in NONE when you

Because that would fix none to actually be none. Who cares.

Quoted 3 lines
Quoted 1 line

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

And I've been saying that many times already ;-)

Why should I look at random patches on the interweb to make sense of these patches here?

That just underlines these here patches are not making sense.

maintainer
#240 lore raw
Quoted 5 lines · On Wed, 8 Nov 2023 17:49:16 +0100 Peter Zijlstra <[email protected]> wrote:
Quoted 1 line · Steven Rostedt

Peter, how can you say we can get rid of cond_resched() in NONE when you

Because that would fix none to actually be none. Who cares.

Well, that would lead to regressions with PREEMPT_NONE and the watchdog timer.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

And I've been saying that many times already ;-)

Why should I look at random patches on the interweb to make sense of these patches here?

I actually said it to others, this wasn't really supposed to be addressed to you.

Quoted 2 lines

That just underlines these here patches are not making sense.

It's a complex series, and there's a lot of room for improvement. I'm happy to help out here.

-- Steve

#241 lore raw
In reply to Peter Zijlstra
Quoted 6 lines · Peter Zijlstra
Quoted 1 line · Steven Rostedt

Peter, how can you say we can get rid of cond_resched() in NONE when you

Because that would fix none to actually be none. Who cares.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

And I've been saying that many times already ;-)

Why should I look at random patches on the interweb to make sense of these patches here?

That just underlines these here patches are not making sense.

Yeah, I'm changing too many things structural things all together.

Let me redo this. This time limiting the changes to the scheduler adding a preemption model which adds the lazy-bit and which can behave in ways that are similar to preempt=none/full differently by toggling the treatment of lazy-bit.

This keeps the current models as it is.

And, once that makes sense to people, then we can decide how best to remove cond_resched() etc.

--
ankur

#242 lore raw
In reply to Thomas Gleixner
Quoted 92 lines · Thomas Gleixner
Quoted 33 lines · Peter Zijlstra

On Wed, Nov 08, 2023 at 02:04:02AM -0800, Ankur Arora wrote:
I'm not understanding, those should stay obviously.

The current preempt_dynamic stuff has 5 toggles:

/*
* SC:cond_resched
* SC:might_resched
* SC:preempt_schedule
* SC:preempt_schedule_notrace
* SC:irqentry_exit_cond_resched
*
*
* NONE:

 *   cond_resched               <- __cond_resched
 *   might_resched              <- RET0
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * VOLUNTARY:
 *   cond_resched               <- __cond_resched
 *   might_resched              <- __cond_resched
 *   preempt_schedule           <- NOP
 *   preempt_schedule_notrace   <- NOP
 *   irqentry_exit_cond_resched <- NOP
 *
 * FULL:
 *   cond_resched               <- RET0
 *   might_resched              <- RET0
 *   preempt_schedule           <- preempt_schedule
 *   preempt_schedule_notrace   <- preempt_schedule_notrace
 *   irqentry_exit_cond_resched <- irqentry_exit_cond_resched
Quoted 5 lines

*/

If you kill voluntary as we know it today, you can remove cond_resched and might_resched, but the remaining 3 are still needed to switch between NONE and FULL.

No. The whole point of LAZY is to keep preempt_schedule(), preempt_schedule_notrace(), irqentry_exit_cond_resched() always enabled.

Look at my PoC: https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/

The idea is to always enable preempt count and keep _all_ preemption points enabled.

For NONE/VOLUNTARY mode let the scheduler set TIF_NEED_RESCHED_LAZY instead of TIF_NEED_RESCHED. In full mode set TIF_NEED_RESCHED.

Here is where the regular and the lazy flags are evaluated:

Ret2user Ret2kernel PreemptCnt=0 need_resched()

NEED_RESCHED       Y                Y               Y         Y
LAZY_RESCHED       Y                N               N         Y

The trick is that LAZY is not folded into preempt_count so a 1->0 counter transition won't cause preempt_schedule() to be invoked because the topmost bit (NEED_RESCHED) is set.

The scheduler can still decide to set TIF_NEED_RESCHED which will cause an immediate preemption at the next preemption point.

This allows to force out a task which loops, e.g. in a massive copy or clear operation, as it did not reach a point where TIF_NEED_RESCHED_LAZY is evaluated after a time which is defined by the scheduler itself.

For my PoC I did:

1) Set TIF_NEED_RESCHED_LAZY

2) Set TIF_NEED_RESCHED when the task did not react on TIF_NEED_RESCHED_LAZY within a tick

I know that's crude but it just works and obviously requires quite some refinement.

So the way how you switch between preemption modes is to select when the scheduler sets TIF_NEED_RESCHED/TIF_NEED_RESCHED_LAZY. No static call switching at all.

In full preemption mode it sets always TIF_NEED_RESCHED and otherwise it uses the LAZY bit first, grants some time and then gets out the hammer and sets TIF_NEED_RESCHED when the task did not reach a LAZY preemption point.

Which means once the whole thing is in place then the whole PREEMPT_DYNAMIC along with NONE, VOLUNTARY, FULL can go away along with the cond_resched() hackery.

Quoted 5 lines

So I think this series is backwards.

It should add the LAZY muck with a Kconfig switch like I did in my PoC _first_. Once that is working and agreed on, the existing muck can be removed.

Yeah. I should have done it in the order in your PoC. Right now I'm doing all of the stuff you describe above, but because there are far too many structural changes, it's not clear to anybody what the code is doing.

Okay, so for the next version let me limit the series to just the scheduler changes which can be orthogonal to the old models (basically a new scheduler model PREEMPT_AUTO).

Once that is agreed on, the other models can be removed (or expressed in terms of PREEMPT_AUTO.)

--
ankur

#243 lore raw
In reply to Ankur Arora

From: Ankur Arora

Quoted 1 line

Sent: 07 November 2023 21:57

...

Quoted 7 lines

There are four main sets of preemption points in the kernel:

1. return to user
2. explicit preemption points (cond_resched() and its ilk)
3. return to kernel (tick/IPI/irq at irqexit)
4. end of non-preemptible sections at (preempt_count() == preempt_offset)

...

Quoted 7 lines

Policies:

A - preemption=none: run to completion
B - preemption=voluntary: run to completion, unless a task of higher
sched-class awaits
C - preemption=full: optimized for low-latency. Preempt whenever a higher
priority task awaits.

If you remove cond_resched() then won't both B and C require an extra IPI. That is probably OK for RT tasks but could get expensive for normal tasks that aren't bound to a specific cpu.

I suspect C could also lead to tasks being pre-empted just before they sleep (eg after waking another task).
There might already be mitigation for that, I'm not sure if a voluntary sleep can be done in a non-pre-emptible section.

Certainly it should all help the scheduling of RT tasks - which can currently get delayed by a non-RT task in a slow kernel path. Although the worst one is the softint code...

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)

maintainer
#244 lore raw
Quoted 11 lines · On Wed, 8 Nov 2023 09:43:10 +0000 David Laight <[email protected]> wrote:
Quoted 7 lines

Policies:

A - preemption=none: run to completion
B - preemption=voluntary: run to completion, unless a task of higher
sched-class awaits
C - preemption=full: optimized for low-latency. Preempt whenever a higher
priority task awaits.

If you remove cond_resched() then won't both B and C require an extra IPI. That is probably OK for RT tasks but could get expensive for normal tasks that aren't bound to a specific cpu.

What IPI is extra?

Quoted 5 lines

I suspect C could also lead to tasks being pre-empted just before they sleep (eg after waking another task).
There might already be mitigation for that, I'm not sure if a voluntary sleep can be done in a non-pre-emptible section.

No, voluntary sleep can not be done in a preemptible section.

-- Steve

#245 lore raw

From: Steven Rostedt

Quoted 13 lines

Sent: 08 November 2023 15:16

Quoted 8 lines · On Wed, 8 Nov 2023 09:43:10 +0000 David Laight <[email protected]> wrote:
Quoted 7 lines

Policies:

A - preemption=none: run to completion
B - preemption=voluntary: run to completion, unless a task of higher
sched-class awaits
C - preemption=full: optimized for low-latency. Preempt whenever a higher
priority task awaits.

Quoted 5 lines
Quoted 3 lines

If you remove cond_resched() then won't both B and C require an extra IPI. That is probably OK for RT tasks but could get expensive for normal tasks that aren't bound to a specific cpu.

What IPI is extra?

I was thinking that you wouldn't currently need an IPI if the target cpu was running in-kernel because nothing would happen until cond_resched() was called.

Quoted 6 lines
Quoted 4 lines

I suspect C could also lead to tasks being pre-empted just before they sleep (eg after waking another task).
There might already be mitigation for that, I'm not sure if a voluntary sleep can be done in a non-pre-emptible section.

No, voluntary sleep can not be done in a preemptible section.

I'm guessing you missed out a negation in that (or s/not/only/).

I was thinking about sequences like:

	wake_up();
	...
	set_current_state(TASK_UNINTERRUPTIBLE)
	add_wait_queue();
	spin_unlock();
	schedule();

Where you really don't want to be pre-empted by the woken up task. For non CONFIG_RT the lock might do it - if held long enough. Otherwise you'll need to have pre-emption disabled and enable it just after the set_current_state().
And then quite likely disable again after the schedule() to balance things out.

So having the scheduler save the pre-empt disable count might be useful.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)

reviewer
#246 lore raw
In reply to Ankur Arora
Quoted 7 lines · Ankur Arora

What's broken:
- ARCH_NO_PREEMPT (See patch-45 "preempt: ARCH_NO_PREEMPT only preempts lazily")
- Non-x86 architectures. It's trivial to support other archs (only need to add TIF_NEED_RESCHED_LAZY) but wanted to hold off until I got some comments on the series.
(From some testing on arm64, didn't find any surprises.)

When you say "testing on arm64, didn't find any surprises", I assume you mean with an additional patch adding TIF_NEED_RESCHED_LAZY?

Applying this series as-is atop v6.6-rc7 and building defconfig (with GCC 13.2.0) blows up with:

| In file included from ./arch/arm64/include/asm/preempt.h:5,
|                  from ./include/linux/preempt.h:79,
|                  from ./include/linux/spinlock.h:56,
|                  from ./include/linux/mmzone.h:8,
|                  from ./include/linux/gfp.h:7,
|                  from ./include/linux/slab.h:16,
|                  from ./include/linux/resource_ext.h:11,
|                  from ./include/linux/acpi.h:13,
|                  from ./include/acpi/apei.h:9,
|                  from ./include/acpi/ghes.h:5,
|                  from ./include/linux/arm_sdei.h:8,
|                  from arch/arm64/kernel/asm-offsets.c:10:
| ./include/linux/thread_info.h:63:2: error: #error "Arch needs to define TIF_NEED_RESCHED_LAZY"
|    63 | #error "Arch needs to define TIF_NEED_RESCHED_LAZY"
|       |  ^~~~~
| ./include/linux/thread_info.h:66:42: error: 'TIF_NEED_RESCHED_LAZY' undeclared here (not in a function); did you mean 'TIF_NEED_RESCHED'?
|    66 | #define TIF_NEED_RESCHED_LAZY_OFFSET    (TIF_NEED_RESCHED_LAZY - TIF_NEED_RESCHED)
|       |                                          ^~~~~~~~~~~~~~~~~~~~~
| ./include/linux/thread_info.h:70:24: note: in expansion of macro 'TIF_NEED_RESCHED_LAZY_OFFSET'
|    70 |         RESCHED_lazy = TIF_NEED_RESCHED_LAZY_OFFSET,
|       |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
| make[2]: *** [scripts/Makefile.build:116: arch/arm64/kernel/asm-offsets.s] Error 1
| make[1]: *** [/home/mark/src/linux/Makefile:1202: prepare0] Error 2
| make: *** [Makefile:234: __sub-make] Error 2

Note that since arm64 doesn't use the generic entry code, that also requires changes to arm64_preempt_schedule_irq() in arch/arm64/kernel/entry-common.c, to handle TIF_NEED_RESCHED_LAZY.

Quoted 1 line

- ftrace support for need-resched-lazy is incomplete

What exactly do we need for ftrace here?

Thanks,
Mark.

#247 lore raw
Quoted 11 lines · Mark Rutland
Quoted 7 lines · Ankur Arora

What's broken:
- ARCH_NO_PREEMPT (See patch-45 "preempt: ARCH_NO_PREEMPT only preempts lazily")
- Non-x86 architectures. It's trivial to support other archs (only need to add TIF_NEED_RESCHED_LAZY) but wanted to hold off until I got some comments on the series.
(From some testing on arm64, didn't find any surprises.)

When you say "testing on arm64, didn't find any surprises", I assume you mean with an additional patch adding TIF_NEED_RESCHED_LAZY?

Yeah. And, handling that in the user exit path.

Quoted 3 lines

Note that since arm64 doesn't use the generic entry code, that also requires changes to arm64_preempt_schedule_irq() in arch/arm64/kernel/entry-common.c, to handle TIF_NEED_RESCHED_LAZY.

So, the intent (which got muddied due to this overly large series) was to delay handling TIF_NEED_RESCHED_LAZY until we are about to return to user.

I think arm64_preempt_schedule_irq() should only handle TIF_NEED_RESCHED and the _TIF_NEED_RESCHED_LAZY should be handled via _TIF_WORK_MASK and do_notify_resume().

(The design is much clearer in Thomas' PoC:
https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/)

Quoted 3 lines
Quoted 1 line

- ftrace support for need-resched-lazy is incomplete

What exactly do we need for ftrace here?

Only support for TIF_NEED_RESCHED_LAZY which should be complete. That comment was based on a misreading of the code.

Thanks

--
ankur

reviewer
#248 lore raw
Quoted 16 lines · Ankur Arora
Quoted 11 lines · Mark Rutland
Quoted 7 lines · Ankur Arora

What's broken:
- ARCH_NO_PREEMPT (See patch-45 "preempt: ARCH_NO_PREEMPT only preempts lazily")
- Non-x86 architectures. It's trivial to support other archs (only need to add TIF_NEED_RESCHED_LAZY) but wanted to hold off until I got some comments on the series.
(From some testing on arm64, didn't find any surprises.)

When you say "testing on arm64, didn't find any surprises", I assume you mean with an additional patch adding TIF_NEED_RESCHED_LAZY?

Yeah. And, handling that in the user exit path.

Quoted 7 lines
Quoted 3 lines

Note that since arm64 doesn't use the generic entry code, that also requires changes to arm64_preempt_schedule_irq() in arch/arm64/kernel/entry-common.c, to handle TIF_NEED_RESCHED_LAZY.

So, the intent (which got muddied due to this overly large series) was to delay handling TIF_NEED_RESCHED_LAZY until we are about to return to user.

Ah, I missed that detail -- thanks for clarifying!

Quoted 3 lines

I think arm64_preempt_schedule_irq() should only handle TIF_NEED_RESCHED and the _TIF_NEED_RESCHED_LAZY should be handled via _TIF_WORK_MASK and do_notify_resume().

Digging a bit more, I think that should still work.

One slight clarification: arm64_preempt_schedule_irq() doesn't look at TIF_NEED_RESCHED today, as it relies on the scheduler IPI calling preempt_fold_need_resched() to propogate TIF_NEED_RESCHED into PREEMPT_NEED_RESCHED. That should still work since this series makes preempt_fold_need_resched() check tif_need_resched(RESCHED_eager).

I was a bit cnofused because in the generic entry code, irqentry_exit_cond_resched() explicitly checks for TIF_NEED_RESCHED, and I'm not sure why it does that rather than relying on the scheduler IPI as above.

Quoted 9 lines

(The design is much clearer in Thomas' PoC:
https://lore.kernel.org/lkml/87jzshhexi.ffs@tglx/)

Quoted 3 lines
Quoted 1 line

- ftrace support for need-resched-lazy is incomplete

What exactly do we need for ftrace here?

Only support for TIF_NEED_RESCHED_LAZY which should be complete. That comment was based on a misreading of the code.

Cool; thanks!

Mark.

#249 lore raw
Quoted 39 lines · Mark Rutland
Quoted 16 lines · Ankur Arora
Quoted 11 lines · Mark Rutland
Quoted 7 lines · Ankur Arora

What's broken:
- ARCH_NO_PREEMPT (See patch-45 "preempt: ARCH_NO_PREEMPT only preempts lazily")
- Non-x86 architectures. It's trivial to support other archs (only need to add TIF_NEED_RESCHED_LAZY) but wanted to hold off until I got some comments on the series.
(From some testing on arm64, didn't find any surprises.)

When you say "testing on arm64, didn't find any surprises", I assume you mean with an additional patch adding TIF_NEED_RESCHED_LAZY?

Yeah. And, handling that in the user exit path.

Quoted 7 lines
Quoted 3 lines

Note that since arm64 doesn't use the generic entry code, that also requires changes to arm64_preempt_schedule_irq() in arch/arm64/kernel/entry-common.c, to handle TIF_NEED_RESCHED_LAZY.

So, the intent (which got muddied due to this overly large series) was to delay handling TIF_NEED_RESCHED_LAZY until we are about to return to user.

Ah, I missed that detail -- thanks for clarifying!

Quoted 3 lines

I think arm64_preempt_schedule_irq() should only handle TIF_NEED_RESCHED and the _TIF_NEED_RESCHED_LAZY should be handled via _TIF_WORK_MASK and do_notify_resume().

Digging a bit more, I think that should still work.

One slight clarification: arm64_preempt_schedule_irq() doesn't look at TIF_NEED_RESCHED today, as it relies on the scheduler IPI calling preempt_fold_need_resched() to propogate TIF_NEED_RESCHED into PREEMPT_NEED_RESCHED. That should still work since this series makes preempt_fold_need_resched() check tif_need_resched(RESCHED_eager).

Quoted 3 lines

I was a bit cnofused because in the generic entry code, irqentry_exit_cond_resched() explicitly checks for TIF_NEED_RESCHED, and I'm not sure why it does that rather than relying on the scheduler IPI as above.

Yeah I found that confusing as well. I suspect the reason is that not all archs do the folding and we need the explicit check for those that don't.

--
ankur