linux-mips.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v2 0/3] convert tree to get_random_u32_{below,above,between}()
@ 2022-11-14 16:45 Jason A. Donenfeld
  2022-11-14 16:45 ` [PATCH v2 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
                   ` (3 more replies)
  0 siblings, 4 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-14 16:45 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

Hey everyone,

[Changes v1->v2: Jakub asked me to send a v2 around now in the current
 cycle to minimize potential conflicts with the net tree. So this is
 rebased and stripped down to just the treewide parts. As well, the
 removal function is deferred until the end of 6.2 in a separate pull so
 that we don't have merge issues.]

This series is the second tranche of tree-wide conversions to get random
integer handling a bit tamer. It's another Coccinelle-based patchset.

First we s/prandom_u32_max/get_random_u32_below/, since the former is
just a deprecated alias for the latter. Then later, we can remove
prandom_u32_max all together. I'm quite happy about finally being able
to do that. It means that prandom.h is now only for deterministic and
repeatable randomness, not non-deterministic/cryptographic randomness.
That line is no longer blurred.

In order to clean up a bunch of inefficient patterns, we use two simple
helper functions built on top of get_random_u32_below:
get_random_u32_above and get_random_u32_between. The next two patches
convert some gnarly open-coded number juggling to use these helpers.

I've used Coccinelle for these three treewide patches, so hopefully
review is rather uneventful. I didn't accept all of the changes that
Coccinelle proposed, though, as these tend to be somewhat
context-specific. I erred on the side of just going with the most
obvious cases, at least this time through. And then we can address more
complicated cases through actual maintainer trees.

Since get_random_u32_below() and others sits in my random.git tree,
these patches too will flow through that same tree.

Regards,
Jason

Cc: Kees Cook <keescook@chromium.org>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Jakub Kicinski <kuba@kernel.org>
Cc: Russell King <linux@armlinux.org.uk>
Cc: Catalin Marinas <catalin.marinas@arm.com>
Cc: Thomas Bogendoerfer <tsbogend@alpha.franken.de>
Cc: Heiko Carstens <hca@linux.ibm.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Cc: Christoph Böhmwalder <christoph.boehmwalder@linbit.com>
Cc: Jani Nikula <jani.nikula@linux.intel.com>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Sakari Ailus <sakari.ailus@linux.intel.com>
Cc: Martin K. Petersen <martin.petersen@oracle.com>
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Andreas Dilger <adilger.kernel@dilger.ca>
Cc: Jaegeuk Kim <jaegeuk@kernel.org>
Cc: Richard Weinberger <richard@nod.at>
Cc: Darrick J. Wong <djwong@kernel.org>
Cc: SeongJae Park <sj@kernel.org>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Helge Deller <deller@gmx.de>
Cc: netdev@vger.kernel.org
Cc: linux-crypto@vger.kernel.org
Cc: linux-block@vger.kernel.org
Cc: linux-fsdevel@vger.kernel.org
Cc: linux-media@vger.kernel.org
Cc: linux-arm-kernel@lists.infradead.org
Cc: loongarch@lists.linux.dev
Cc: linux-mips@vger.kernel.org
Cc: linuxppc-dev@lists.ozlabs.org
Cc: linux-mmc@vger.kernel.org
Cc: linux-parisc@vger.kernel.org

Jason A. Donenfeld (3):
  treewide: use get_random_u32_below() instead of deprecated function
  treewide: use get_random_u32_{above,below}() instead of manual loop
  treewide: use get_random_u32_between() when possible

 arch/arm/kernel/process.c                     |  2 +-
 arch/arm64/kernel/process.c                   |  2 +-
 arch/loongarch/kernel/process.c               |  2 +-
 arch/loongarch/kernel/vdso.c                  |  2 +-
 arch/mips/kernel/process.c                    |  2 +-
 arch/mips/kernel/vdso.c                       |  2 +-
 arch/parisc/kernel/vdso.c                     |  2 +-
 arch/powerpc/crypto/crc-vpmsum_test.c         |  4 +-
 arch/powerpc/kernel/process.c                 |  2 +-
 arch/s390/kernel/process.c                    |  2 +-
 arch/s390/kernel/vdso.c                       |  2 +-
 arch/sparc/vdso/vma.c                         |  2 +-
 arch/um/kernel/process.c                      |  2 +-
 arch/x86/entry/vdso/vma.c                     |  2 +-
 arch/x86/kernel/module.c                      |  2 +-
 arch/x86/kernel/process.c                     |  2 +-
 arch/x86/mm/pat/cpa-test.c                    |  4 +-
 crypto/rsa-pkcs1pad.c                         |  2 +-
 crypto/testmgr.c                              | 86 +++++++++----------
 drivers/block/drbd/drbd_receiver.c            |  4 +-
 drivers/bus/mhi/host/internal.h               |  2 +-
 drivers/dma-buf/st-dma-fence-chain.c          |  6 +-
 .../gpu/drm/i915/gem/i915_gem_execbuffer.c    |  2 +-
 .../drm/i915/gt/intel_execlists_submission.c  |  2 +-
 drivers/gpu/drm/i915/intel_memory_region.c    |  4 +-
 drivers/infiniband/core/cma.c                 |  2 +-
 drivers/infiniband/hw/cxgb4/id_table.c        |  4 +-
 drivers/infiniband/hw/hns/hns_roce_ah.c       |  5 +-
 drivers/infiniband/ulp/rtrs/rtrs-clt.c        |  2 +-
 drivers/md/bcache/request.c                   |  2 +-
 drivers/media/common/v4l2-tpg/v4l2-tpg-core.c |  8 +-
 .../media/test-drivers/vidtv/vidtv_demod.c    |  8 +-
 .../test-drivers/vivid/vivid-kthread-cap.c    |  2 +-
 .../test-drivers/vivid/vivid-kthread-out.c    |  2 +-
 .../media/test-drivers/vivid/vivid-radio-rx.c |  4 +-
 .../media/test-drivers/vivid/vivid-sdr-cap.c  |  2 +-
 .../test-drivers/vivid/vivid-touch-cap.c      |  2 +-
 drivers/mmc/core/core.c                       |  4 +-
 drivers/mmc/host/dw_mmc.c                     |  2 +-
 drivers/mtd/nand/raw/nandsim.c                |  4 +-
 drivers/mtd/tests/mtd_nandecctest.c           | 10 +--
 drivers/mtd/tests/stresstest.c                |  8 +-
 drivers/mtd/ubi/debug.c                       |  2 +-
 drivers/mtd/ubi/debug.h                       |  6 +-
 drivers/net/ethernet/broadcom/cnic.c          |  2 +-
 .../chelsio/inline_crypto/chtls/chtls_io.c    |  4 +-
 drivers/net/phy/at803x.c                      |  2 +-
 drivers/net/team/team_mode_random.c           |  2 +-
 drivers/net/wireguard/selftest/allowedips.c   | 20 ++---
 drivers/net/wireguard/timers.c                |  4 +-
 .../broadcom/brcm80211/brcmfmac/p2p.c         |  2 +-
 .../net/wireless/intel/iwlwifi/mvm/mac-ctxt.c |  2 +-
 drivers/pci/p2pdma.c                          |  2 +-
 drivers/s390/scsi/zfcp_fc.c                   |  2 +-
 drivers/scsi/fcoe/fcoe_ctlr.c                 |  4 +-
 drivers/scsi/qedi/qedi_main.c                 |  2 +-
 drivers/scsi/scsi_debug.c                     |  6 +-
 fs/ceph/inode.c                               |  2 +-
 fs/ceph/mdsmap.c                              |  2 +-
 fs/ext2/ialloc.c                              |  2 +-
 fs/ext4/ialloc.c                              |  2 +-
 fs/ext4/mmp.c                                 |  8 +-
 fs/ext4/super.c                               |  5 +-
 fs/f2fs/gc.c                                  |  2 +-
 fs/f2fs/segment.c                             |  8 +-
 fs/ubifs/debug.c                              |  8 +-
 fs/ubifs/lpt_commit.c                         | 14 +--
 fs/ubifs/tnc_commit.c                         |  2 +-
 fs/xfs/libxfs/xfs_alloc.c                     |  2 +-
 fs/xfs/libxfs/xfs_ialloc.c                    |  2 +-
 fs/xfs/xfs_error.c                            |  2 +-
 include/linux/damon.h                         |  2 +-
 include/linux/nodemask.h                      |  2 +-
 kernel/bpf/core.c                             |  4 +-
 kernel/kcsan/selftest.c                       |  4 +-
 kernel/locking/test-ww_mutex.c                |  4 +-
 kernel/time/clocksource.c                     |  2 +-
 lib/fault-inject.c                            |  2 +-
 lib/find_bit_benchmark.c                      |  4 +-
 lib/kobject.c                                 |  2 +-
 lib/reed_solomon/test_rslib.c                 |  6 +-
 lib/sbitmap.c                                 |  4 +-
 lib/test-string_helpers.c                     |  2 +-
 lib/test_fprobe.c                             |  5 +-
 lib/test_hexdump.c                            | 10 +--
 lib/test_kprobes.c                            |  5 +-
 lib/test_list_sort.c                          |  2 +-
 lib/test_printf.c                             |  2 +-
 lib/test_rhashtable.c                         |  6 +-
 lib/test_vmalloc.c                            |  8 +-
 mm/kasan/kasan_test.c                         |  6 +-
 mm/kfence/core.c                              |  4 +-
 mm/kfence/kfence_test.c                       |  4 +-
 mm/slub.c                                     |  2 +-
 mm/swapfile.c                                 |  5 +-
 net/802/garp.c                                |  2 +-
 net/802/mrp.c                                 |  2 +-
 net/batman-adv/bat_iv_ogm.c                   |  4 +-
 net/batman-adv/bat_v_elp.c                    |  2 +-
 net/batman-adv/bat_v_ogm.c                    |  4 +-
 net/batman-adv/network-coding.c               |  2 +-
 net/bluetooth/mgmt.c                          |  5 +-
 net/can/j1939/socket.c                        |  2 +-
 net/can/j1939/transport.c                     |  2 +-
 net/ceph/mon_client.c                         |  2 +-
 net/ceph/osd_client.c                         |  2 +-
 net/core/neighbour.c                          |  4 +-
 net/core/pktgen.c                             | 37 ++++----
 net/core/stream.c                             |  2 +-
 net/ipv4/icmp.c                               |  2 +-
 net/ipv4/igmp.c                               |  6 +-
 net/ipv4/inet_connection_sock.c               |  2 +-
 net/ipv4/inet_hashtables.c                    |  2 +-
 net/ipv4/route.c                              |  4 +-
 net/ipv4/tcp_bbr.c                            |  2 +-
 net/ipv4/tcp_input.c                          |  3 +-
 net/ipv6/addrconf.c                           |  8 +-
 net/ipv6/mcast.c                              | 10 +--
 net/ipv6/output_core.c                        |  8 +-
 net/ipv6/route.c                              |  2 +-
 net/netfilter/ipvs/ip_vs_twos.c               |  4 +-
 net/netfilter/nf_conntrack_core.c             |  4 +-
 net/netfilter/nf_nat_helper.c                 |  2 +-
 net/netlink/af_netlink.c                      |  2 +-
 net/packet/af_packet.c                        |  4 +-
 net/sched/act_gact.c                          |  2 +-
 net/sched/act_sample.c                        |  2 +-
 net/sched/sch_choke.c                         |  2 +-
 net/sched/sch_netem.c                         |  4 +-
 net/sctp/socket.c                             |  2 +-
 net/sctp/transport.c                          |  2 +-
 net/sunrpc/cache.c                            |  2 +-
 net/sunrpc/xprtsock.c                         |  2 +-
 net/tipc/socket.c                             |  2 +-
 net/vmw_vsock/af_vsock.c                      |  3 +-
 net/xfrm/xfrm_state.c                         |  2 +-
 136 files changed, 286 insertions(+), 313 deletions(-)

-- 
2.38.1


^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH v2 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop
  2022-11-14 16:45 [PATCH v2 0/3] convert tree to get_random_u32_{below,above,between}() Jason A. Donenfeld
@ 2022-11-14 16:45 ` Jason A. Donenfeld
  2022-11-14 16:45 ` [PATCH v2 3/3] treewide: use get_random_u32_between() when possible Jason A. Donenfeld
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-14 16:45 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

These cases were done with this Coccinelle:

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I > E);
+   I = get_random_u32_below(E + 1);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I >= E);
+   I = get_random_u32_below(E);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I < E);
+   I = get_random_u32_above(E - 1);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I <= E);
+   I = get_random_u32_above(E);

@@
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (!I);
+   I = get_random_u32_above(0);

@@
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I == 0);
+   I = get_random_u32_above(0);

@@
expression E;
@@
- E + 1 + get_random_u32_below(U32_MAX - E)
+ get_random_u32_above(E)

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
---
 fs/ext4/mmp.c            | 8 +-------
 lib/test_fprobe.c        | 5 +----
 lib/test_kprobes.c       | 5 +----
 net/ipv6/output_core.c   | 8 +-------
 net/vmw_vsock/af_vsock.c | 3 +--
 5 files changed, 5 insertions(+), 24 deletions(-)

