]> git.itanic.dy.fi Git - linux-stable/commitdiff
treewide: use get_random_{u8,u16}() when possible, part 1
authorJason A. Donenfeld <Jason@zx2c4.com>
Wed, 5 Oct 2022 15:23:53 +0000 (17:23 +0200)
committerJason A. Donenfeld <Jason@zx2c4.com>
Tue, 11 Oct 2022 23:42:58 +0000 (17:42 -0600)
Rather than truncate a 32-bit value to a 16-bit value or an 8-bit value,
simply use the get_random_{u8,u16}() functions, which are faster than
wasting the additional bytes from a 32-bit value. This was done
mechanically with this coccinelle script:

@@
expression E;
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
typedef u16;
typedef __be16;
typedef __le16;
typedef u8;
@@
(
- (get_random_u32() & 0xffff)
+ get_random_u16()
|
- (get_random_u32() & 0xff)
+ get_random_u8()
|
- (get_random_u32() % 65536)
+ get_random_u16()
|
- (get_random_u32() % 256)
+ get_random_u8()
|
- (get_random_u32() >> 16)
+ get_random_u16()
|
- (get_random_u32() >> 24)
+ get_random_u8()
|
- (u16)get_random_u32()
+ get_random_u16()
|
- (u8)get_random_u32()
+ get_random_u8()
|
- (__be16)get_random_u32()
+ (__be16)get_random_u16()
|
- (__le16)get_random_u32()
+ (__le16)get_random_u16()
|
- prandom_u32_max(65536)
+ get_random_u16()
|
- prandom_u32_max(256)
+ get_random_u8()
|
- E->inet_id = get_random_u32()
+ E->inet_id = get_random_u16()
)

@@
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
typedef u16;
identifier v;
@@
- u16 v = get_random_u32();
+ u16 v = get_random_u16();

@@
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
typedef u8;
identifier v;
@@
- u8 v = get_random_u32();
+ u8 v = get_random_u8();

@@
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
typedef u16;
u16 v;
@@
-  v = get_random_u32();
+  v = get_random_u16();

@@
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
typedef u8;
u8 v;
@@
-  v = get_random_u32();
+  v = get_random_u8();

// Find a potential literal
@literal_mask@
expression LITERAL;
type T;
identifier get_random_u32 =~ "get_random_int|prandom_u32|get_random_u32";
position p;
@@

        ((T)get_random_u32()@p & (LITERAL))

// Examine limits
@script:python add_one@
literal << literal_mask.LITERAL;
RESULT;
@@

value = None
if literal.startswith('0x'):
        value = int(literal, 16)
elif literal[0] in '123456789':
        value = int(literal, 10)
if value is None:
        print("I don't know how to handle %s" % (literal))
        cocci.include_match(False)
elif value < 256:
        coccinelle.RESULT = cocci.make_ident("get_random_u8")
elif value < 65536:
        coccinelle.RESULT = cocci.make_ident("get_random_u16")
else:
        print("Skipping large mask of %s" % (literal))
        cocci.include_match(False)

// Replace the literal mask with the calculated result.
@plus_one@
expression literal_mask.LITERAL;
position literal_mask.p;
identifier add_one.RESULT;
identifier FUNC;
@@

-       (FUNC()@p & (LITERAL))
+       (RESULT() & LITERAL)

Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Kees Cook <keescook@chromium.org>
Reviewed-by: Yury Norov <yury.norov@gmail.com>
Acked-by: Jakub Kicinski <kuba@kernel.org>
Acked-by: Toke Høiland-Jørgensen <toke@toke.dk> # for sch_cake
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
21 files changed:
arch/arm/kernel/signal.c
arch/arm64/kernel/syscall.c
crypto/testmgr.c
drivers/media/common/v4l2-tpg/v4l2-tpg-core.c
drivers/media/test-drivers/vivid/vivid-radio-rx.c
drivers/net/ethernet/chelsio/inline_crypto/chtls/chtls_cm.c
drivers/net/hamradio/baycom_epp.c
drivers/net/hamradio/hdlcdrv.c
drivers/net/hamradio/yam.c
drivers/net/wireguard/selftest/allowedips.c
drivers/net/wireless/st/cw1200/wsm.c
drivers/scsi/lpfc/lpfc_hbadisc.c
lib/cmdline_kunit.c
net/dccp/ipv4.c
net/ipv4/datagram.c
net/ipv4/ip_output.c
net/ipv4/tcp_ipv4.c
net/mac80211/scan.c
net/netfilter/nf_nat_core.c
net/sched/sch_cake.c
net/sctp/socket.c