diff --git a/fs/ext4/mmp.c b/fs/ext4/mmp.c
index 588cb09c5291..4681fff6665f 100644
--- a/fs/ext4/mmp.c
+++ b/fs/ext4/mmp.c
@@ -262,13 +262,7 @@ void ext4_stop_mmpd(struct ext4_sb_info *sbi)
  */
 static unsigned int mmp_new_seq(void)
 {
-	u32 new_seq;
-
-	do {
-		new_seq = get_random_u32();
-	} while (new_seq > EXT4_MMP_SEQ_MAX);
-
-	return new_seq;
+	return get_random_u32_below(EXT4_MMP_SEQ_MAX + 1);
 }
 
 /*
diff --git a/lib/test_fprobe.c b/lib/test_fprobe.c
index e0381b3ec410..1fb56cf5e5ce 100644
--- a/lib/test_fprobe.c
+++ b/lib/test_fprobe.c
@@ -144,10 +144,7 @@ static unsigned long get_ftrace_location(void *func)
 
 static int fprobe_test_init(struct kunit *test)
 {
-	do {
-		rand1 = get_random_u32();
-	} while (rand1 <= div_factor);
-
+	rand1 = get_random_u32_above(div_factor);
 	target = fprobe_selftest_target;
 	target2 = fprobe_selftest_target2;
 	target_ip = get_ftrace_location(target);
diff --git a/lib/test_kprobes.c b/lib/test_kprobes.c
index eeb1d728d974..1c95e5719802 100644
--- a/lib/test_kprobes.c
+++ b/lib/test_kprobes.c
@@ -339,10 +339,7 @@ static int kprobes_test_init(struct kunit *test)
 	stacktrace_target = kprobe_stacktrace_target;
 	internal_target = kprobe_stacktrace_internal_target;
 	stacktrace_driver = kprobe_stacktrace_driver;
-
-	do {
-		rand1 = get_random_u32();
-	} while (rand1 <= div_factor);
+	rand1 = get_random_u32_above(div_factor);
 	return 0;
 }
 
diff --git a/net/ipv6/output_core.c b/net/ipv6/output_core.c
index 2685c3f15e9d..b5205311f372 100644
--- a/net/ipv6/output_core.c
+++ b/net/ipv6/output_core.c
@@ -15,13 +15,7 @@ static u32 __ipv6_select_ident(struct net *net,
 			       const struct in6_addr *dst,
 			       const struct in6_addr *src)
 {
-	u32 id;
-
-	do {
-		id = get_random_u32();
-	} while (!id);
-
-	return id;
+	return get_random_u32_above(0);
 }
 
 /* This function exists only for tap drivers that must support broken
diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c
index ff38c5a4d174..d593d5b6d4b1 100644
--- a/net/vmw_vsock/af_vsock.c
+++ b/net/vmw_vsock/af_vsock.c
@@ -626,8 +626,7 @@ static int __vsock_bind_connectible(struct vsock_sock *vsk,
 	struct sockaddr_vm new_addr;
 
 	if (!port)
-		port = LAST_RESERVED_PORT + 1 +
-			get_random_u32_below(U32_MAX - LAST_RESERVED_PORT);
+		port = get_random_u32_above(LAST_RESERVED_PORT);
 
 	vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
 
-- 
2.38.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-14 16:45 [PATCH v2 0/3] convert tree to get_random_u32_{below,above,between}() Jason A. Donenfeld
  2022-11-14 16:45 ` [PATCH v2 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
@ 2022-11-14 16:45 ` Jason A. Donenfeld
  2022-11-16 22:43   ` Kees Cook
       [not found] ` <20221114164558.1180362-2-Jason@zx2c4.com>
  2022-11-17 20:29 ` [PATCH v3 0/3] convert tree to get_random_u32_{below,above,inclusive}() Jason A. Donenfeld
  3 siblings, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-14 16:45 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

These cases were done with this Coccinelle:

@@
expression H;
expression L;
@@
- (get_random_u32_below(H) + L)
+ get_random_u32_between(L, H + L)

@@
expression H;
expression L;
expression E;
@@
  get_random_u32_between(L,
  H
- + E
- - E
  )

@@
expression H;
expression L;
expression E;
@@
  get_random_u32_between(L,
  H
- - E
- + E
  )

@@
expression H;
expression L;
expression E;
expression F;
@@
  get_random_u32_between(L,
  H
- - E
  + F
- + E
  )

@@
expression H;
expression L;
expression E;
expression F;
@@
  get_random_u32_between(L,
  H
- + E
  + F
- - E
  )

And then subsequently cleaned up by hand, with several automatic cases
rejected if it didn't make sense contextually.

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> # for infiniband
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
---
 arch/x86/kernel/module.c                      |  2 +-
 crypto/rsa-pkcs1pad.c                         |  2 +-
 crypto/testmgr.c                              | 10 ++++----
 drivers/bus/mhi/host/internal.h               |  2 +-
 drivers/dma-buf/st-dma-fence-chain.c          |  2 +-
 drivers/infiniband/core/cma.c                 |  2 +-
 drivers/infiniband/hw/hns/hns_roce_ah.c       |  5 ++--
 drivers/mtd/nand/raw/nandsim.c                |  2 +-
 drivers/net/wireguard/selftest/allowedips.c   |  8 +++---
 .../broadcom/brcm80211/brcmfmac/p2p.c         |  2 +-
 .../net/wireless/intel/iwlwifi/mvm/mac-ctxt.c |  2 +-
 fs/f2fs/segment.c                             |  6 ++---
 kernel/kcsan/selftest.c                       |  2 +-
 lib/test_hexdump.c                            | 10 ++++----
 lib/test_printf.c                             |  2 +-
 lib/test_vmalloc.c                            |  6 ++---
 mm/kasan/kasan_test.c                         |  6 ++---
 mm/kfence/kfence_test.c                       |  2 +-
 mm/swapfile.c                                 |  5 ++--
 net/bluetooth/mgmt.c                          |  5 ++--
 net/core/pktgen.c                             | 25 ++++++++-----------
 net/ipv4/tcp_input.c                          |  2 +-
 net/ipv6/addrconf.c                           |  6 ++---
 net/netfilter/nf_nat_helper.c                 |  2 +-
 net/xfrm/xfrm_state.c                         |  2 +-
 25 files changed, 56 insertions(+), 64 deletions(-)

diff --git a/arch/x86/kernel/module.c b/arch/x86/kernel/module.c
index c09ae279ef32..9f74b7d71a50 100644
--- a/arch/x86/kernel/module.c
+++ b/arch/x86/kernel/module.c
@@ -53,7 +53,7 @@ static unsigned long int get_module_load_offset(void)
 		 */
 		if (module_load_offset == 0)
 			module_load_offset =
-				(get_random_u32_below(1024) + 1) * PAGE_SIZE;
+				get_random_u32_between(1, 1024 + 1) * PAGE_SIZE;
 		mutex_unlock(&module_kaslr_mutex);
 	}
 	return module_load_offset;
diff --git a/crypto/rsa-pkcs1pad.c b/crypto/rsa-pkcs1pad.c
index 0f722f8f779b..f31c94855a09 100644
--- a/crypto/rsa-pkcs1pad.c
+++ b/crypto/rsa-pkcs1pad.c
@@ -253,7 +253,7 @@ static int pkcs1pad_encrypt(struct akcipher_request *req)
 	ps_end = ctx->key_size - req->src_len - 2;
 	req_ctx->in_buf[0] = 0x02;
 	for (i = 1; i < ps_end; i++)