index ea128e32e8ca8f28ae7ea8805bb986e78c7d6074..e07f359254c3cca23352984055a98a5e21230220 100644 (file)
@@ -655,7 +655,7 @@ struct page *get_signal_page(void)
                 PAGE_SIZE / sizeof(u32));
 
        /* Give the signal return code some randomness */
-       offset = 0x200 + (get_random_int() & 0x7fc);
+       offset = 0x200 + (get_random_u16() & 0x7fc);
        signal_return_offset = offset;
 
        /* Copy signal return handlers into the page */
index 733451fe7e41f031e2b5cf34396521d8ec0a0639..d72e8f23422daf6dc0b812855d5d28a36bbd4c54 100644 (file)
@@ -67,7 +67,7 @@ static void invoke_syscall(struct pt_regs *regs, unsigned int scno,
         *
         * The resulting 5 bits of entropy is seen in SP[8:4].
         */
-       choose_random_kstack_offset(get_random_int() & 0x1FF);
+       choose_random_kstack_offset(get_random_u16() & 0x1FF);
 }
 
 static inline bool has_syscall_work(unsigned long flags)
index bff4833dbe7c8477421e9680d8d026cbeb452404..bcd059caa1c81321ee08b45a939b855f9dff2f98 100644 (file)
@@ -927,7 +927,7 @@ static void generate_random_bytes(u8 *buf, size_t count)
                        b = 0xff;
                        break;
                default:
-                       b = (u8)prandom_u32();
+                       b = get_random_u8();
                        break;
                }
                memset(buf, b, count);
@@ -935,8 +935,8 @@ static void generate_random_bytes(u8 *buf, size_t count)
                break;
        case 2:
                /* Ascending or descending bytes, plus optional mutations */
-               increment = (u8)prandom_u32();
-               b = (u8)prandom_u32();
+               increment = get_random_u8();
+               b = get_random_u8();
                for (i = 0; i < count; i++, b += increment)
                        buf[i] = b;
                mutate_buffer(buf, count);
@@ -944,7 +944,7 @@ static void generate_random_bytes(u8 *buf, size_t count)
        default:
                /* Fully random bytes */
                for (i = 0; i < count; i++)
-                       buf[i] = (u8)prandom_u32();
+                       buf[i] = get_random_u8();
        }
 }
 
index 9b7bcdce6e44e64a129ad62980fd6e7a8a2f1042..303d02b1d71c9e67d34a8710a54f98c5d2576e9f 100644 (file)
@@ -870,7 +870,7 @@ static void precalculate_color(struct tpg_data *tpg, int k)
                g = tpg_colors[col].g;
                b = tpg_colors[col].b;
        } else if (tpg->pattern == TPG_PAT_NOISE) {
-               r = g = b = prandom_u32_max(256);
+               r = g = b = get_random_u8();
        } else if (k == TPG_COLOR_RANDOM) {
                r = g = b = tpg->qual_offset + prandom_u32_max(196);
        } else if (k >= TPG_COLOR_RAMP) {
index 232cab508f48b0e9a02934dca6196933b73657a5..8bd09589fb153875daaca7f914a2b75711723637 100644 (file)
@@ -104,8 +104,8 @@ ssize_t vivid_radio_rx_read(struct file *file, char __user *buf,
                                break;
                        case 2:
                                rds.block |= V4L2_RDS_BLOCK_ERROR;
-                               rds.lsb = prandom_u32_max(256);
-                               rds.msb = prandom_u32_max(256);
+                               rds.lsb = get_random_u8();
+                               rds.msb = get_random_u8();
                                break;
                        case 3: /* Skip block altogether */
                                if (i)
index f90bfba4b303481dbe116bc2720becc5b0f978b4..eda129d0143e7ccd70dfdda719b387a84b3cd7e3 100644 (file)
@@ -1466,7 +1466,7 @@ static void make_established(struct sock *sk, u32 snd_isn, unsigned int opt)
        tp->write_seq = snd_isn;
        tp->snd_nxt = snd_isn;
        tp->snd_una = snd_isn;
-       inet_sk(sk)->inet_id = prandom_u32();
+       inet_sk(sk)->inet_id = get_random_u16();
        assign_rxopt(sk, opt);
 
        if (tp->rcv_wnd > (RCV_BUFSIZ_M << 10))
index 7df78a721b04eff3e241554b2867da7fa26c1b0e..791b4a53d69fdf20679780c02bb580bbd78aa3b9 100644 (file)
@@ -438,7 +438,7 @@ static int transmit(struct baycom_state *bc, int cnt, unsigned char stat)
                        if ((--bc->hdlctx.slotcnt) > 0)
                                return 0;
                        bc->hdlctx.slotcnt = bc->ch_params.slottime;
-                       if (prandom_u32_max(256) > bc->ch_params.ppersist)
+                       if (get_random_u8() > bc->ch_params.ppersist)
                                return 0;
                }
        }
index bef904325a0fbb4c3988659e0f045cabc6b8c67c..2263029d1a20e614b0d08da400285f36af913c3d 100644 (file)
@@ -377,7 +377,7 @@ void hdlcdrv_arbitrate(struct net_device *dev, struct hdlcdrv_state *s)
        if ((--s->hdlctx.slotcnt) > 0)
                return;
        s->hdlctx.slotcnt = s->ch_params.slottime;
-       if (prandom_u32_max(256) > s->ch_params.ppersist)
+       if (get_random_u8() > s->ch_params.ppersist)
                return;
        start_tx(dev, s);
 }
index 97a6cc5c7ae89f1041e708835cbd9589c6ab8782..2ed2f836f09af5a0bf8dbecce1d77e2f48042dc6 100644 (file)
@@ -626,7 +626,7 @@ static void yam_arbitrate(struct net_device *dev)
        yp->slotcnt = yp->slot / 10;
 
        /* is random > persist ? */
-       if (prandom_u32_max(256) > yp->pers)
+       if (get_random_u8() > yp->pers)
                return;
 
        yam_start_tx(dev, yp);
index 41db10f9be4985619b21a0922159ad91f87a803b..dd897c0740a2814012119bb689e56156411b55a5 100644 (file)
@@ -310,7 +310,7 @@ static __init bool randomized_test(void)
                        for (k = 0; k < 4; ++k)
                                mutated[k] = (mutated[k] & mutate_mask[k]) |
                                             (~mutate_mask[k] &
-                                             prandom_u32_max(256));
+                                             get_random_u8());
                        cidr = prandom_u32_max(32) + 1;
                        peer = peers[prandom_u32_max(NUM_PEERS)];
                        if (wg_allowedips_insert_v4(&t,
@@ -354,7 +354,7 @@ static __init bool randomized_test(void)
                        for (k = 0; k < 4; ++k)
                                mutated[k] = (mutated[k] & mutate_mask[k]) |
                                             (~mutate_mask[k] &
-                                             prandom_u32_max(256));
+                                             get_random_u8());
                        cidr = prandom_u32_max(128) + 1;
                        peer = peers[prandom_u32_max(NUM_PEERS)];
                        if (wg_allowedips_insert_v6(&t,
index 5a3e7a626702d82670e53530e4f12777cd907dec..4a9e4b5d3547a2436c8cc7d80cb4ce7265aafda6 100644 (file)
@@ -1594,7 +1594,7 @@ static int cw1200_get_prio_queue(struct cw1200_common *priv,
                edca = &priv->edca.params[i];
                score = ((edca->aifns + edca->cwmin) << 16) +
                        ((edca->cwmax - edca->cwmin) *
-                        (get_random_int() & 0xFFFF));
+                        get_random_u16());
                if (score < best && (winner < 0 || i != 3)) {
                        best = score;
                        winner = i;
index c7f834ba8edbbb50f4b4a0fddd09c0bedb75378f..d38ebd7281b9b96f4485b58aa8af808d91d5f8a1 100644 (file)
@@ -2156,8 +2156,8 @@ lpfc_check_pending_fcoe_event(struct lpfc_hba *phba, uint8_t unreg_fcf)
  * This function makes an running random selection decision on FCF record to
  * use through a sequence of @fcf_cnt eligible FCF records with equal
  * probability. To perform integer manunipulation of random numbers with
- * size unit32_t, the lower 16 bits of the 32-bit random number returned
- * from prandom_u32() are taken as the random random number generated.
+ * size unit32_t, a 16-bit random number returned from get_random_u16() is
+ * taken as the random random number generated.
  *
  * Returns true when outcome is for the newly read FCF record should be
  * chosen; otherwise, return false when outcome is for keeping the previously
@@ -2169,7 +2169,7 @@ lpfc_sli4_new_fcf_random_select(struct lpfc_hba *phba, uint32_t fcf_cnt)
        uint32_t rand_num;
 
        /* Get 16-bit uniform random number */
-       rand_num = 0xFFFF & prandom_u32();
+       rand_num = get_random_u16();
 
        /* Decision with probability 1/fcf_cnt */
        if ((fcf_cnt * rand_num) < 0xFFFF)
index a72a2c16066ef7cb2efa1e8c1636f4ff8a8a672b..d4572dbc914539a56c8b2a6da5ab101a9e11d80d 100644 (file)
@@ -76,7 +76,7 @@ static void cmdline_test_lead_int(struct kunit *test)
                int rc = cmdline_test_values[i];
                int offset;
 
-               sprintf(in, "%u%s", get_random_int() % 256, str);
+               sprintf(in, "%u%s", get_random_u8(), str);
                /* Only first '-' after the number will advance the pointer */
                offset = strlen(in) - strlen(str) + !!(rc == 2);
                cmdline_do_one_test(test, in, rc, offset);
@@ -94,7 +94,7 @@ static void cmdline_test_tail_int(struct kunit *test)
                int rc = strcmp(str, "") ? (strcmp(str, "-") ? 0 : 1) : 1;
                int offset;
 
-               sprintf(in, "%s%u", str, get_random_int() % 256);
+               sprintf(in, "%s%u", str, get_random_u8());
                /*
                 * Only first and leading '-' not followed by integer
                 * will advance the pointer.
index 6a6e121dc00c07add075679cd3bd5f9a5bad9027..713b7b8dad7e58844e67da727b831d0f9f28dc38 100644 (file)
@@ -144,7 +144,7 @@ int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
                                                    inet->inet_daddr,
                                                    inet->inet_sport,
                                                    inet->inet_dport);
-       inet->inet_id = prandom_u32();
+       inet->inet_id = get_random_u16();
 
        err = dccp_connect(sk);
        rt = NULL;
@@ -443,7 +443,7 @@ struct sock *dccp_v4_request_recv_sock(const struct sock *sk,
        RCU_INIT_POINTER(newinet->inet_opt, rcu_dereference(ireq->ireq_opt));
        newinet->mc_index  = inet_iif(skb);
        newinet->mc_ttl    = ip_hdr(skb)->ttl;
-       newinet->inet_id   = prandom_u32();
+       newinet->inet_id   = get_random_u16();
 
        if (dst == NULL && (dst = inet_csk_route_child_sock(sk, newsk, req)) == NULL)
                goto put_and_exit;
index 405a8c2aea641119bd802d06943283252c9d5589..0ee7fd2597300f1e63396ea7025b47f194de2a02 100644 (file)
@@ -73,7 +73,7 @@ int __ip4_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len
        reuseport_has_conns(sk, true);
        sk->sk_state = TCP_ESTABLISHED;
        sk_set_txhash(sk);
-       inet->inet_id = prandom_u32();
+       inet->inet_id = get_random_u16();
 
        sk_dst_set(sk, &rt->dst);
        err = 0;
index 1ae83ad629b2562a43b180fd68d7efc6515692c0..922c87ef1ab588205edda64fe09c2d7d460e67db 100644 (file)
@@ -172,7 +172,7 @@ int ip_build_and_send_pkt(struct sk_buff *skb, const struct sock *sk,
                 * Avoid using the hashed IP ident generator.
                 */
                if (sk->sk_protocol == IPPROTO_TCP)
-                       iph->id = (__force __be16)prandom_u32();
+                       iph->id = (__force __be16)get_random_u16();
                else
                        __ip_select_ident(net, iph, 1);
        }
index 6376ad91576546d48ffcc8ed9cdf8a1904679e33..7a250ef9d1b7b5eedc10dbf4f599343d0fa464d2 100644 (file)
@@ -323,7 +323,7 @@ int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
                                                 inet->inet_daddr);
        }
 
-       inet->inet_id = prandom_u32();
+       inet->inet_id = get_random_u16();
 
        if (tcp_fastopen_defer_connect(sk, &err))
                return err;
@@ -1543,7 +1543,7 @@ struct sock *tcp_v4_syn_recv_sock(const struct sock *sk, struct sk_buff *skb,
        inet_csk(newsk)->icsk_ext_hdr_len = 0;
        if (inet_opt)
                inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
-       newinet->inet_id = prandom_u32();
+       newinet->inet_id = get_random_u16();
 
        /* Set ToS of the new socket based upon the value of incoming SYN.
         * ECT bits are set later in tcp_init_transfer().
index 0e8c4f48c36d790c92b4dee1bea491c8f12ed09d..dc3cdee51e6604d8713b0c1915743dbe2212bfbc 100644 (file)
@@ -641,7 +641,7 @@ static void ieee80211_send_scan_probe_req(struct ieee80211_sub_if_data *sdata,
                if (flags & IEEE80211_PROBE_FLAG_RANDOM_SN) {
                        struct ieee80211_hdr *hdr = (void *)skb->data;
                        struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
-                       u16 sn = get_random_u32();
+                       u16 sn = get_random_u16();
 
                        info->control.flags |= IEEE80211_TX_CTRL_NO_SEQNO;
                        hdr->seq_ctrl =
index d8e6380f63371c1265342078e4d0112092a2efa5..18319a6e68062bf2bdd7c1ef44a9ee5a7a5185ad 100644 (file)
@@ -468,7 +468,7 @@ static void nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple *tuple,
        if (range->flags & NF_NAT_RANGE_PROTO_OFFSET)
                off = (ntohs(*keyptr) - ntohs(range->base_proto.all));
        else
-               off = prandom_u32();
+               off = get_random_u16();
 
        attempts = range_size;
        if (attempts > max_attempts)
@@ -490,7 +490,7 @@ static void nf_nat_l4proto_unique_tuple(struct nf_conntrack_tuple *tuple,
        if (attempts >= range_size || attempts < 16)
                return;
        attempts /= 2;
-       off = prandom_u32();
+       off = get_random_u16();
        goto another_round;
 }
 
index 55c6879d2c7e7fe0a452102e1704b9a00ba74684..7193d25932ce2f274512237afa01cde08aac6d65 100644 (file)
@@ -2092,11 +2092,11 @@ static struct sk_buff *cake_dequeue(struct Qdisc *sch)
 
                WARN_ON(host_load > CAKE_QUEUES);
 
-               /* The shifted prandom_u32() is a way to apply dithering to
-                * avoid accumulating roundoff errors
+               /* The get_random_u16() is a way to apply dithering to avoid
+                * accumulating roundoff errors
                 */
                flow->deficit += (b->flow_quantum * quantum_div[host_load] +
-                                 (prandom_u32() >> 16)) >> 16;
+                                 get_random_u16()) >> 16;
                list_move_tail(&flow->flowchain, &b->old_flows);
 
                goto retry;
index 1e354ba449607d496619de795236882ae5a44ad1..83628c347744b32987c256c4a49a3c6fc19e20da 100644 (file)
@@ -9448,7 +9448,7 @@ void sctp_copy_sock(struct sock *newsk, struct sock *sk,
        newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
        newinet->inet_dport = htons(asoc->peer.port);
        newinet->pmtudisc = inet->pmtudisc;
-       newinet->inet_id = prandom_u32();
+       newinet->inet_id = get_random_u16();
 
        newinet->uc_ttl = inet->uc_ttl;
        newinet->mc_loop = 1;