-		req_ctx->in_buf[i] = 1 + get_random_u32_below(255);
+		req_ctx->in_buf[i] = get_random_u32_between(1, 256);
 	req_ctx->in_buf[ps_end] = 0x00;
 
 	pkcs1pad_sg_set_buf(req_ctx->in_sg, req_ctx->in_buf,
diff --git a/crypto/testmgr.c b/crypto/testmgr.c
index 079923d43ce2..b09b9408ec44 100644
--- a/crypto/testmgr.c
+++ b/crypto/testmgr.c
@@ -962,11 +962,11 @@ static char *generate_random_sgl_divisions(struct test_sg_division *divs,
 		if (div == &divs[max_divs - 1] || get_random_u32_below(2) == 0)
 			this_len = remaining;
 		else
-			this_len = 1 + get_random_u32_below(remaining);
+			this_len = get_random_u32_between(1, remaining + 1);
 		div->proportion_of_total = this_len;
 
 		if (get_random_u32_below(4) == 0)
-			div->offset = (PAGE_SIZE - 128) + get_random_u32_below(128);
+			div->offset = get_random_u32_between(PAGE_SIZE - 128, PAGE_SIZE);
 		else if (get_random_u32_below(2) == 0)
 			div->offset = get_random_u32_below(32);
 		else
@@ -1094,12 +1094,12 @@ static void generate_random_testvec_config(struct testvec_config *cfg,
 	}
 
 	if (get_random_u32_below(2) == 0) {
-		cfg->iv_offset = 1 + get_random_u32_below(MAX_ALGAPI_ALIGNMASK);
+		cfg->iv_offset = get_random_u32_between(1, MAX_ALGAPI_ALIGNMASK + 1);
 		p += scnprintf(p, end - p, " iv_offset=%u", cfg->iv_offset);
 	}
 
 	if (get_random_u32_below(2) == 0) {
-		cfg->key_offset = 1 + get_random_u32_below(MAX_ALGAPI_ALIGNMASK);
+		cfg->key_offset = get_random_u32_between(1, MAX_ALGAPI_ALIGNMASK + 1);
 		p += scnprintf(p, end - p, " key_offset=%u", cfg->key_offset);
 	}
 
@@ -1653,7 +1653,7 @@ static void generate_random_hash_testvec(struct shash_desc *desc,
 	if (maxkeysize) {
 		vec->ksize = maxkeysize;
 		if (get_random_u32_below(4) == 0)
-			vec->ksize = 1 + get_random_u32_below(maxkeysize);
+			vec->ksize = get_random_u32_between(1, maxkeysize + 1);
 		generate_random_bytes((u8 *)vec->key, vec->ksize);
 
 		vec->setkey_error = crypto_shash_setkey(desc->tfm, vec->key,
diff --git a/drivers/bus/mhi/host/internal.h b/drivers/bus/mhi/host/internal.h
index c73621aabbd1..cfb85d00ab6e 100644
--- a/drivers/bus/mhi/host/internal.h
+++ b/drivers/bus/mhi/host/internal.h
@@ -129,7 +129,7 @@ enum mhi_pm_state {
 #define PRIMARY_CMD_RING				0
 #define MHI_DEV_WAKE_DB					127
 #define MHI_MAX_MTU					0xffff
-#define MHI_RANDOM_U32_NONZERO(bmsk)			(get_random_u32_below(bmsk) + 1)
+#define MHI_RANDOM_U32_NONZERO(bmsk)			(get_random_u32_between(1, bmsk + 1))
 
 enum mhi_er_type {
 	MHI_ER_TYPE_INVALID = 0x0,
diff --git a/drivers/dma-buf/st-dma-fence-chain.c b/drivers/dma-buf/st-dma-fence-chain.c
index 9fbad7317d9b..bb46b57cc230 100644
--- a/drivers/dma-buf/st-dma-fence-chain.c
+++ b/drivers/dma-buf/st-dma-fence-chain.c
@@ -400,7 +400,7 @@ static int __find_race(void *arg)
 		struct dma_fence *fence = dma_fence_get(data->fc.tail);
 		int seqno;
 
-		seqno = get_random_u32_below(data->fc.chain_length) + 1;
+		seqno = get_random_u32_between(1, data->fc.chain_length + 1);
 
 		err = dma_fence_chain_find_seqno(&fence, seqno);
 		if (err) {
diff --git a/drivers/infiniband/core/cma.c b/drivers/infiniband/core/cma.c
index dd1c703b10df..b5983b19513d 100644
--- a/drivers/infiniband/core/cma.c
+++ b/drivers/infiniband/core/cma.c
@@ -3807,7 +3807,7 @@ static int cma_alloc_any_port(enum rdma_ucm_port_space ps,
 
 	inet_get_local_port_range(net, &low, &high);
 	remaining = (high - low) + 1;
-	rover = get_random_u32_below(remaining) + low;
+	rover = get_random_u32_between(low, remaining + low);
 retry:
 	if (last_used_port != rover) {
 		struct rdma_bind_list *bind_list;
diff --git a/drivers/infiniband/hw/hns/hns_roce_ah.c b/drivers/infiniband/hw/hns/hns_roce_ah.c
index b37d2a81584d..02481487b203 100644
--- a/drivers/infiniband/hw/hns/hns_roce_ah.c
+++ b/drivers/infiniband/hw/hns/hns_roce_ah.c
@@ -41,9 +41,8 @@ static inline u16 get_ah_udp_sport(const struct rdma_ah_attr *ah_attr)
 	u16 sport;
 
 	if (!fl)
-		sport = get_random_u32_below(IB_ROCE_UDP_ENCAP_VALID_PORT_MAX +
-					     1 - IB_ROCE_UDP_ENCAP_VALID_PORT_MIN) +
-			IB_ROCE_UDP_ENCAP_VALID_PORT_MIN;
+		sport = get_random_u32_between(IB_ROCE_UDP_ENCAP_VALID_PORT_MIN,
+					       IB_ROCE_UDP_ENCAP_VALID_PORT_MAX + 1);
 	else
 		sport = rdma_flow_label_to_udp_sport(fl);
 
diff --git a/drivers/mtd/nand/raw/nandsim.c b/drivers/mtd/nand/raw/nandsim.c
index 274a31b93100..d4d7c6dac001 100644
--- a/drivers/mtd/nand/raw/nandsim.c
+++ b/drivers/mtd/nand/raw/nandsim.c
@@ -1405,7 +1405,7 @@ static void ns_do_bit_flips(struct nandsim *ns, int num)
 	if (bitflips && get_random_u16() < (1 << 6)) {
 		int flips = 1;
 		if (bitflips > 1)
-			flips = get_random_u32_below(bitflips) + 1;
+			flips = get_random_u32_between(1, bitflips + 1);
 		while (flips--) {
 			int pos = get_random_u32_below(num * 8);
 			ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
diff --git a/drivers/net/wireguard/selftest/allowedips.c b/drivers/net/wireguard/selftest/allowedips.c
index 78a916f30c82..34d5981f4513 100644
--- a/drivers/net/wireguard/selftest/allowedips.c
+++ b/drivers/net/wireguard/selftest/allowedips.c
@@ -285,7 +285,7 @@ static __init bool randomized_test(void)
 
 	for (i = 0; i < NUM_RAND_ROUTES; ++i) {
 		get_random_bytes(ip, 4);
-		cidr = get_random_u32_below(32) + 1;
+		cidr = get_random_u32_between(1, 32 + 1);
 		peer = peers[get_random_u32_below(NUM_PEERS)];
 		if (wg_allowedips_insert_v4(&t, (struct in_addr *)ip, cidr,
 					    peer, &mutex) < 0) {
@@ -311,7 +311,7 @@ static __init bool randomized_test(void)
 				mutated[k] = (mutated[k] & mutate_mask[k]) |
 					     (~mutate_mask[k] &
 					      get_random_u8());
-			cidr = get_random_u32_below(32) + 1;
+			cidr = get_random_u32_between(1, 32 + 1);
 			peer = peers[get_random_u32_below(NUM_PEERS)];
 			if (wg_allowedips_insert_v4(&t,
 						    (struct in_addr *)mutated,
@@ -329,7 +329,7 @@ static __init bool randomized_test(void)
 
 	for (i = 0; i < NUM_RAND_ROUTES; ++i) {
 		get_random_bytes(ip, 16);
-		cidr = get_random_u32_below(128) + 1;
+		cidr = get_random_u32_between(1, 128 + 1);
 		peer = peers[get_random_u32_below(NUM_PEERS)];
 		if (wg_allowedips_insert_v6(&t, (struct in6_addr *)ip, cidr,
 					    peer, &mutex) < 0) {
@@ -355,7 +355,7 @@ static __init bool randomized_test(void)
 				mutated[k] = (mutated[k] & mutate_mask[k]) |
 					     (~mutate_mask[k] &
 					      get_random_u8());
-			cidr = get_random_u32_below(128) + 1;
+			cidr = get_random_u32_between(1, 128 + 1);
 			peer = peers[get_random_u32_below(NUM_PEERS)];
 			if (wg_allowedips_insert_v6(&t,
 						    (struct in6_addr *)mutated,
diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
index 23c971b77965..0e6bf5e5c8a9 100644
--- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
+++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
@@ -1128,7 +1128,7 @@ static void brcmf_p2p_afx_handler(struct work_struct *work)
 	if (afx_hdl->is_listen && afx_hdl->my_listen_chan)
 		/* 100ms ~ 300ms */
 		err = brcmf_p2p_discover_listen(p2p, afx_hdl->my_listen_chan,
-						100 * (1 + get_random_u32_below(3)));
+						100 * get_random_u32_between(1, 4));
 	else
 		err = brcmf_p2p_act_frm_search(p2p, afx_hdl->peer_listen_chan);
 
diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c b/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
index 1696fbf1009a..f0b94633834e 100644
--- a/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
+++ b/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
@@ -1099,7 +1099,7 @@ static void iwl_mvm_mac_ctxt_cmd_fill_ap(struct iwl_mvm *mvm,
 			iwl_mvm_mac_ap_iterator, &data);
 
 		if (data.beacon_device_ts) {
-			u32 rand = get_random_u32_below(64 - 36) + 36;
+			u32 rand = get_random_u32_between(36, 64);
 			mvmvif->ap_beacon_time = data.beacon_device_ts +
 				ieee80211_tu_to_usec(data.beacon_int * rand /
 						     100);
diff --git a/fs/f2fs/segment.c b/fs/f2fs/segment.c
index 334415d946f8..8319fdc59fb4 100644
--- a/fs/f2fs/segment.c
+++ b/fs/f2fs/segment.c
@@ -2588,7 +2588,7 @@ static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
 	curseg->alloc_type = LFS;
 	if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
 		curseg->fragment_remained_chunk =
-				get_random_u32_below(sbi->max_fragment_chunk) + 1;
+				get_random_u32_between(1, sbi->max_fragment_chunk + 1);
 }
 
 static int __next_free_blkoff(struct f2fs_sb_info *sbi,
@@ -2625,9 +2625,9 @@ static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
 			/* To allocate block chunks in different sizes, use random number */
 			if (--seg->fragment_remained_chunk <= 0) {
 				seg->fragment_remained_chunk =
-				   get_random_u32_below(sbi->max_fragment_chunk) + 1;
+				   get_random_u32_between(1, sbi->max_fragment_chunk + 1);
 				seg->next_blkoff +=
-				   get_random_u32_below(sbi->max_fragment_hole) + 1;
+				   get_random_u32_between(1, sbi->max_fragment_hole + 1);
 			}
 		}
 	}
diff --git a/kernel/kcsan/selftest.c b/kernel/kcsan/selftest.c
index 7b619f16a492..eed30ad29796 100644
--- a/kernel/kcsan/selftest.c
+++ b/kernel/kcsan/selftest.c
@@ -31,7 +31,7 @@ static bool __init test_encode_decode(void)
 	int i;
 
 	for (i = 0; i < ITERS_PER_TEST; ++i) {
-		size_t size = get_random_u32_below(MAX_ENCODABLE_SIZE) + 1;
+		size_t size = get_random_u32_between(1, MAX_ENCODABLE_SIZE + 1);
 		bool is_write = !!get_random_u32_below(2);
 		unsigned long verif_masked_addr;
 		long encoded_watchpoint;
diff --git a/lib/test_hexdump.c b/lib/test_hexdump.c
index efc50fd30a44..f4ff3041ec10 100644
--- a/lib/test_hexdump.c
+++ b/lib/test_hexdump.c
@@ -149,7 +149,7 @@ static void __init test_hexdump(size_t len, int rowsize, int groupsize,
 static void __init test_hexdump_set(int rowsize, bool ascii)
 {
 	size_t d = min_t(size_t, sizeof(data_b), rowsize);
-	size_t len = get_random_u32_below(d) + 1;
+	size_t len = get_random_u32_between(1, d + 1);
 
 	test_hexdump(len, rowsize, 4, ascii);
 	test_hexdump(len, rowsize, 2, ascii);
@@ -208,11 +208,11 @@ static void __init test_hexdump_overflow(size_t buflen, size_t len,
 static void __init test_hexdump_overflow_set(size_t buflen, bool ascii)
 {
 	unsigned int i = 0;
-	int rs = (get_random_u32_below(2) + 1) * 16;
+	int rs = get_random_u32_between(1, 3) * 16;
 
 	do {
 		int gs = 1 << i;
-		size_t len = get_random_u32_below(rs) + gs;
+		size_t len = get_random_u32_between(gs, rs + gs);
 
 		test_hexdump_overflow(buflen, rounddown(len, gs), rs, gs, ascii);
 	} while (i++ < 3);
@@ -223,11 +223,11 @@ static int __init test_hexdump_init(void)
 	unsigned int i;
 	int rowsize;
 
-	rowsize = (get_random_u32_below(2) + 1) * 16;
+	rowsize = get_random_u32_between(1, 3) * 16;
 	for (i = 0; i < 16; i++)
 		test_hexdump_set(rowsize, false);
 
-	rowsize = (get_random_u32_below(2) + 1) * 16;
+	rowsize = get_random_u32_between(1, 3) * 16;
 	for (i = 0; i < 16; i++)
 		test_hexdump_set(rowsize, true);
 
diff --git a/lib/test_printf.c b/lib/test_printf.c
index 6d10187eddac..da5efc8b8543 100644
--- a/lib/test_printf.c
+++ b/lib/test_printf.c
@@ -126,7 +126,7 @@ __test(const char *expect, int elen, const char *fmt, ...)
 	 * be able to print it as expected.
 	 */
 	failed_tests += do_test(BUF_SIZE, expect, elen, fmt, ap);
-	rand = 1 + get_random_u32_below(elen + 1);
+	rand = get_random_u32_between(1, elen + 2);
 	/* Since elen < BUF_SIZE, we have 1 <= rand <= BUF_SIZE. */
 	failed_tests += do_test(rand, expect, elen, fmt, ap);
 	failed_tests += do_test(0, expect, elen, fmt, ap);
diff --git a/lib/test_vmalloc.c b/lib/test_vmalloc.c
index 104f09ea5fcc..7a2caf4596c5 100644
--- a/lib/test_vmalloc.c
+++ b/lib/test_vmalloc.c
@@ -151,7 +151,7 @@ static int random_size_alloc_test(void)
 	int i;
 
 	for (i = 0; i < test_loop_count; i++) {
-		n = get_random_u32_below(100) + 1;
+		n = get_random_u32_between(1, 101);
 		p = vmalloc(n * PAGE_SIZE);
 
 		if (!p)
@@ -291,12 +291,12 @@ pcpu_alloc_test(void)
 		return -1;
 
 	for (i = 0; i < 35000; i++) {
-		size = get_random_u32_below(PAGE_SIZE / 4) + 1;
+		size = get_random_u32_between(1, PAGE_SIZE / 4 + 1);
 
 		/*
 		 * Maximum PAGE_SIZE
 		 */
-		align = 1 << (get_random_u32_below(11) + 1);
+		align = 1 << get_random_u32_between(1, 12);
 
 		pcpu[i] = __alloc_percpu(size, align);
 		if (!pcpu[i])
diff --git a/mm/kasan/kasan_test.c b/mm/kasan/kasan_test.c
index 640f9c7f8e44..6167e19056f0 100644
--- a/mm/kasan/kasan_test.c
+++ b/mm/kasan/kasan_test.c
@@ -1299,7 +1299,7 @@ static void match_all_not_assigned(struct kunit *test)
 	KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
 
 	for (i = 0; i < 256; i++) {
-		size = get_random_u32_below(1024) + 1;
+		size = get_random_u32_between(1, 1024 + 1);
 		ptr = kmalloc(size, GFP_KERNEL);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
 		KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
@@ -1308,7 +1308,7 @@ static void match_all_not_assigned(struct kunit *test)
 	}
 
 	for (i = 0; i < 256; i++) {
-		order = get_random_u32_below(4) + 1;
+		order = get_random_u32_between(1, 5);
 		pages = alloc_pages(GFP_KERNEL, order);
 		ptr = page_address(pages);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
@@ -1321,7 +1321,7 @@ static void match_all_not_assigned(struct kunit *test)
 		return;
 
 	for (i = 0; i < 256; i++) {
-		size = get_random_u32_below(1024) + 1;
+		size = get_random_u32_between(1, 1024 + 1);
 		ptr = vmalloc(size);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
 		KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 20028c179796..99abe86fc9b1 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -532,7 +532,7 @@ static void test_free_bulk(struct kunit *test)
 	int iter;
 
 	for (iter = 0; iter < 5; iter++) {
-		const size_t size = setup_test_cache(test, 8 + get_random_u32_below(300),
+		const size_t size = setup_test_cache(test, get_random_u32_between(8, 308),
 						     0, (iter & 1) ? ctor_set_x : NULL);
 		void *objects[] = {
 			test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT),
diff --git a/mm/swapfile.c b/mm/swapfile.c
index e9318305a24a..08f0152c32da 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -772,8 +772,7 @@ static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
 		/* No free swap slots available */
 		if (si->highest_bit <= si->lowest_bit)
 			return;
-		next = si->lowest_bit +
-			get_random_u32_below(si->highest_bit - si->lowest_bit + 1);
+		next = get_random_u32_between(si->lowest_bit, si->highest_bit + 1);
 		next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
 		next = max_t(unsigned int, next, si->lowest_bit);
 	}
@@ -3089,7 +3088,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		 */
 		for_each_possible_cpu(cpu) {
 			per_cpu(*p->cluster_next_cpu, cpu) =
-				1 + get_random_u32_below(p->highest_bit);
+				get_random_u32_between(1, p->highest_bit + 1);
 		}
 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 
diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c
index b2f9679066c4..bab37a529db5 100644
--- a/net/bluetooth/mgmt.c
+++ b/net/bluetooth/mgmt.c
@@ -7373,9 +7373,8 @@ static int get_conn_info(struct sock *sk, struct hci_dev *hdev, void *data,
 	/* To avoid client trying to guess when to poll again for information we
 	 * calculate conn info age as random value between min/max set in hdev.
 	 */
-	conn_info_age = hdev->conn_info_min_age +
-			get_random_u32_below(hdev->conn_info_max_age -
-					     hdev->conn_info_min_age);
+	conn_info_age = get_random_u32_between(hdev->conn_info_min_age,
+					       hdev->conn_info_max_age);
 
 	/* Query controller to refresh cached values if they are too old or were
 	 * never read.
diff --git a/net/core/pktgen.c b/net/core/pktgen.c
index 95da2ddc1c20..5eb401003368 100644
--- a/net/core/pktgen.c
+++ b/net/core/pktgen.c
@@ -2380,9 +2380,8 @@ static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
 	else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
 		__u16 t;
 		if (pkt_dev->flags & F_QUEUE_MAP_RND) {
-			t = get_random_u32_below(pkt_dev->queue_map_max -
-						 pkt_dev->queue_map_min + 1) +
-			    pkt_dev->queue_map_min;
+			t = get_random_u32_between(pkt_dev->queue_map_min,
+						   pkt_dev->queue_map_max + 1);
 		} else {
 			t = pkt_dev->cur_queue_map + 1;
 			if (t > pkt_dev->queue_map_max)
@@ -2478,9 +2477,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 
 	if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
 		if (pkt_dev->flags & F_UDPSRC_RND)
-			pkt_dev->cur_udp_src = get_random_u32_below(
-				pkt_dev->udp_src_max - pkt_dev->udp_src_min) +
-				pkt_dev->udp_src_min;
+			pkt_dev->cur_udp_src = get_random_u32_between(pkt_dev->udp_src_min,
+								      pkt_dev->udp_src_max);
 
 		else {
 			pkt_dev->cur_udp_src++;
@@ -2491,9 +2489,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 
 	if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
 		if (pkt_dev->flags & F_UDPDST_RND) {
-			pkt_dev->cur_udp_dst = get_random_u32_below(
-				pkt_dev->udp_dst_max - pkt_dev->udp_dst_min) +
-				pkt_dev->udp_dst_min;
+			pkt_dev->cur_udp_dst = get_random_u32_between(pkt_dev->udp_dst_min,
+								      pkt_dev->udp_dst_max);
 		} else {
 			pkt_dev->cur_udp_dst++;
 			if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
@@ -2508,7 +2505,7 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 		if (imn < imx) {
 			__u32 t;
 			if (pkt_dev->flags & F_IPSRC_RND)
-				t = get_random_u32_below(imx - imn) + imn;
+				t = get_random_u32_between(imn, imx);
 			else {
 				t = ntohl(pkt_dev->cur_saddr);
 				t++;
@@ -2530,8 +2527,7 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 				if (pkt_dev->flags & F_IPDST_RND) {
 
 					do {
-						t = get_random_u32_below(imx - imn) +
-						    imn;
+						t = get_random_u32_between(imn, imx);
 						s = htonl(t);
 					} while (ipv4_is_loopback(s) ||
 						ipv4_is_multicast(s) ||
@@ -2578,9 +2574,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 	if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
 		__u32 t;
 		if (pkt_dev->flags & F_TXSIZE_RND) {
-			t = get_random_u32_below(pkt_dev->max_pkt_size -
-						 pkt_dev->min_pkt_size) +
-			    pkt_dev->min_pkt_size;
+			t = get_random_u32_between(pkt_dev->min_pkt_size,
+						   pkt_dev->max_pkt_size);
 		} else {
 			t = pkt_dev->cur_pkt_size + 1;
 			if (t > pkt_dev->max_pkt_size)
diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c
index 3b076e5ba932..1a348298a99e 100644
--- a/net/ipv4/tcp_input.c
+++ b/net/ipv4/tcp_input.c
@@ -3647,7 +3647,7 @@ static void tcp_send_challenge_ack(struct sock *sk)
 
 		WRITE_ONCE(net->ipv4.tcp_challenge_timestamp, now);
 		WRITE_ONCE(net->ipv4.tcp_challenge_count,
-			   half + get_random_u32_below(ack_limit));
+			   get_random_u32_between(half, ack_limit + half));
 	}
 	count = READ_ONCE(net->ipv4.tcp_challenge_count);
 	if (count > 0) {
diff --git a/net/ipv6/addrconf.c b/net/ipv6/addrconf.c
index daf89a2eb492..3f750e6d0ac3 100644
--- a/net/ipv6/addrconf.c
+++ b/net/ipv6/addrconf.c
@@ -104,7 +104,7 @@ static inline u32 cstamp_delta(unsigned long cstamp)
 static inline s32 rfc3315_s14_backoff_init(s32 irt)
 {
 	/* multiply 'initial retransmission time' by 0.9 .. 1.1 */
-	u64 tmp = (900000 + get_random_u32_below(200001)) * (u64)irt;
+	u64 tmp = get_random_u32_between(900000, 1100001) * (u64)irt;
 	do_div(tmp, 1000000);
 	return (s32)tmp;
 }
@@ -112,11 +112,11 @@ static inline s32 rfc3315_s14_backoff_init(s32 irt)
 static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
 {
 	/* multiply 'retransmission timeout' by 1.9 .. 2.1 */
-	u64 tmp = (1900000 + get_random_u32_below(200001)) * (u64)rt;
+	u64 tmp = get_random_u32_between(1900000, 2100001) * (u64)rt;
 	do_div(tmp, 1000000);
 	if ((s32)tmp > mrt) {
 		/* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
-		tmp = (900000 + get_random_u32_below(200001)) * (u64)mrt;
+		tmp = get_random_u32_between(900000, 1100001) * (u64)mrt;
 		do_div(tmp, 1000000);
 	}
 	return (s32)tmp;
diff --git a/net/netfilter/nf_nat_helper.c b/net/netfilter/nf_nat_helper.c
index bf591e6af005..a12c3470f7fd 100644
--- a/net/netfilter/nf_nat_helper.c
+++ b/net/netfilter/nf_nat_helper.c
@@ -223,7 +223,7 @@ u16 nf_nat_exp_find_port(struct nf_conntrack_expect *exp, u16 port)
 		if (res != -EBUSY || (--attempts_left < 0))
 			break;
 
-		port = min + get_random_u32_below(range);
+		port = get_random_u32_between(min, range + min);
 	}
 
 	return 0;
diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c
index 40f831854774..c118476f73ae 100644
--- a/net/xfrm/xfrm_state.c
+++ b/net/xfrm/xfrm_state.c
@@ -2072,7 +2072,7 @@ int xfrm_alloc_spi(struct xfrm_state *x, u32 low, u32 high)
 	} else {
 		u32 spi = 0;
 		for (h = 0; h < high-low+1; h++) {
-			spi = low + get_random_u32_below(high - low + 1);
+			spi = get_random_u32_between(low, high + 1);
 			x0 = xfrm_state_lookup(net, mark, &x->id.daddr, htonl(spi), x->id.proto, x->props.family);
 			if (x0 == NULL) {
 				newspi = htonl(spi);
-- 
2.38.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 1/3] treewide: use get_random_u32_below() instead of deprecated function
       [not found] ` <20221114164558.1180362-2-Jason@zx2c4.com>
@ 2022-11-14 17:35   ` Russell King (Oracle)
  0 siblings, 0 replies; 22+ messages in thread
From: Russell King (Oracle) @ 2022-11-14 17:35 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc

On Mon, Nov 14, 2022 at 05:45:56PM +0100, Jason A. Donenfeld wrote:
> This is a simple mechanical transformation done by:
> 
> @@
> expression E;
> @@
> - prandom_u32_max
> + get_random_u32_below
>   (E)
> 
> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
> Acked-by: Darrick J. Wong <djwong@kernel.org> # for xfs
> Reviewed-by: SeongJae Park <sj@kernel.org> # for damon
> Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> # for infiniband
> Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
> ---
>  arch/arm/kernel/process.c                     |  2 +-

Reviewed-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk> # for arm

Thanks.

-- 
RMK's Patch system: https://www.armlinux.org.uk/developer/patches/
FTTP is here! 40Mbps down 10Mbps up. Decent connectivity at last!

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-14 16:45 ` [PATCH v2 3/3] treewide: use get_random_u32_between() when possible Jason A. Donenfeld
@ 2022-11-16 22:43   ` Kees Cook
  2022-11-16 23:55     ` Jason A. Donenfeld
  0 siblings, 1 reply; 22+ messages in thread
From: Kees Cook @ 2022-11-16 22:43 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc

On Mon, Nov 14, 2022 at 05:45:58PM +0100, Jason A. Donenfeld wrote:
> -				(get_random_u32_below(1024) + 1) * PAGE_SIZE;
> +				get_random_u32_between(1, 1024 + 1) * PAGE_SIZE;

I really don't like "between". Can't this be named "inclusive" (and
avoid adding 1 everywhere, which seems ugly), or at least named
something less ambiguous?

> -		n = get_random_u32_below(100) + 1;
> +		n = get_random_u32_between(1, 101);

Because I find this much less readable. "Below 100" is clear: 0-99
inclusive, plus 1, so 1-100 inclusive. "Between 1 and 101" is not obvious
to me to mean: 1-100 inclusive.

These seem so much nicer:
	get_random_u32_inclusive(1, 1024)
	get_random_u32_inclusive(1, 100)

-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-16 22:43   ` Kees Cook
@ 2022-11-16 23:55     ` Jason A. Donenfeld
  2022-11-17  0:03       ` Jason A. Donenfeld
  2022-11-17  2:05       ` Jason A. Donenfeld
  0 siblings, 2 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-16 23:55 UTC (permalink / raw)
  To: Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Wed, Nov 16, 2022 at 02:43:13PM -0800, Kees Cook wrote:
> On Mon, Nov 14, 2022 at 05:45:58PM +0100, Jason A. Donenfeld wrote:
> > -				(get_random_u32_below(1024) + 1) * PAGE_SIZE;
> > +				get_random_u32_between(1, 1024 + 1) * PAGE_SIZE;
> 
> I really don't like "between". Can't this be named "inclusive" (and
> avoid adding 1 everywhere, which seems ugly), or at least named
> something less ambiguous?
> 
> > -		n = get_random_u32_below(100) + 1;
> > +		n = get_random_u32_between(1, 101);
> 
> Because I find this much less readable. "Below 100" is clear: 0-99
> inclusive, plus 1, so 1-100 inclusive. "Between 1 and 101" is not obvious
> to me to mean: 1-100 inclusive.
> 
> These seem so much nicer:
> 	get_random_u32_inclusive(1, 1024)
> 	get_random_u32_inclusive(1, 100)

Yann pointed out something similar -- the half-closed interval being
confusing -- and while I was initially dismissive, I've warmed up to
doing this fully closed after sending a diff of that:

https://lore.kernel.org/lkml/Y3Qt8HiXj8giOnZy@zx2c4.com/

So okay, let's say that I'll implement the inclusive version instead. We
now have two problems to solve:

1) How/whether to make f(0, UR2_MAX) safe,
   - without additional 64-bit arithmetic,
   - minimizing the number of branches.
   I have a few ideas I'll code golf for a bit.

2) What to call it:
   - between I still like, because it mirrors "I'm thinking of a number
     between 1 and 10 and..." that everybody knows,
   - inclusive I guess works, but it's not a preposition,
   - bikeshed color #3?

I think I can make progress with (1) alone by fiddling around with
godbolt enough, like usual. I could use some more ideas for (2) though.

Jason

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-16 23:55     ` Jason A. Donenfeld
@ 2022-11-17  0:03       ` Jason A. Donenfeld
  2022-11-17  0:31         ` Kees Cook
  2022-11-17  2:05       ` Jason A. Donenfeld
  1 sibling, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17  0:03 UTC (permalink / raw)
  To: Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
> 2) What to call it:
>    - between I still like, because it mirrors "I'm thinking of a number
>      between 1 and 10 and..." that everybody knows,
>    - inclusive I guess works, but it's not a preposition,
>    - bikeshed color #3?

- between
- ranged
- spanning

https://www.thefreedictionary.com/List-of-prepositions.htm
- amid

Sigh, names.


^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17  0:03       ` Jason A. Donenfeld
@ 2022-11-17  0:31         ` Kees Cook
  2022-11-17  0:43           ` Jason A. Donenfeld
  0 siblings, 1 reply; 22+ messages in thread
From: Kees Cook @ 2022-11-17  0:31 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Thu, Nov 17, 2022 at 01:03:14AM +0100, Jason A. Donenfeld wrote:
> On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
> > 2) What to call it:
> >    - between I still like, because it mirrors "I'm thinking of a number
> >      between 1 and 10 and..." that everybody knows,
> >    - inclusive I guess works, but it's not a preposition,
> >    - bikeshed color #3?
> 
> - between
> - ranged
> - spanning
> 
> https://www.thefreedictionary.com/List-of-prepositions.htm
> - amid
> 
> Sigh, names.

I think "inclusive" is best. The other words still don't provide
unambiguous language. It's the language used in formal math, e.g.
sigma-notation, etc. It's an adjective for "get random" (verb, noun).

-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17  0:31         ` Kees Cook
@ 2022-11-17  0:43           ` Jason A. Donenfeld
  2022-11-17  0:47             ` Kees Cook
  0 siblings, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17  0:43 UTC (permalink / raw)
  To: Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Wed, Nov 16, 2022 at 04:31:18PM -0800, Kees Cook wrote:
> On Thu, Nov 17, 2022 at 01:03:14AM +0100, Jason A. Donenfeld wrote:
> > On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
> > > 2) What to call it:
> > >    - between I still like, because it mirrors "I'm thinking of a number
> > >      between 1 and 10 and..." that everybody knows,
> > >    - inclusive I guess works, but it's not a preposition,
> > >    - bikeshed color #3?
> > 
> > - between
> > - ranged
> > - spanning
> > 
> > https://www.thefreedictionary.com/List-of-prepositions.htm
> > - amid
> > 
> > Sigh, names.
> 
> I think "inclusive" is best.

I find it not very descriptive of what the function does. Is there one
you like second best? Or are you convinced they're all much much much
worse than "inclusive" that they shouldn't be considered?

Jason

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17  0:43           ` Jason A. Donenfeld
@ 2022-11-17  0:47             ` Kees Cook
  2022-11-17 15:42               ` Theodore Ts'o
  0 siblings, 1 reply; 22+ messages in thread
From: Kees Cook @ 2022-11-17  0:47 UTC (permalink / raw)
  To: Jason A. Donenfeld, Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On November 16, 2022 4:43:54 PM PST, "Jason A. Donenfeld" <Jason@zx2c4.com> wrote:
>On Wed, Nov 16, 2022 at 04:31:18PM -0800, Kees Cook wrote:
>> On Thu, Nov 17, 2022 at 01:03:14AM +0100, Jason A. Donenfeld wrote:
>> > On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
>> > > 2) What to call it:
>> > >    - between I still like, because it mirrors "I'm thinking of a number
>> > >      between 1 and 10 and..." that everybody knows,
>> > >    - inclusive I guess works, but it's not a preposition,
>> > >    - bikeshed color #3?
>> > 
>> > - between
>> > - ranged
>> > - spanning
>> > 
>> > https://www.thefreedictionary.com/List-of-prepositions.htm
>> > - amid
>> > 
>> > Sigh, names.
>> 
>> I think "inclusive" is best.
>
>I find it not very descriptive of what the function does. Is there one
>you like second best? Or are you convinced they're all much much much
>worse than "inclusive" that they shouldn't be considered?

Right, I don't think any are sufficiently descriptive. "Incluisve" with two arguments seems unambiguous and complete to me. :)


-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-16 23:55     ` Jason A. Donenfeld
  2022-11-17  0:03       ` Jason A. Donenfeld
@ 2022-11-17  2:05       ` Jason A. Donenfeld
  2022-11-17 10:32         ` Russell King (Oracle)
  1 sibling, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17  2:05 UTC (permalink / raw)
  To: Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
> 1) How/whether to make f(0, UR2_MAX) safe,
>    - without additional 64-bit arithmetic,
>    - minimizing the number of branches.
>    I have a few ideas I'll code golf for a bit.
> I think I can make progress with (1) alone by fiddling around with
> godbolt enough, like usual.

The code gen is definitely worse.

Original half-open interval:

    return floor + get_random_u32_below(ceil - floor);

Suggested fully closed interval:
	
    ceil = ceil - floor + 1;
    return likely(ceil) ? floor + get_random_u32_below(ceil) : get_random_u32();

Is the worse code gen actually worth it? Options:

 a) Decide worse codegen is worth it.
 b) Declare f(0, U32_MAX) undefined and just not handle it.
 c) Stick with original half-open interval that doesn't have this problem.

Jason

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17  2:05       ` Jason A. Donenfeld
@ 2022-11-17 10:32         ` Russell King (Oracle)
  0 siblings, 0 replies; 22+ messages in thread
From: Russell King (Oracle) @ 2022-11-17 10:32 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: Kees Cook, linux-kernel, patches, Greg Kroah-Hartman,
	Jakub Kicinski, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Thu, Nov 17, 2022 at 03:05:14AM +0100, Jason A. Donenfeld wrote:
> On Thu, Nov 17, 2022 at 12:55:47AM +0100, Jason A. Donenfeld wrote:
> > 1) How/whether to make f(0, UR2_MAX) safe,
> >    - without additional 64-bit arithmetic,
> >    - minimizing the number of branches.
> >    I have a few ideas I'll code golf for a bit.
> > I think I can make progress with (1) alone by fiddling around with
> > godbolt enough, like usual.
> 
> The code gen is definitely worse.
> 
> Original half-open interval:
> 
>     return floor + get_random_u32_below(ceil - floor);
> 
> Suggested fully closed interval:
> 	
>     ceil = ceil - floor + 1;
>     return likely(ceil) ? floor + get_random_u32_below(ceil) : get_random_u32();

How many of these uses are going to have ceil and floor as a variable?
If they're constants (e.g. due to being in an inline function with
constant arguments) then the compiler will optimise all of the above
and the assembly code will just be either:

1. a call to get_random_u32()
2. a call to get_random_u32_below() and an addition.

If one passes ceil or floor as a variable, then yes, the code gen is
going to be as complicated as you suggest above.

-- 
RMK's Patch system: https://www.armlinux.org.uk/developer/patches/
FTTP is here! 40Mbps down 10Mbps up. Decent connectivity at last!

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17  0:47             ` Kees Cook
@ 2022-11-17 15:42               ` Theodore Ts'o
  2022-11-17 16:19                 ` Jason A. Donenfeld
  2022-11-17 22:15                 ` David Laight
  0 siblings, 2 replies; 22+ messages in thread
From: Theodore Ts'o @ 2022-11-17 15:42 UTC (permalink / raw)
  To: Kees Cook
  Cc: Jason A. Donenfeld, Kees Cook, linux-kernel, patches,
	Greg Kroah-Hartman, Jakub Kicinski, Russell King,
	Catalin Marinas, Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Wed, Nov 16, 2022 at 04:47:27PM -0800, Kees Cook wrote:
> >> > - between
> >> > - ranged
> >> > - spanning
> >> > 
> >> > https://www.thefreedictionary.com/List-of-prepositions.htm
> >> > - amid
> >> > 
> >> > Sigh, names.
> >> 
> >> I think "inclusive" is best.
> >
> >I find it not very descriptive of what the function does. Is there one
> >you like second best? Or are you convinced they're all much much much
> >worse than "inclusive" that they shouldn't be considered?
> 
> Right, I don't think any are sufficiently descriptive. "Incluisve"
> with two arguments seems unambiguous and complete to me. :)

The problem with "between", "ranged", "spanning" is that they don't
tell the reader whether we're dealing with an "open interval" or a
"closed interval".  They are just different ways of saying that it's a
range between, say, 0 and 20.  But it doesn't tell you whether it
includes 0 or 20 or not.

The only way I can see for making it ambiguous is either to use the
terminology "closed interval" or "inclusive".  And "open" and "closed"
can have other meanings, so get_random_u32_inclusive() is going to be
less confusing than get_random_u32_closed().

Cheers,

					- Ted

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17 15:42               ` Theodore Ts'o
@ 2022-11-17 16:19                 ` Jason A. Donenfeld
  2022-11-17 22:15                 ` David Laight
  1 sibling, 0 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17 16:19 UTC (permalink / raw)
  To: Theodore Ts'o
  Cc: Kees Cook, Kees Cook, linux-kernel, patches, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

On Thu, Nov 17, 2022 at 10:42:37AM -0500, Theodore Ts'o wrote:
> On Wed, Nov 16, 2022 at 04:47:27PM -0800, Kees Cook wrote:
> > >> > - between
> > >> > - ranged
> > >> > - spanning
> > >> > 
> > >> > https://www.thefreedictionary.com/List-of-prepositions.htm
> > >> > - amid
> > >> > 
> > >> > Sigh, names.
> > >> 
> > >> I think "inclusive" is best.
> > >
> > >I find it not very descriptive of what the function does. Is there one
> > >you like second best? Or are you convinced they're all much much much
> > >worse than "inclusive" that they shouldn't be considered?
> > 
> > Right, I don't think any are sufficiently descriptive. "Incluisve"
> > with two arguments seems unambiguous and complete to me. :)
> 
> The problem with "between", "ranged", "spanning" is that they don't
> tell the reader whether we're dealing with an "open interval" or a
> "closed interval".  They are just different ways of saying that it's a
> range between, say, 0 and 20.  But it doesn't tell you whether it
> includes 0 or 20 or not.
> 
> The only way I can see for making it ambiguous is either to use the
> terminology "closed interval" or "inclusive".  And "open" and "closed"
> can have other meanings, so get_random_u32_inclusive() is going to be
> less confusing than get_random_u32_closed().

Alright, that about settles it then. I'll re-roll.

Jason

^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH v3 0/3] convert tree to get_random_u32_{below,above,inclusive}()
  2022-11-14 16:45 [PATCH v2 0/3] convert tree to get_random_u32_{below,above,between}() Jason A. Donenfeld
                   ` (2 preceding siblings ...)
       [not found] ` <20221114164558.1180362-2-Jason@zx2c4.com>
@ 2022-11-17 20:29 ` Jason A. Donenfeld
  2022-11-17 20:29   ` [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
                     ` (2 more replies)
  3 siblings, 3 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17 20:29 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

Hey everyone,

[Changes v2->v3: rename get_random_u32_between() to
 get_random_u32_inclusive(), and implement with closed interval.]

This series is the second tranche of tree-wide conversions to get random
integer handling a bit tamer. It's another Coccinelle-based patchset.

First we s/prandom_u32_max/get_random_u32_below/, since the former is
just a deprecated alias for the latter. Then later, we can remove
prandom_u32_max all together. I'm quite happy about finally being able
to do that. It means that prandom.h is now only for deterministic and
repeatable randomness, not non-deterministic/cryptographic randomness.
That line is no longer blurred.

In order to clean up a bunch of inefficient patterns, we use two simple
helper functions built on top of get_random_u32_below:
get_random_u32_above and get_random_u32_inclusive. The next two patches
convert some gnarly open-coded number juggling to use these helpers.

I've used Coccinelle for these three treewide patches, so hopefully
review is rather uneventful. I didn't accept all of the changes that
Coccinelle proposed, though, as these tend to be somewhat
context-specific. I erred on the side of just going with the most
obvious cases, at least this time through. And then we can address more
complicated cases through actual maintainer trees.

Since get_random_u32_below() and others sits in my random.git tree,
these patches too will flow through that same tree.

Regards,
Jason

Cc: Kees Cook <keescook@chromium.org>
Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Jakub Kicinski <kuba@kernel.org>
Cc: Russell King <linux@armlinux.org.uk>
Cc: Catalin Marinas <catalin.marinas@arm.com>
Cc: Thomas Bogendoerfer <tsbogend@alpha.franken.de>
Cc: Heiko Carstens <hca@linux.ibm.com>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Cc: Christoph Böhmwalder <christoph.boehmwalder@linbit.com>
Cc: Jani Nikula <jani.nikula@linux.intel.com>
Cc: Jason Gunthorpe <jgg@nvidia.com>
Cc: Sakari Ailus <sakari.ailus@linux.intel.com>
Cc: Martin K. Petersen <martin.petersen@oracle.com>
Cc: Theodore Ts'o <tytso@mit.edu>
Cc: Andreas Dilger <adilger.kernel@dilger.ca>
Cc: Jaegeuk Kim <jaegeuk@kernel.org>
Cc: Richard Weinberger <richard@nod.at>
Cc: Darrick J. Wong <djwong@kernel.org>
Cc: SeongJae Park <sj@kernel.org>
Cc: Thomas Gleixner <tglx@linutronix.de>
Cc: Andrew Morton <akpm@linux-foundation.org>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Helge Deller <deller@gmx.de>
Cc: netdev@vger.kernel.org
Cc: linux-crypto@vger.kernel.org
Cc: linux-block@vger.kernel.org
Cc: linux-fsdevel@vger.kernel.org
Cc: linux-media@vger.kernel.org
Cc: linux-arm-kernel@lists.infradead.org
Cc: loongarch@lists.linux.dev
Cc: linux-mips@vger.kernel.org
Cc: linuxppc-dev@lists.ozlabs.org
Cc: linux-mmc@vger.kernel.org
Cc: linux-parisc@vger.kernel.org

Jason A. Donenfeld (3):
  treewide: use get_random_u32_below() instead of deprecated function
  treewide: use get_random_u32_{above,below}() instead of manual loop
  treewide: use get_random_u32_inclusive() when possible

 arch/arm/kernel/process.c                     |  2 +-
 arch/arm64/kernel/process.c                   |  2 +-
 arch/loongarch/kernel/process.c               |  2 +-
 arch/loongarch/kernel/vdso.c                  |  2 +-
 arch/mips/kernel/process.c                    |  2 +-
 arch/mips/kernel/vdso.c                       |  2 +-
 arch/parisc/kernel/vdso.c                     |  2 +-
 arch/powerpc/crypto/crc-vpmsum_test.c         |  4 +-
 arch/powerpc/kernel/process.c                 |  2 +-
 arch/s390/kernel/process.c                    |  2 +-
 arch/s390/kernel/vdso.c                       |  2 +-
 arch/sparc/vdso/vma.c                         |  2 +-
 arch/um/kernel/process.c                      |  2 +-
 arch/x86/entry/vdso/vma.c                     |  2 +-
 arch/x86/kernel/module.c                      |  2 +-
 arch/x86/kernel/process.c                     |  2 +-
 arch/x86/mm/pat/cpa-test.c                    |  4 +-
 crypto/rsa-pkcs1pad.c                         |  2 +-
 crypto/testmgr.c                              | 86 +++++++++----------
 drivers/block/drbd/drbd_receiver.c            |  4 +-
 drivers/bus/mhi/host/internal.h               |  2 +-
 drivers/dma-buf/st-dma-fence-chain.c          |  6 +-
 .../gpu/drm/i915/gem/i915_gem_execbuffer.c    |  2 +-
 .../drm/i915/gt/intel_execlists_submission.c  |  2 +-
 drivers/gpu/drm/i915/intel_memory_region.c    |  4 +-
 drivers/infiniband/core/cma.c                 |  2 +-
 drivers/infiniband/hw/cxgb4/id_table.c        |  4 +-
 drivers/infiniband/hw/hns/hns_roce_ah.c       |  5 +-
 drivers/infiniband/ulp/rtrs/rtrs-clt.c        |  2 +-
 drivers/md/bcache/request.c                   |  2 +-
 drivers/media/common/v4l2-tpg/v4l2-tpg-core.c |  8 +-
 .../media/test-drivers/vidtv/vidtv_demod.c    |  8 +-
 .../test-drivers/vivid/vivid-kthread-cap.c    |  2 +-
 .../test-drivers/vivid/vivid-kthread-out.c    |  2 +-
 .../media/test-drivers/vivid/vivid-radio-rx.c |  4 +-
 .../media/test-drivers/vivid/vivid-sdr-cap.c  |  2 +-
 .../test-drivers/vivid/vivid-touch-cap.c      |  2 +-
 drivers/mmc/core/core.c                       |  4 +-
 drivers/mmc/host/dw_mmc.c                     |  2 +-
 drivers/mtd/nand/raw/nandsim.c                |  4 +-
 drivers/mtd/tests/mtd_nandecctest.c           | 10 +--
 drivers/mtd/tests/stresstest.c                |  8 +-
 drivers/mtd/ubi/debug.c                       |  2 +-
 drivers/mtd/ubi/debug.h                       |  6 +-
 drivers/net/ethernet/broadcom/cnic.c          |  2 +-
 .../chelsio/inline_crypto/chtls/chtls_io.c    |  4 +-
 drivers/net/phy/at803x.c                      |  2 +-
 drivers/net/team/team_mode_random.c           |  2 +-
 drivers/net/wireguard/selftest/allowedips.c   | 20 ++---
 drivers/net/wireguard/timers.c                |  4 +-
 .../broadcom/brcm80211/brcmfmac/p2p.c         |  2 +-
 .../net/wireless/intel/iwlwifi/mvm/mac-ctxt.c |  2 +-
 drivers/pci/p2pdma.c                          |  2 +-
 drivers/s390/scsi/zfcp_fc.c                   |  2 +-
 drivers/scsi/fcoe/fcoe_ctlr.c                 |  4 +-
 drivers/scsi/qedi/qedi_main.c                 |  2 +-
 drivers/scsi/scsi_debug.c                     |  6 +-
 fs/ceph/inode.c                               |  2 +-
 fs/ceph/mdsmap.c                              |  2 +-
 fs/ext2/ialloc.c                              |  2 +-
 fs/ext4/ialloc.c                              |  2 +-
 fs/ext4/mmp.c                                 |  8 +-
 fs/ext4/super.c                               |  5 +-
 fs/f2fs/gc.c                                  |  2 +-
 fs/f2fs/segment.c                             |  8 +-
 fs/ubifs/debug.c                              |  8 +-
 fs/ubifs/lpt_commit.c                         | 14 +--
 fs/ubifs/tnc_commit.c                         |  2 +-
 fs/xfs/libxfs/xfs_alloc.c                     |  2 +-
 fs/xfs/libxfs/xfs_ialloc.c                    |  2 +-
 fs/xfs/xfs_error.c                            |  2 +-
 include/linux/damon.h                         |  2 +-
 include/linux/nodemask.h                      |  2 +-
 kernel/bpf/core.c                             |  4 +-
 kernel/kcsan/selftest.c                       |  4 +-
 kernel/locking/test-ww_mutex.c                |  4 +-
 kernel/time/clocksource.c                     |  2 +-
 lib/fault-inject.c                            |  2 +-
 lib/find_bit_benchmark.c                      |  4 +-
 lib/kobject.c                                 |  2 +-
 lib/reed_solomon/test_rslib.c                 |  6 +-
 lib/sbitmap.c                                 |  4 +-
 lib/test-string_helpers.c                     |  2 +-
 lib/test_fprobe.c                             |  5 +-
 lib/test_hexdump.c                            | 10 +--
 lib/test_kprobes.c                            |  5 +-
 lib/test_list_sort.c                          |  2 +-
 lib/test_printf.c                             |  2 +-
 lib/test_rhashtable.c                         |  6 +-
 lib/test_vmalloc.c                            |  8 +-
 mm/kasan/kasan_test.c                         |  6 +-
 mm/kfence/core.c                              |  4 +-
 mm/kfence/kfence_test.c                       |  4 +-
 mm/slub.c                                     |  2 +-
 mm/swapfile.c                                 |  5 +-
 net/802/garp.c                                |  2 +-
 net/802/mrp.c                                 |  2 +-
 net/batman-adv/bat_iv_ogm.c                   |  4 +-
 net/batman-adv/bat_v_elp.c                    |  2 +-
 net/batman-adv/bat_v_ogm.c                    |  4 +-
 net/batman-adv/network-coding.c               |  2 +-
 net/bluetooth/mgmt.c                          |  5 +-
 net/can/j1939/socket.c                        |  2 +-
 net/can/j1939/transport.c                     |  2 +-
 net/ceph/mon_client.c                         |  2 +-
 net/ceph/osd_client.c                         |  2 +-
 net/core/neighbour.c                          |  4 +-
 net/core/pktgen.c                             | 37 ++++----
 net/core/stream.c                             |  2 +-
 net/ipv4/icmp.c                               |  2 +-
 net/ipv4/igmp.c                               |  6 +-
 net/ipv4/inet_connection_sock.c               |  2 +-
 net/ipv4/inet_hashtables.c                    |  2 +-
 net/ipv4/route.c                              |  4 +-
 net/ipv4/tcp_bbr.c                            |  2 +-
 net/ipv4/tcp_input.c                          |  3 +-
 net/ipv6/addrconf.c                           |  8 +-
 net/ipv6/mcast.c                              | 10 +--
 net/ipv6/output_core.c                        |  8 +-
 net/ipv6/route.c                              |  2 +-
 net/netfilter/ipvs/ip_vs_twos.c               |  4 +-
 net/netfilter/nf_conntrack_core.c             |  4 +-
 net/netfilter/nf_nat_helper.c                 |  2 +-
 net/netlink/af_netlink.c                      |  2 +-
 net/packet/af_packet.c                        |  4 +-
 net/sched/act_gact.c                          |  2 +-
 net/sched/act_sample.c                        |  2 +-
 net/sched/sch_choke.c                         |  2 +-
 net/sched/sch_netem.c                         |  4 +-
 net/sctp/socket.c                             |  2 +-
 net/sctp/transport.c                          |  2 +-
 net/sunrpc/cache.c                            |  2 +-
 net/sunrpc/xprtsock.c                         |  2 +-
 net/tipc/socket.c                             |  2 +-
 net/vmw_vsock/af_vsock.c                      |  3 +-
 net/xfrm/xfrm_state.c                         |  2 +-
 136 files changed, 286 insertions(+), 313 deletions(-)

-- 
2.38.1

^ permalink raw reply	[flat|nested] 22+ messages in thread

* [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop
  2022-11-17 20:29 ` [PATCH v3 0/3] convert tree to get_random_u32_{below,above,inclusive}() Jason A. Donenfeld
@ 2022-11-17 20:29   ` Jason A. Donenfeld
  2022-11-17 21:58     ` Kees Cook
  2022-11-17 20:29   ` [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible Jason A. Donenfeld
       [not found]   ` <20221117202906.2312482-2-Jason@zx2c4.com>
  2 siblings, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17 20:29 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

These cases were done with this Coccinelle:

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I > E);
+   I = get_random_u32_below(E + 1);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I >= E);
+   I = get_random_u32_below(E);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I < E);
+   I = get_random_u32_above(E - 1);

@@
expression E;
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I <= E);
+   I = get_random_u32_above(E);

@@
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (!I);
+   I = get_random_u32_above(0);

@@
identifier I;
@@
-   do {
      ... when != I
-     I = get_random_u32();
      ... when != I
-   } while (I == 0);
+   I = get_random_u32_above(0);

@@
expression E;
@@
- E + 1 + get_random_u32_below(U32_MAX - E)
+ get_random_u32_above(E)

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
---
 fs/ext4/mmp.c            | 8 +-------
 lib/test_fprobe.c        | 5 +----
 lib/test_kprobes.c       | 5 +----
 net/ipv6/output_core.c   | 8 +-------
 net/vmw_vsock/af_vsock.c | 3 +--
 5 files changed, 5 insertions(+), 24 deletions(-)

diff --git a/fs/ext4/mmp.c b/fs/ext4/mmp.c
index 588cb09c5291..4681fff6665f 100644
--- a/fs/ext4/mmp.c
+++ b/fs/ext4/mmp.c
@@ -262,13 +262,7 @@ void ext4_stop_mmpd(struct ext4_sb_info *sbi)
  */
 static unsigned int mmp_new_seq(void)
 {
-	u32 new_seq;
-
-	do {
-		new_seq = get_random_u32();
-	} while (new_seq > EXT4_MMP_SEQ_MAX);
-
-	return new_seq;
+	return get_random_u32_below(EXT4_MMP_SEQ_MAX + 1);
 }
 
 /*
diff --git a/lib/test_fprobe.c b/lib/test_fprobe.c
index e0381b3ec410..1fb56cf5e5ce 100644
--- a/lib/test_fprobe.c
+++ b/lib/test_fprobe.c
@@ -144,10 +144,7 @@ static unsigned long get_ftrace_location(void *func)
 
 static int fprobe_test_init(struct kunit *test)
 {
-	do {
-		rand1 = get_random_u32();
-	} while (rand1 <= div_factor);
-
+	rand1 = get_random_u32_above(div_factor);
 	target = fprobe_selftest_target;
 	target2 = fprobe_selftest_target2;
 	target_ip = get_ftrace_location(target);
diff --git a/lib/test_kprobes.c b/lib/test_kprobes.c
index eeb1d728d974..1c95e5719802 100644
--- a/lib/test_kprobes.c
+++ b/lib/test_kprobes.c
@@ -339,10 +339,7 @@ static int kprobes_test_init(struct kunit *test)
 	stacktrace_target = kprobe_stacktrace_target;
 	internal_target = kprobe_stacktrace_internal_target;
 	stacktrace_driver = kprobe_stacktrace_driver;
-
-	do {
-		rand1 = get_random_u32();
-	} while (rand1 <= div_factor);
+	rand1 = get_random_u32_above(div_factor);
 	return 0;
 }
 
diff --git a/net/ipv6/output_core.c b/net/ipv6/output_core.c
index 2685c3f15e9d..b5205311f372 100644
--- a/net/ipv6/output_core.c
+++ b/net/ipv6/output_core.c
@@ -15,13 +15,7 @@ static u32 __ipv6_select_ident(struct net *net,
 			       const struct in6_addr *dst,
 			       const struct in6_addr *src)
 {
-	u32 id;
-
-	do {
-		id = get_random_u32();
-	} while (!id);
-
-	return id;
+	return get_random_u32_above(0);
 }
 
 /* This function exists only for tap drivers that must support broken
diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c
index ff38c5a4d174..d593d5b6d4b1 100644
--- a/net/vmw_vsock/af_vsock.c
+++ b/net/vmw_vsock/af_vsock.c
@@ -626,8 +626,7 @@ static int __vsock_bind_connectible(struct vsock_sock *vsk,
 	struct sockaddr_vm new_addr;
 
 	if (!port)
-		port = LAST_RESERVED_PORT + 1 +
-			get_random_u32_below(U32_MAX - LAST_RESERVED_PORT);
+		port = get_random_u32_above(LAST_RESERVED_PORT);
 
 	vsock_addr_init(&new_addr, addr->svm_cid, addr->svm_port);
 
-- 
2.38.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible
  2022-11-17 20:29 ` [PATCH v3 0/3] convert tree to get_random_u32_{below,above,inclusive}() Jason A. Donenfeld
  2022-11-17 20:29   ` [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
@ 2022-11-17 20:29   ` Jason A. Donenfeld
  2022-11-17 21:57     ` Kees Cook
       [not found]   ` <20221117202906.2312482-2-Jason@zx2c4.com>
  2 siblings, 1 reply; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17 20:29 UTC (permalink / raw)
  To: linux-kernel, patches
  Cc: Jason A. Donenfeld, Kees Cook, Greg Kroah-Hartman,
	Jakub Kicinski, Russell King, Catalin Marinas,
	Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Theodore Ts'o,
	Andreas Dilger, Jaegeuk Kim, Richard Weinberger,
	Darrick J . Wong, SeongJae Park, Thomas Gleixner, Andrew Morton,
	Michael Ellerman, Helge Deller, netdev, linux-crypto,
	linux-block, linux-fsdevel, linux-media, linux-arm-kernel,
	loongarch, linux-mips, linuxppc-dev, linux-mmc, linux-parisc

These cases were done with this Coccinelle:

@@
expression H;
expression L;
@@
- (get_random_u32_below(H) + L)
+ get_random_u32_inclusive(L, H + L - 1)

@@
expression H;
expression L;
expression E;
@@
  get_random_u32_inclusive(L,
  H
- + E
- - E
  )

@@
expression H;
expression L;
expression E;
@@
  get_random_u32_inclusive(L,
  H
- - E
- + E
  )

@@
expression H;
expression L;
expression E;
expression F;
@@
  get_random_u32_inclusive(L,
  H
- - E
  + F
- + E
  )

@@
expression H;
expression L;
expression E;
expression F;
@@
  get_random_u32_inclusive(L,
  H
- + E
  + F
- - E
  )

And then subsequently cleaned up by hand, with several automatic cases
rejected if it didn't make sense contextually.

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> # for infiniband
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
---
 arch/x86/kernel/module.c                      |  2 +-
 crypto/rsa-pkcs1pad.c                         |  2 +-
 crypto/testmgr.c                              | 10 ++++----
 drivers/bus/mhi/host/internal.h               |  2 +-
 drivers/dma-buf/st-dma-fence-chain.c          |  2 +-
 drivers/infiniband/core/cma.c                 |  2 +-
 drivers/infiniband/hw/hns/hns_roce_ah.c       |  5 ++--
 drivers/mtd/nand/raw/nandsim.c                |  2 +-
 drivers/net/wireguard/selftest/allowedips.c   |  8 +++---
 .../broadcom/brcm80211/brcmfmac/p2p.c         |  2 +-
 .../net/wireless/intel/iwlwifi/mvm/mac-ctxt.c |  2 +-
 fs/f2fs/segment.c                             |  6 ++---
 kernel/kcsan/selftest.c                       |  2 +-
 lib/test_hexdump.c                            | 10 ++++----
 lib/test_printf.c                             |  2 +-
 lib/test_vmalloc.c                            |  6 ++---
 mm/kasan/kasan_test.c                         |  6 ++---
 mm/kfence/kfence_test.c                       |  2 +-
 mm/swapfile.c                                 |  5 ++--
 net/bluetooth/mgmt.c                          |  5 ++--
 net/core/pktgen.c                             | 25 ++++++++-----------
 net/ipv4/tcp_input.c                          |  2 +-
 net/ipv6/addrconf.c                           |  6 ++---
 net/netfilter/nf_nat_helper.c                 |  2 +-
 net/xfrm/xfrm_state.c                         |  2 +-
 25 files changed, 56 insertions(+), 64 deletions(-)

diff --git a/arch/x86/kernel/module.c b/arch/x86/kernel/module.c
index c09ae279ef32..a98687642dd0 100644
--- a/arch/x86/kernel/module.c
+++ b/arch/x86/kernel/module.c
@@ -53,7 +53,7 @@ static unsigned long int get_module_load_offset(void)
 		 */
 		if (module_load_offset == 0)
 			module_load_offset =
-				(get_random_u32_below(1024) + 1) * PAGE_SIZE;
+				get_random_u32_inclusive(1, 1024) * PAGE_SIZE;
 		mutex_unlock(&module_kaslr_mutex);
 	}
 	return module_load_offset;
diff --git a/crypto/rsa-pkcs1pad.c b/crypto/rsa-pkcs1pad.c
index 0f722f8f779b..e75728f87ce5 100644
--- a/crypto/rsa-pkcs1pad.c
+++ b/crypto/rsa-pkcs1pad.c
@@ -253,7 +253,7 @@ static int pkcs1pad_encrypt(struct akcipher_request *req)
 	ps_end = ctx->key_size - req->src_len - 2;
 	req_ctx->in_buf[0] = 0x02;
 	for (i = 1; i < ps_end; i++)
-		req_ctx->in_buf[i] = 1 + get_random_u32_below(255);
+		req_ctx->in_buf[i] = get_random_u32_inclusive(1, 255);
 	req_ctx->in_buf[ps_end] = 0x00;
 
 	pkcs1pad_sg_set_buf(req_ctx->in_sg, req_ctx->in_buf,
diff --git a/crypto/testmgr.c b/crypto/testmgr.c
index 079923d43ce2..e669acd2ebdd 100644
--- a/crypto/testmgr.c
+++ b/crypto/testmgr.c
@@ -962,11 +962,11 @@ static char *generate_random_sgl_divisions(struct test_sg_division *divs,
 		if (div == &divs[max_divs - 1] || get_random_u32_below(2) == 0)
 			this_len = remaining;
 		else
-			this_len = 1 + get_random_u32_below(remaining);
+			this_len = get_random_u32_inclusive(1, remaining);
 		div->proportion_of_total = this_len;
 
 		if (get_random_u32_below(4) == 0)
-			div->offset = (PAGE_SIZE - 128) + get_random_u32_below(128);
+			div->offset = get_random_u32_inclusive(PAGE_SIZE - 128, PAGE_SIZE - 1);
 		else if (get_random_u32_below(2) == 0)
 			div->offset = get_random_u32_below(32);
 		else
@@ -1094,12 +1094,12 @@ static void generate_random_testvec_config(struct testvec_config *cfg,
 	}
 
 	if (get_random_u32_below(2) == 0) {
-		cfg->iv_offset = 1 + get_random_u32_below(MAX_ALGAPI_ALIGNMASK);
+		cfg->iv_offset = get_random_u32_inclusive(1, MAX_ALGAPI_ALIGNMASK);
 		p += scnprintf(p, end - p, " iv_offset=%u", cfg->iv_offset);
 	}
 
 	if (get_random_u32_below(2) == 0) {
-		cfg->key_offset = 1 + get_random_u32_below(MAX_ALGAPI_ALIGNMASK);
+		cfg->key_offset = get_random_u32_inclusive(1, MAX_ALGAPI_ALIGNMASK);
 		p += scnprintf(p, end - p, " key_offset=%u", cfg->key_offset);
 	}
 
@@ -1653,7 +1653,7 @@ static void generate_random_hash_testvec(struct shash_desc *desc,
 	if (maxkeysize) {
 		vec->ksize = maxkeysize;
 		if (get_random_u32_below(4) == 0)
-			vec->ksize = 1 + get_random_u32_below(maxkeysize);
+			vec->ksize = get_random_u32_inclusive(1, maxkeysize);
 		generate_random_bytes((u8 *)vec->key, vec->ksize);
 
 		vec->setkey_error = crypto_shash_setkey(desc->tfm, vec->key,
diff --git a/drivers/bus/mhi/host/internal.h b/drivers/bus/mhi/host/internal.h
index c73621aabbd1..2e139e76de4c 100644
--- a/drivers/bus/mhi/host/internal.h
+++ b/drivers/bus/mhi/host/internal.h
@@ -129,7 +129,7 @@ enum mhi_pm_state {
 #define PRIMARY_CMD_RING				0
 #define MHI_DEV_WAKE_DB					127
 #define MHI_MAX_MTU					0xffff
-#define MHI_RANDOM_U32_NONZERO(bmsk)			(get_random_u32_below(bmsk) + 1)
+#define MHI_RANDOM_U32_NONZERO(bmsk)			(get_random_u32_inclusive(1, bmsk))
 
 enum mhi_er_type {
 	MHI_ER_TYPE_INVALID = 0x0,
diff --git a/drivers/dma-buf/st-dma-fence-chain.c b/drivers/dma-buf/st-dma-fence-chain.c
index 9fbad7317d9b..c0979c8049b5 100644
--- a/drivers/dma-buf/st-dma-fence-chain.c
+++ b/drivers/dma-buf/st-dma-fence-chain.c
@@ -400,7 +400,7 @@ static int __find_race(void *arg)
 		struct dma_fence *fence = dma_fence_get(data->fc.tail);
 		int seqno;
 
-		seqno = get_random_u32_below(data->fc.chain_length) + 1;
+		seqno = get_random_u32_inclusive(1, data->fc.chain_length);
 
 		err = dma_fence_chain_find_seqno(&fence, seqno);
 		if (err) {
diff --git a/drivers/infiniband/core/cma.c b/drivers/infiniband/core/cma.c
index dd1c703b10df..aacd6254df77 100644
--- a/drivers/infiniband/core/cma.c
+++ b/drivers/infiniband/core/cma.c
@@ -3807,7 +3807,7 @@ static int cma_alloc_any_port(enum rdma_ucm_port_space ps,
 
 	inet_get_local_port_range(net, &low, &high);
 	remaining = (high - low) + 1;
-	rover = get_random_u32_below(remaining) + low;
+	rover = get_random_u32_inclusive(low, remaining + low - 1);
 retry:
 	if (last_used_port != rover) {
 		struct rdma_bind_list *bind_list;
diff --git a/drivers/infiniband/hw/hns/hns_roce_ah.c b/drivers/infiniband/hw/hns/hns_roce_ah.c
index b37d2a81584d..e77fcc74f15c 100644
--- a/drivers/infiniband/hw/hns/hns_roce_ah.c
+++ b/drivers/infiniband/hw/hns/hns_roce_ah.c
@@ -41,9 +41,8 @@ static inline u16 get_ah_udp_sport(const struct rdma_ah_attr *ah_attr)
 	u16 sport;
 
 	if (!fl)
-		sport = get_random_u32_below(IB_ROCE_UDP_ENCAP_VALID_PORT_MAX +
-					     1 - IB_ROCE_UDP_ENCAP_VALID_PORT_MIN) +
-			IB_ROCE_UDP_ENCAP_VALID_PORT_MIN;
+		sport = get_random_u32_inclusive(IB_ROCE_UDP_ENCAP_VALID_PORT_MIN,
+						 IB_ROCE_UDP_ENCAP_VALID_PORT_MAX);
 	else
 		sport = rdma_flow_label_to_udp_sport(fl);
 
diff --git a/drivers/mtd/nand/raw/nandsim.c b/drivers/mtd/nand/raw/nandsim.c
index 274a31b93100..c21abf748948 100644
--- a/drivers/mtd/nand/raw/nandsim.c
+++ b/drivers/mtd/nand/raw/nandsim.c
@@ -1405,7 +1405,7 @@ static void ns_do_bit_flips(struct nandsim *ns, int num)
 	if (bitflips && get_random_u16() < (1 << 6)) {
 		int flips = 1;
 		if (bitflips > 1)
-			flips = get_random_u32_below(bitflips) + 1;
+			flips = get_random_u32_inclusive(1, bitflips);
 		while (flips--) {
 			int pos = get_random_u32_below(num * 8);
 			ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
diff --git a/drivers/net/wireguard/selftest/allowedips.c b/drivers/net/wireguard/selftest/allowedips.c
index 78a916f30c82..78ebe2892a78 100644
--- a/drivers/net/wireguard/selftest/allowedips.c
+++ b/drivers/net/wireguard/selftest/allowedips.c
@@ -285,7 +285,7 @@ static __init bool randomized_test(void)
 
 	for (i = 0; i < NUM_RAND_ROUTES; ++i) {
 		get_random_bytes(ip, 4);
-		cidr = get_random_u32_below(32) + 1;
+		cidr = get_random_u32_inclusive(1, 32);
 		peer = peers[get_random_u32_below(NUM_PEERS)];
 		if (wg_allowedips_insert_v4(&t, (struct in_addr *)ip, cidr,
 					    peer, &mutex) < 0) {
@@ -311,7 +311,7 @@ static __init bool randomized_test(void)
 				mutated[k] = (mutated[k] & mutate_mask[k]) |
 					     (~mutate_mask[k] &
 					      get_random_u8());
-			cidr = get_random_u32_below(32) + 1;
+			cidr = get_random_u32_inclusive(1, 32);
 			peer = peers[get_random_u32_below(NUM_PEERS)];
 			if (wg_allowedips_insert_v4(&t,
 						    (struct in_addr *)mutated,
@@ -329,7 +329,7 @@ static __init bool randomized_test(void)
 
 	for (i = 0; i < NUM_RAND_ROUTES; ++i) {
 		get_random_bytes(ip, 16);
-		cidr = get_random_u32_below(128) + 1;
+		cidr = get_random_u32_inclusive(1, 128);
 		peer = peers[get_random_u32_below(NUM_PEERS)];
 		if (wg_allowedips_insert_v6(&t, (struct in6_addr *)ip, cidr,
 					    peer, &mutex) < 0) {
@@ -355,7 +355,7 @@ static __init bool randomized_test(void)
 				mutated[k] = (mutated[k] & mutate_mask[k]) |
 					     (~mutate_mask[k] &
 					      get_random_u8());
-			cidr = get_random_u32_below(128) + 1;
+			cidr = get_random_u32_inclusive(1, 128);
 			peer = peers[get_random_u32_below(NUM_PEERS)];
 			if (wg_allowedips_insert_v6(&t,
 						    (struct in6_addr *)mutated,
diff --git a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
index 23c971b77965..c704ca752138 100644
--- a/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
+++ b/drivers/net/wireless/broadcom/brcm80211/brcmfmac/p2p.c
@@ -1128,7 +1128,7 @@ static void brcmf_p2p_afx_handler(struct work_struct *work)
 	if (afx_hdl->is_listen && afx_hdl->my_listen_chan)
 		/* 100ms ~ 300ms */
 		err = brcmf_p2p_discover_listen(p2p, afx_hdl->my_listen_chan,
-						100 * (1 + get_random_u32_below(3)));
+						100 * get_random_u32_inclusive(1, 3));
 	else
 		err = brcmf_p2p_act_frm_search(p2p, afx_hdl->peer_listen_chan);
 
diff --git a/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c b/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
index 1696fbf1009a..3a7a44bb3c60 100644
--- a/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
+++ b/drivers/net/wireless/intel/iwlwifi/mvm/mac-ctxt.c
@@ -1099,7 +1099,7 @@ static void iwl_mvm_mac_ctxt_cmd_fill_ap(struct iwl_mvm *mvm,
 			iwl_mvm_mac_ap_iterator, &data);
 
 		if (data.beacon_device_ts) {
-			u32 rand = get_random_u32_below(64 - 36) + 36;
+			u32 rand = get_random_u32_inclusive(36, 63);
 			mvmvif->ap_beacon_time = data.beacon_device_ts +
 				ieee80211_tu_to_usec(data.beacon_int * rand /
 						     100);
diff --git a/fs/f2fs/segment.c b/fs/f2fs/segment.c
index 334415d946f8..b304692c0cf5 100644
--- a/fs/f2fs/segment.c
+++ b/fs/f2fs/segment.c
@@ -2588,7 +2588,7 @@ static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
 	curseg->alloc_type = LFS;
 	if (F2FS_OPTION(sbi).fs_mode == FS_MODE_FRAGMENT_BLK)
 		curseg->fragment_remained_chunk =
-				get_random_u32_below(sbi->max_fragment_chunk) + 1;
+				get_random_u32_inclusive(1, sbi->max_fragment_chunk);
 }
 
 static int __next_free_blkoff(struct f2fs_sb_info *sbi,
@@ -2625,9 +2625,9 @@ static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
 			/* To allocate block chunks in different sizes, use random number */
 			if (--seg->fragment_remained_chunk <= 0) {
 				seg->fragment_remained_chunk =
-				   get_random_u32_below(sbi->max_fragment_chunk) + 1;
+				   get_random_u32_inclusive(1, sbi->max_fragment_chunk);
 				seg->next_blkoff +=
-				   get_random_u32_below(sbi->max_fragment_hole) + 1;
+				   get_random_u32_inclusive(1, sbi->max_fragment_hole);
 			}
 		}
 	}
diff --git a/kernel/kcsan/selftest.c b/kernel/kcsan/selftest.c
index 7b619f16a492..8679322450f2 100644
--- a/kernel/kcsan/selftest.c
+++ b/kernel/kcsan/selftest.c
@@ -31,7 +31,7 @@ static bool __init test_encode_decode(void)
 	int i;
 
 	for (i = 0; i < ITERS_PER_TEST; ++i) {
-		size_t size = get_random_u32_below(MAX_ENCODABLE_SIZE) + 1;
+		size_t size = get_random_u32_inclusive(1, MAX_ENCODABLE_SIZE);
 		bool is_write = !!get_random_u32_below(2);
 		unsigned long verif_masked_addr;
 		long encoded_watchpoint;
diff --git a/lib/test_hexdump.c b/lib/test_hexdump.c
index efc50fd30a44..bcfff9cbc6dd 100644
--- a/lib/test_hexdump.c
+++ b/lib/test_hexdump.c
@@ -149,7 +149,7 @@ static void __init test_hexdump(size_t len, int rowsize, int groupsize,
 static void __init test_hexdump_set(int rowsize, bool ascii)
 {
 	size_t d = min_t(size_t, sizeof(data_b), rowsize);
-	size_t len = get_random_u32_below(d) + 1;
+	size_t len = get_random_u32_inclusive(1, d);
 
 	test_hexdump(len, rowsize, 4, ascii);
 	test_hexdump(len, rowsize, 2, ascii);
@@ -208,11 +208,11 @@ static void __init test_hexdump_overflow(size_t buflen, size_t len,
 static void __init test_hexdump_overflow_set(size_t buflen, bool ascii)
 {
 	unsigned int i = 0;
-	int rs = (get_random_u32_below(2) + 1) * 16;
+	int rs = get_random_u32_inclusive(1, 2) * 16;
 
 	do {
 		int gs = 1 << i;
-		size_t len = get_random_u32_below(rs) + gs;
+		size_t len = get_random_u32_inclusive(gs, rs + gs - 1);
 
 		test_hexdump_overflow(buflen, rounddown(len, gs), rs, gs, ascii);
 	} while (i++ < 3);
@@ -223,11 +223,11 @@ static int __init test_hexdump_init(void)
 	unsigned int i;
 	int rowsize;
 
-	rowsize = (get_random_u32_below(2) + 1) * 16;
+	rowsize = get_random_u32_inclusive(1, 2) * 16;
 	for (i = 0; i < 16; i++)
 		test_hexdump_set(rowsize, false);
 
-	rowsize = (get_random_u32_below(2) + 1) * 16;
+	rowsize = get_random_u32_inclusive(1, 2) * 16;
 	for (i = 0; i < 16; i++)
 		test_hexdump_set(rowsize, true);
 
diff --git a/lib/test_printf.c b/lib/test_printf.c
index 6d10187eddac..f098914a48d5 100644
--- a/lib/test_printf.c
+++ b/lib/test_printf.c
@@ -126,7 +126,7 @@ __test(const char *expect, int elen, const char *fmt, ...)
 	 * be able to print it as expected.
 	 */
 	failed_tests += do_test(BUF_SIZE, expect, elen, fmt, ap);
-	rand = 1 + get_random_u32_below(elen + 1);
+	rand = get_random_u32_inclusive(1, elen + 1);
 	/* Since elen < BUF_SIZE, we have 1 <= rand <= BUF_SIZE. */
 	failed_tests += do_test(rand, expect, elen, fmt, ap);
 	failed_tests += do_test(0, expect, elen, fmt, ap);
diff --git a/lib/test_vmalloc.c b/lib/test_vmalloc.c
index 104f09ea5fcc..f90d2c27675b 100644
--- a/lib/test_vmalloc.c
+++ b/lib/test_vmalloc.c
@@ -151,7 +151,7 @@ static int random_size_alloc_test(void)
 	int i;
 
 	for (i = 0; i < test_loop_count; i++) {
-		n = get_random_u32_below(100) + 1;
+		n = get_random_u32_inclusive(1, 100);
 		p = vmalloc(n * PAGE_SIZE);
 
 		if (!p)
@@ -291,12 +291,12 @@ pcpu_alloc_test(void)
 		return -1;
 
 	for (i = 0; i < 35000; i++) {
-		size = get_random_u32_below(PAGE_SIZE / 4) + 1;
+		size = get_random_u32_inclusive(1, PAGE_SIZE / 4);
 
 		/*
 		 * Maximum PAGE_SIZE
 		 */
-		align = 1 << (get_random_u32_below(11) + 1);
+		align = 1 << get_random_u32_inclusive(1, 11);
 
 		pcpu[i] = __alloc_percpu(size, align);
 		if (!pcpu[i])
diff --git a/mm/kasan/kasan_test.c b/mm/kasan/kasan_test.c
index 640f9c7f8e44..54181eba3e24 100644
--- a/mm/kasan/kasan_test.c
+++ b/mm/kasan/kasan_test.c
@@ -1299,7 +1299,7 @@ static void match_all_not_assigned(struct kunit *test)
 	KASAN_TEST_NEEDS_CONFIG_OFF(test, CONFIG_KASAN_GENERIC);
 
 	for (i = 0; i < 256; i++) {
-		size = get_random_u32_below(1024) + 1;
+		size = get_random_u32_inclusive(1, 1024);
 		ptr = kmalloc(size, GFP_KERNEL);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
 		KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
@@ -1308,7 +1308,7 @@ static void match_all_not_assigned(struct kunit *test)
 	}
 
 	for (i = 0; i < 256; i++) {
-		order = get_random_u32_below(4) + 1;
+		order = get_random_u32_inclusive(1, 4);
 		pages = alloc_pages(GFP_KERNEL, order);
 		ptr = page_address(pages);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
@@ -1321,7 +1321,7 @@ static void match_all_not_assigned(struct kunit *test)
 		return;
 
 	for (i = 0; i < 256; i++) {
-		size = get_random_u32_below(1024) + 1;
+		size = get_random_u32_inclusive(1, 1024);
 		ptr = vmalloc(size);
 		KUNIT_ASSERT_NOT_ERR_OR_NULL(test, ptr);
 		KUNIT_EXPECT_GE(test, (u8)get_tag(ptr), (u8)KASAN_TAG_MIN);
diff --git a/mm/kfence/kfence_test.c b/mm/kfence/kfence_test.c
index 20028c179796..b5d66a69200d 100644
--- a/mm/kfence/kfence_test.c
+++ b/mm/kfence/kfence_test.c
@@ -532,7 +532,7 @@ static void test_free_bulk(struct kunit *test)
 	int iter;
 
 	for (iter = 0; iter < 5; iter++) {
-		const size_t size = setup_test_cache(test, 8 + get_random_u32_below(300),
+		const size_t size = setup_test_cache(test, get_random_u32_inclusive(8, 307),
 						     0, (iter & 1) ? ctor_set_x : NULL);
 		void *objects[] = {
 			test_alloc(test, size, GFP_KERNEL, ALLOCATE_RIGHT),
diff --git a/mm/swapfile.c b/mm/swapfile.c
index e9318305a24a..4ee31056d3f8 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -772,8 +772,7 @@ static void set_cluster_next(struct swap_info_struct *si, unsigned long next)
 		/* No free swap slots available */
 		if (si->highest_bit <= si->lowest_bit)
 			return;
-		next = si->lowest_bit +
-			get_random_u32_below(si->highest_bit - si->lowest_bit + 1);
+		next = get_random_u32_inclusive(si->lowest_bit, si->highest_bit);
 		next = ALIGN_DOWN(next, SWAP_ADDRESS_SPACE_PAGES);
 		next = max_t(unsigned int, next, si->lowest_bit);
 	}
@@ -3089,7 +3088,7 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)
 		 */
 		for_each_possible_cpu(cpu) {
 			per_cpu(*p->cluster_next_cpu, cpu) =
-				1 + get_random_u32_below(p->highest_bit);
+				get_random_u32_inclusive(1, p->highest_bit);
 		}
 		nr_cluster = DIV_ROUND_UP(maxpages, SWAPFILE_CLUSTER);
 
diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c
index b2f9679066c4..81ce668b0b77 100644
--- a/net/bluetooth/mgmt.c
+++ b/net/bluetooth/mgmt.c
@@ -7373,9 +7373,8 @@ static int get_conn_info(struct sock *sk, struct hci_dev *hdev, void *data,
 	/* To avoid client trying to guess when to poll again for information we
 	 * calculate conn info age as random value between min/max set in hdev.
 	 */
-	conn_info_age = hdev->conn_info_min_age +
-			get_random_u32_below(hdev->conn_info_max_age -
-					     hdev->conn_info_min_age);
+	conn_info_age = get_random_u32_inclusive(hdev->conn_info_min_age,
+						 hdev->conn_info_max_age - 1);
 
 	/* Query controller to refresh cached values if they are too old or were
 	 * never read.
diff --git a/net/core/pktgen.c b/net/core/pktgen.c
index 95da2ddc1c20..760238196db1 100644
--- a/net/core/pktgen.c
+++ b/net/core/pktgen.c
@@ -2380,9 +2380,8 @@ static void set_cur_queue_map(struct pktgen_dev *pkt_dev)
 	else if (pkt_dev->queue_map_min <= pkt_dev->queue_map_max) {
 		__u16 t;
 		if (pkt_dev->flags & F_QUEUE_MAP_RND) {
-			t = get_random_u32_below(pkt_dev->queue_map_max -
-						 pkt_dev->queue_map_min + 1) +
-			    pkt_dev->queue_map_min;
+			t = get_random_u32_inclusive(pkt_dev->queue_map_min,
+						     pkt_dev->queue_map_max);
 		} else {
 			t = pkt_dev->cur_queue_map + 1;
 			if (t > pkt_dev->queue_map_max)
@@ -2478,9 +2477,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 
 	if (pkt_dev->udp_src_min < pkt_dev->udp_src_max) {
 		if (pkt_dev->flags & F_UDPSRC_RND)
-			pkt_dev->cur_udp_src = get_random_u32_below(
-				pkt_dev->udp_src_max - pkt_dev->udp_src_min) +
-				pkt_dev->udp_src_min;
+			pkt_dev->cur_udp_src = get_random_u32_inclusive(pkt_dev->udp_src_min,
+									pkt_dev->udp_src_max - 1);
 
 		else {
 			pkt_dev->cur_udp_src++;
@@ -2491,9 +2489,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 
 	if (pkt_dev->udp_dst_min < pkt_dev->udp_dst_max) {
 		if (pkt_dev->flags & F_UDPDST_RND) {
-			pkt_dev->cur_udp_dst = get_random_u32_below(
-				pkt_dev->udp_dst_max - pkt_dev->udp_dst_min) +
-				pkt_dev->udp_dst_min;
+			pkt_dev->cur_udp_dst = get_random_u32_inclusive(pkt_dev->udp_dst_min,
+									pkt_dev->udp_dst_max - 1);
 		} else {
 			pkt_dev->cur_udp_dst++;
 			if (pkt_dev->cur_udp_dst >= pkt_dev->udp_dst_max)
@@ -2508,7 +2505,7 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 		if (imn < imx) {
 			__u32 t;
 			if (pkt_dev->flags & F_IPSRC_RND)
-				t = get_random_u32_below(imx - imn) + imn;
+				t = get_random_u32_inclusive(imn, imx - 1);
 			else {
 				t = ntohl(pkt_dev->cur_saddr);
 				t++;
@@ -2530,8 +2527,7 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 				if (pkt_dev->flags & F_IPDST_RND) {
 
 					do {
-						t = get_random_u32_below(imx - imn) +
-						    imn;
+						t = get_random_u32_inclusive(imn, imx - 1);
 						s = htonl(t);
 					} while (ipv4_is_loopback(s) ||
 						ipv4_is_multicast(s) ||
@@ -2578,9 +2574,8 @@ static void mod_cur_headers(struct pktgen_dev *pkt_dev)
 	if (pkt_dev->min_pkt_size < pkt_dev->max_pkt_size) {
 		__u32 t;
 		if (pkt_dev->flags & F_TXSIZE_RND) {
-			t = get_random_u32_below(pkt_dev->max_pkt_size -
-						 pkt_dev->min_pkt_size) +
-			    pkt_dev->min_pkt_size;
+			t = get_random_u32_inclusive(pkt_dev->min_pkt_size,
+						     pkt_dev->max_pkt_size - 1);
 		} else {
 			t = pkt_dev->cur_pkt_size + 1;
 			if (t > pkt_dev->max_pkt_size)
diff --git a/net/ipv4/tcp_input.c b/net/ipv4/tcp_input.c
index 3b076e5ba932..23cf418efe4f 100644
--- a/net/ipv4/tcp_input.c
+++ b/net/ipv4/tcp_input.c
@@ -3647,7 +3647,7 @@ static void tcp_send_challenge_ack(struct sock *sk)
 
 		WRITE_ONCE(net->ipv4.tcp_challenge_timestamp, now);
 		WRITE_ONCE(net->ipv4.tcp_challenge_count,
-			   half + get_random_u32_below(ack_limit));
+			   get_random_u32_inclusive(half, ack_limit + half - 1));
 	}
 	count = READ_ONCE(net->ipv4.tcp_challenge_count);
 	if (count > 0) {
diff --git a/net/ipv6/addrconf.c b/net/ipv6/addrconf.c
index daf89a2eb492..d720f6f5de3f 100644
--- a/net/ipv6/addrconf.c
+++ b/net/ipv6/addrconf.c
@@ -104,7 +104,7 @@ static inline u32 cstamp_delta(unsigned long cstamp)
 static inline s32 rfc3315_s14_backoff_init(s32 irt)
 {
 	/* multiply 'initial retransmission time' by 0.9 .. 1.1 */
-	u64 tmp = (900000 + get_random_u32_below(200001)) * (u64)irt;
+	u64 tmp = get_random_u32_inclusive(900000, 1100000) * (u64)irt;
 	do_div(tmp, 1000000);
 	return (s32)tmp;
 }
@@ -112,11 +112,11 @@ static inline s32 rfc3315_s14_backoff_init(s32 irt)
 static inline s32 rfc3315_s14_backoff_update(s32 rt, s32 mrt)
 {
 	/* multiply 'retransmission timeout' by 1.9 .. 2.1 */
-	u64 tmp = (1900000 + get_random_u32_below(200001)) * (u64)rt;
+	u64 tmp = get_random_u32_inclusive(1900000, 2100000) * (u64)rt;
 	do_div(tmp, 1000000);
 	if ((s32)tmp > mrt) {
 		/* multiply 'maximum retransmission time' by 0.9 .. 1.1 */
-		tmp = (900000 + get_random_u32_below(200001)) * (u64)mrt;
+		tmp = get_random_u32_inclusive(900000, 1100000) * (u64)mrt;
 		do_div(tmp, 1000000);
 	}
 	return (s32)tmp;
diff --git a/net/netfilter/nf_nat_helper.c b/net/netfilter/nf_nat_helper.c
index bf591e6af005..67e56456615f 100644
--- a/net/netfilter/nf_nat_helper.c
+++ b/net/netfilter/nf_nat_helper.c
@@ -223,7 +223,7 @@ u16 nf_nat_exp_find_port(struct nf_conntrack_expect *exp, u16 port)
 		if (res != -EBUSY || (--attempts_left < 0))
 			break;
 
-		port = min + get_random_u32_below(range);
+		port = get_random_u32_inclusive(min, range + min - 1);
 	}
 
 	return 0;
diff --git a/net/xfrm/xfrm_state.c b/net/xfrm/xfrm_state.c
index 40f831854774..d63a3644ee1a 100644
--- a/net/xfrm/xfrm_state.c
+++ b/net/xfrm/xfrm_state.c
@@ -2072,7 +2072,7 @@ int xfrm_alloc_spi(struct xfrm_state *x, u32 low, u32 high)
 	} else {
 		u32 spi = 0;
 		for (h = 0; h < high-low+1; h++) {
-			spi = low + get_random_u32_below(high - low + 1);
+			spi = get_random_u32_inclusive(low, high);
 			x0 = xfrm_state_lookup(net, mark, &x->id.daddr, htonl(spi), x->id.proto, x->props.family);
 			if (x0 == NULL) {
 				newspi = htonl(spi);
-- 
2.38.1


^ permalink raw reply related	[flat|nested] 22+ messages in thread

* Re: [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible
  2022-11-17 20:29   ` [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible Jason A. Donenfeld
@ 2022-11-17 21:57     ` Kees Cook
  2022-11-17 22:10       ` Jason A. Donenfeld
  0 siblings, 1 reply; 22+ messages in thread
From: Kees Cook @ 2022-11-17 21:57 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc

On Thu, Nov 17, 2022 at 09:29:06PM +0100, Jason A. Donenfeld wrote:
> These cases were done with this Coccinelle:
> 
> @@
> expression H;
> expression L;
> @@
> - (get_random_u32_below(H) + L)
> + get_random_u32_inclusive(L, H + L - 1)
> 
> @@
> expression H;
> expression L;
> expression E;
> @@
>   get_random_u32_inclusive(L,
>   H
> - + E
> - - E
>   )
> 
> @@
> expression H;
> expression L;
> expression E;
> @@
>   get_random_u32_inclusive(L,
>   H
> - - E
> - + E
>   )
> 
> @@
> expression H;
> expression L;
> expression E;
> expression F;
> @@
>   get_random_u32_inclusive(L,
>   H
> - - E
>   + F
> - + E
>   )
> 
> @@
> expression H;
> expression L;
> expression E;
> expression F;
> @@
>   get_random_u32_inclusive(L,
>   H
> - + E
>   + F
> - - E
>   )
> 
> And then subsequently cleaned up by hand, with several automatic cases
> rejected if it didn't make sense contextually.
> 
> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
> Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> # for infiniband
> Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
> ---
>  arch/x86/kernel/module.c                      |  2 +-
>  crypto/rsa-pkcs1pad.c                         |  2 +-
>  crypto/testmgr.c                              | 10 ++++----
>  drivers/bus/mhi/host/internal.h               |  2 +-
>  drivers/dma-buf/st-dma-fence-chain.c          |  2 +-
>  drivers/infiniband/core/cma.c                 |  2 +-
>  drivers/infiniband/hw/hns/hns_roce_ah.c       |  5 ++--
>  drivers/mtd/nand/raw/nandsim.c                |  2 +-
>  drivers/net/wireguard/selftest/allowedips.c   |  8 +++---
>  .../broadcom/brcm80211/brcmfmac/p2p.c         |  2 +-
>  .../net/wireless/intel/iwlwifi/mvm/mac-ctxt.c |  2 +-
>  fs/f2fs/segment.c                             |  6 ++---
>  kernel/kcsan/selftest.c                       |  2 +-
>  lib/test_hexdump.c                            | 10 ++++----
>  lib/test_printf.c                             |  2 +-
>  lib/test_vmalloc.c                            |  6 ++---
>  mm/kasan/kasan_test.c                         |  6 ++---
>  mm/kfence/kfence_test.c                       |  2 +-
>  mm/swapfile.c                                 |  5 ++--
>  net/bluetooth/mgmt.c                          |  5 ++--
>  net/core/pktgen.c                             | 25 ++++++++-----------
>  net/ipv4/tcp_input.c                          |  2 +-
>  net/ipv6/addrconf.c                           |  6 ++---
>  net/netfilter/nf_nat_helper.c                 |  2 +-
>  net/xfrm/xfrm_state.c                         |  2 +-
>  25 files changed, 56 insertions(+), 64 deletions(-)

Even the diffstat agrees this is a nice clean-up. :)

Reviewed-by: Kees Cook <keescook@chromium.org>

The only comment I have is that maybe these cases can just be left as-is
with _below()?

> -             size_t len = get_random_u32_below(rs) + gs;
> +             size_t len = get_random_u32_inclusive(gs, rs + gs - 1);

It seems like writing it in the form of base plus [0, limit) is clearer?

		size_t len = gs + get_random_u32_below(rs);

But there is only a handful, so *shrug*

All the others are much cleaner rewritten as _inclusive().

-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop
  2022-11-17 20:29   ` [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
@ 2022-11-17 21:58     ` Kees Cook
  0 siblings, 0 replies; 22+ messages in thread
From: Kees Cook @ 2022-11-17 21:58 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc

On Thu, Nov 17, 2022 at 09:29:05PM +0100, Jason A. Donenfeld wrote:
> These cases were done with this Coccinelle:
> 
> @@
> expression E;
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (I > E);
> +   I = get_random_u32_below(E + 1);
> 
> @@
> expression E;
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (I >= E);
> +   I = get_random_u32_below(E);
> 
> @@
> expression E;
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (I < E);
> +   I = get_random_u32_above(E - 1);
> 
> @@
> expression E;
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (I <= E);
> +   I = get_random_u32_above(E);
> 
> @@
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (!I);
> +   I = get_random_u32_above(0);
> 
> @@
> identifier I;
> @@
> -   do {
>       ... when != I
> -     I = get_random_u32();
>       ... when != I
> -   } while (I == 0);
> +   I = get_random_u32_above(0);
> 
> @@
> expression E;
> @@
> - E + 1 + get_random_u32_below(U32_MAX - E)
> + get_random_u32_above(E)
> 
> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
> Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>

Reviewed-by: Kees Cook <keescook@chromium.org>

-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v3 1/3] treewide: use get_random_u32_below() instead of deprecated function
       [not found]   ` <20221117202906.2312482-2-Jason@zx2c4.com>
@ 2022-11-17 21:59     ` Kees Cook
  0 siblings, 0 replies; 22+ messages in thread
From: Kees Cook @ 2022-11-17 21:59 UTC (permalink / raw)
  To: Jason A. Donenfeld
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, Russell King, Ulf Hansson

On Thu, Nov 17, 2022 at 09:29:04PM +0100, Jason A. Donenfeld wrote:
> This is a simple mechanical transformation done by:
> 
> @@
> expression E;
> @@
> - prandom_u32_max
> + get_random_u32_below
>   (E)
> 
> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
> Acked-by: Darrick J. Wong <djwong@kernel.org> # for xfs
> Reviewed-by: SeongJae Park <sj@kernel.org> # for damon
> Reviewed-by: Jason Gunthorpe <jgg@nvidia.com> # for infiniband
> Reviewed-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk> # for arm
> Acked-by: Ulf Hansson <ulf.hansson@linaro.org> # for mmc
> Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>

Reviewed-by: Kees Cook <keescook@chromium.org>

-- 
Kees Cook

^ permalink raw reply	[flat|nested] 22+ messages in thread

* Re: [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible
  2022-11-17 21:57     ` Kees Cook
@ 2022-11-17 22:10       ` Jason A. Donenfeld
  0 siblings, 0 replies; 22+ messages in thread
From: Jason A. Donenfeld @ 2022-11-17 22:10 UTC (permalink / raw)
  To: Kees Cook
  Cc: linux-kernel, patches, Greg Kroah-Hartman, Jakub Kicinski,
	Russell King, Catalin Marinas, Thomas Bogendoerfer,
	Heiko Carstens, Herbert Xu, Christoph Böhmwalder,
	Jani Nikula, Jason Gunthorpe, Sakari Ailus, Martin K . Petersen,
	Theodore Ts'o, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc

On Thu, Nov 17, 2022 at 01:57:13PM -0800, Kees Cook wrote:
> The only comment I have is that maybe these cases can just be left as-is
> with _below()?
> 
> > -             size_t len = get_random_u32_below(rs) + gs;
> > +             size_t len = get_random_u32_inclusive(gs, rs + gs - 1);
> 
> It seems like writing it in the form of base plus [0, limit) is clearer?
> 
> 		size_t len = gs + get_random_u32_below(rs);
> 
> But there is only a handful, so *shrug*

Okay, I'll drop that one.

Jason

^ permalink raw reply	[flat|nested] 22+ messages in thread

* RE: [PATCH v2 3/3] treewide: use get_random_u32_between() when possible
  2022-11-17 15:42               ` Theodore Ts'o
  2022-11-17 16:19                 ` Jason A. Donenfeld
@ 2022-11-17 22:15                 ` David Laight
  1 sibling, 0 replies; 22+ messages in thread
From: David Laight @ 2022-11-17 22:15 UTC (permalink / raw)
  To: 'Theodore Ts'o', Kees Cook
  Cc: Jason A. Donenfeld, Kees Cook, linux-kernel, patches,
	Greg Kroah-Hartman, Jakub Kicinski, Russell King,
	Catalin Marinas, Thomas Bogendoerfer, Heiko Carstens, Herbert Xu,
	Christoph Böhmwalder, Jani Nikula, Jason Gunthorpe,
	Sakari Ailus, Martin K . Petersen, Andreas Dilger, Jaegeuk Kim,
	Richard Weinberger, Darrick J . Wong, SeongJae Park,
	Thomas Gleixner, Andrew Morton, Michael Ellerman, Helge Deller,
	netdev, linux-crypto, linux-block, linux-fsdevel, linux-media,
	linux-arm-kernel, loongarch, linux-mips, linuxppc-dev, linux-mmc,
	linux-parisc, ydroneaud

From: Theodore Ts'o
> Sent: 17 November 2022 15:43
...
> The problem with "between", "ranged", "spanning" is that they don't
> tell the reader whether we're dealing with an "open interval" or a
> "closed interval".  They are just different ways of saying that it's a
> range between, say, 0 and 20.  But it doesn't tell you whether it
> includes 0 or 20 or not.
> 
> The only way I can see for making it ambiguous is either to use the
> terminology "closed interval" or "inclusive".  And "open" and "closed"
> can have other meanings, so get_random_u32_inclusive() is going to be
> less confusing than get_random_u32_closed().

It has to be said that removing the extra function and requiring
the callers use 'base + get_random_below(high [+1] - base)' is
likely to be the only way to succinctly make the code readable
and understandable.

Otherwise readers either have to look up another function to see
what it does or waste variable brain cells on more trivia.

	David

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


^ permalink raw reply	[flat|nested] 22+ messages in thread

end of thread, other threads:[~2022-11-17 22:16 UTC | newest]

Thread overview: 22+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-11-14 16:45 [PATCH v2 0/3] convert tree to get_random_u32_{below,above,between}() Jason A. Donenfeld
2022-11-14 16:45 ` [PATCH v2 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
2022-11-14 16:45 ` [PATCH v2 3/3] treewide: use get_random_u32_between() when possible Jason A. Donenfeld
2022-11-16 22:43   ` Kees Cook
2022-11-16 23:55     ` Jason A. Donenfeld
2022-11-17  0:03       ` Jason A. Donenfeld
2022-11-17  0:31         ` Kees Cook
2022-11-17  0:43           ` Jason A. Donenfeld
2022-11-17  0:47             ` Kees Cook
2022-11-17 15:42               ` Theodore Ts'o
2022-11-17 16:19                 ` Jason A. Donenfeld
2022-11-17 22:15                 ` David Laight
2022-11-17  2:05       ` Jason A. Donenfeld
2022-11-17 10:32         ` Russell King (Oracle)
     [not found] ` <20221114164558.1180362-2-Jason@zx2c4.com>
2022-11-14 17:35   ` [PATCH v2 1/3] treewide: use get_random_u32_below() instead of deprecated function Russell King (Oracle)
2022-11-17 20:29 ` [PATCH v3 0/3] convert tree to get_random_u32_{below,above,inclusive}() Jason A. Donenfeld
2022-11-17 20:29   ` [PATCH v3 2/3] treewide: use get_random_u32_{above,below}() instead of manual loop Jason A. Donenfeld
2022-11-17 21:58     ` Kees Cook
2022-11-17 20:29   ` [PATCH v3 3/3] treewide: use get_random_u32_inclusive() when possible Jason A. Donenfeld
2022-11-17 21:57     ` Kees Cook
2022-11-17 22:10       ` Jason A. Donenfeld
     [not found]   ` <20221117202906.2312482-2-Jason@zx2c4.com>
2022-11-17 21:59     ` [PATCH v3 1/3] treewide: use get_random_u32_below() instead of deprecated function Kees Cook

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).