treewide: use get_random_{u8,u16}() when possible, part 1

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>

+34 -34
+1 -1
arch/arm/kernel/signal.c
··· 655 PAGE_SIZE / sizeof(u32)); 656 657 /* Give the signal return code some randomness */ 658 - offset = 0x200 + (get_random_int() & 0x7fc); 659 signal_return_offset = offset; 660 661 /* Copy signal return handlers into the page */
··· 655 PAGE_SIZE / sizeof(u32)); 656 657 /* Give the signal return code some randomness */ 658 + offset = 0x200 + (get_random_u16() & 0x7fc); 659 signal_return_offset = offset; 660 661 /* Copy signal return handlers into the page */
+1 -1
arch/arm64/kernel/syscall.c
··· 67 * 68 * The resulting 5 bits of entropy is seen in SP[8:4]. 69 */ 70 - choose_random_kstack_offset(get_random_int() & 0x1FF); 71 } 72 73 static inline bool has_syscall_work(unsigned long flags)
··· 67 * 68 * The resulting 5 bits of entropy is seen in SP[8:4]. 69 */ 70 + choose_random_kstack_offset(get_random_u16() & 0x1FF); 71 } 72 73 static inline bool has_syscall_work(unsigned long flags)
+4 -4
crypto/testmgr.c
··· 927 b = 0xff; 928 break; 929 default: 930 - b = (u8)prandom_u32(); 931 break; 932 } 933 memset(buf, b, count); ··· 935 break; 936 case 2: 937 /* Ascending or descending bytes, plus optional mutations */ 938 - increment = (u8)prandom_u32(); 939 - b = (u8)prandom_u32(); 940 for (i = 0; i < count; i++, b += increment) 941 buf[i] = b; 942 mutate_buffer(buf, count); ··· 944 default: 945 /* Fully random bytes */ 946 for (i = 0; i < count; i++) 947 - buf[i] = (u8)prandom_u32(); 948 } 949 } 950
··· 927 b = 0xff; 928 break; 929 default: 930 + b = get_random_u8(); 931 break; 932 } 933 memset(buf, b, count); ··· 935 break; 936 case 2: 937 /* Ascending or descending bytes, plus optional mutations */ 938 + increment = get_random_u8(); 939 + b = get_random_u8(); 940 for (i = 0; i < count; i++, b += increment) 941 buf[i] = b; 942 mutate_buffer(buf, count); ··· 944 default: 945 /* Fully random bytes */ 946 for (i = 0; i < count; i++) 947 + buf[i] = get_random_u8(); 948 } 949 } 950
+1 -1
drivers/media/common/v4l2-tpg/v4l2-tpg-core.c
··· 870 g = tpg_colors[col].g; 871 b = tpg_colors[col].b; 872 } else if (tpg->pattern == TPG_PAT_NOISE) { 873 - r = g = b = prandom_u32_max(256); 874 } else if (k == TPG_COLOR_RANDOM) { 875 r = g = b = tpg->qual_offset + prandom_u32_max(196); 876 } else if (k >= TPG_COLOR_RAMP) {
··· 870 g = tpg_colors[col].g; 871 b = tpg_colors[col].b; 872 } else if (tpg->pattern == TPG_PAT_NOISE) { 873 + r = g = b = get_random_u8(); 874 } else if (k == TPG_COLOR_RANDOM) { 875 r = g = b = tpg->qual_offset + prandom_u32_max(196); 876 } else if (k >= TPG_COLOR_RAMP) {
+2 -2
drivers/media/test-drivers/vivid/vivid-radio-rx.c
··· 104 break; 105 case 2: 106 rds.block |= V4L2_RDS_BLOCK_ERROR; 107 - rds.lsb = prandom_u32_max(256); 108 - rds.msb = prandom_u32_max(256); 109 break; 110 case 3: /* Skip block altogether */ 111 if (i)
··· 104 break; 105 case 2: 106 rds.block |= V4L2_RDS_BLOCK_ERROR; 107 + rds.lsb = get_random_u8(); 108 + rds.msb = get_random_u8(); 109 break; 110 case 3: /* Skip block altogether */ 111 if (i)
+1 -1
drivers/net/ethernet/chelsio/inline_crypto/chtls/chtls_cm.c
··· 1466 tp->write_seq = snd_isn; 1467 tp->snd_nxt = snd_isn; 1468 tp->snd_una = snd_isn; 1469 - inet_sk(sk)->inet_id = prandom_u32(); 1470 assign_rxopt(sk, opt); 1471 1472 if (tp->rcv_wnd > (RCV_BUFSIZ_M << 10))
··· 1466 tp->write_seq = snd_isn; 1467 tp->snd_nxt = snd_isn; 1468 tp->snd_una = snd_isn; 1469 + inet_sk(sk)->inet_id = get_random_u16(); 1470 assign_rxopt(sk, opt); 1471 1472 if (tp->rcv_wnd > (RCV_BUFSIZ_M << 10))
+1 -1
drivers/net/hamradio/baycom_epp.c
··· 438 if ((--bc->hdlctx.slotcnt) > 0) 439 return 0; 440 bc->hdlctx.slotcnt = bc->ch_params.slottime; 441 - if (prandom_u32_max(256) > bc->ch_params.ppersist) 442 return 0; 443 } 444 }
··· 438 if ((--bc->hdlctx.slotcnt) > 0) 439 return 0; 440 bc->hdlctx.slotcnt = bc->ch_params.slottime; 441 + if (get_random_u8() > bc->ch_params.ppersist) 442 return 0; 443 } 444 }
+1 -1
drivers/net/hamradio/hdlcdrv.c
··· 377 if ((--s->hdlctx.slotcnt) > 0) 378 return; 379 s->hdlctx.slotcnt = s->ch_params.slottime; 380 - if (prandom_u32_max(256) > s->ch_params.ppersist) 381 return; 382 start_tx(dev, s); 383 }
··· 377 if ((--s->hdlctx.slotcnt) > 0) 378 return; 379 s->hdlctx.slotcnt = s->ch_params.slottime; 380 + if (get_random_u8() > s->ch_params.ppersist) 381 return; 382 start_tx(dev, s); 383 }
+1 -1
drivers/net/hamradio/yam.c
··· 626 yp->slotcnt = yp->slot / 10; 627 628 /* is random > persist ? */ 629 - if (prandom_u32_max(256) > yp->pers) 630 return; 631 632 yam_start_tx(dev, yp);
··· 626 yp->slotcnt = yp->slot / 10; 627 628 /* is random > persist ? */ 629 + if (get_random_u8() > yp->pers) 630 return; 631 632 yam_start_tx(dev, yp);
+2 -2
drivers/net/wireguard/selftest/allowedips.c
··· 310 for (k = 0; k < 4; ++k) 311 mutated[k] = (mutated[k] & mutate_mask[k]) | 312 (~mutate_mask[k] & 313 - prandom_u32_max(256)); 314 cidr = prandom_u32_max(32) + 1; 315 peer = peers[prandom_u32_max(NUM_PEERS)]; 316 if (wg_allowedips_insert_v4(&t, ··· 354 for (k = 0; k < 4; ++k) 355 mutated[k] = (mutated[k] & mutate_mask[k]) | 356 (~mutate_mask[k] & 357 - prandom_u32_max(256)); 358 cidr = prandom_u32_max(128) + 1; 359 peer = peers[prandom_u32_max(NUM_PEERS)]; 360 if (wg_allowedips_insert_v6(&t,
··· 310 for (k = 0; k < 4; ++k) 311 mutated[k] = (mutated[k] & mutate_mask[k]) | 312 (~mutate_mask[k] & 313 + get_random_u8()); 314 cidr = prandom_u32_max(32) + 1; 315 peer = peers[prandom_u32_max(NUM_PEERS)]; 316 if (wg_allowedips_insert_v4(&t, ··· 354 for (k = 0; k < 4; ++k) 355 mutated[k] = (mutated[k] & mutate_mask[k]) | 356 (~mutate_mask[k] & 357 + get_random_u8()); 358 cidr = prandom_u32_max(128) + 1; 359 peer = peers[prandom_u32_max(NUM_PEERS)]; 360 if (wg_allowedips_insert_v6(&t,
+1 -1
drivers/net/wireless/st/cw1200/wsm.c
··· 1594 edca = &priv->edca.params[i]; 1595 score = ((edca->aifns + edca->cwmin) << 16) + 1596 ((edca->cwmax - edca->cwmin) * 1597 - (get_random_int() & 0xFFFF)); 1598 if (score < best && (winner < 0 || i != 3)) { 1599 best = score; 1600 winner = i;
··· 1594 edca = &priv->edca.params[i]; 1595 score = ((edca->aifns + edca->cwmin) << 16) + 1596 ((edca->cwmax - edca->cwmin) * 1597 + get_random_u16()); 1598 if (score < best && (winner < 0 || i != 3)) { 1599 best = score; 1600 winner = i;
+3 -3
drivers/scsi/lpfc/lpfc_hbadisc.c
··· 2156 * This function makes an running random selection decision on FCF record to 2157 * use through a sequence of @fcf_cnt eligible FCF records with equal 2158 * probability. To perform integer manunipulation of random numbers with 2159 - * size unit32_t, the lower 16 bits of the 32-bit random number returned 2160 - * from prandom_u32() are taken as the random random number generated. 2161 * 2162 * Returns true when outcome is for the newly read FCF record should be 2163 * chosen; otherwise, return false when outcome is for keeping the previously ··· 2169 uint32_t rand_num; 2170 2171 /* Get 16-bit uniform random number */ 2172 - rand_num = 0xFFFF & prandom_u32(); 2173 2174 /* Decision with probability 1/fcf_cnt */ 2175 if ((fcf_cnt * rand_num) < 0xFFFF)
··· 2156 * This function makes an running random selection decision on FCF record to 2157 * use through a sequence of @fcf_cnt eligible FCF records with equal 2158 * probability. To perform integer manunipulation of random numbers with 2159 + * size unit32_t, a 16-bit random number returned from get_random_u16() is 2160 + * taken as the random random number generated. 2161 * 2162 * Returns true when outcome is for the newly read FCF record should be 2163 * chosen; otherwise, return false when outcome is for keeping the previously ··· 2169 uint32_t rand_num; 2170 2171 /* Get 16-bit uniform random number */ 2172 + rand_num = get_random_u16(); 2173 2174 /* Decision with probability 1/fcf_cnt */ 2175 if ((fcf_cnt * rand_num) < 0xFFFF)
+2 -2
lib/cmdline_kunit.c
··· 76 int rc = cmdline_test_values[i]; 77 int offset; 78 79 - sprintf(in, "%u%s", get_random_int() % 256, str); 80 /* Only first '-' after the number will advance the pointer */ 81 offset = strlen(in) - strlen(str) + !!(rc == 2); 82 cmdline_do_one_test(test, in, rc, offset); ··· 94 int rc = strcmp(str, "") ? (strcmp(str, "-") ? 0 : 1) : 1; 95 int offset; 96 97 - sprintf(in, "%s%u", str, get_random_int() % 256); 98 /* 99 * Only first and leading '-' not followed by integer 100 * will advance the pointer.
··· 76 int rc = cmdline_test_values[i]; 77 int offset; 78 79 + sprintf(in, "%u%s", get_random_u8(), str); 80 /* Only first '-' after the number will advance the pointer */ 81 offset = strlen(in) - strlen(str) + !!(rc == 2); 82 cmdline_do_one_test(test, in, rc, offset); ··· 94 int rc = strcmp(str, "") ? (strcmp(str, "-") ? 0 : 1) : 1; 95 int offset; 96 97 + sprintf(in, "%s%u", str, get_random_u8()); 98 /* 99 * Only first and leading '-' not followed by integer 100 * will advance the pointer.
+2 -2
net/dccp/ipv4.c
··· 144 inet->inet_daddr, 145 inet->inet_sport, 146 inet->inet_dport); 147 - inet->inet_id = prandom_u32(); 148 149 err = dccp_connect(sk); 150 rt = NULL; ··· 443 RCU_INIT_POINTER(newinet->inet_opt, rcu_dereference(ireq->ireq_opt)); 444 newinet->mc_index = inet_iif(skb); 445 newinet->mc_ttl = ip_hdr(skb)->ttl; 446 - newinet->inet_id = prandom_u32(); 447 448 if (dst == NULL && (dst = inet_csk_route_child_sock(sk, newsk, req)) == NULL) 449 goto put_and_exit;
··· 144 inet->inet_daddr, 145 inet->inet_sport, 146 inet->inet_dport); 147 + inet->inet_id = get_random_u16(); 148 149 err = dccp_connect(sk); 150 rt = NULL; ··· 443 RCU_INIT_POINTER(newinet->inet_opt, rcu_dereference(ireq->ireq_opt)); 444 newinet->mc_index = inet_iif(skb); 445 newinet->mc_ttl = ip_hdr(skb)->ttl; 446 + newinet->inet_id = get_random_u16(); 447 448 if (dst == NULL && (dst = inet_csk_route_child_sock(sk, newsk, req)) == NULL) 449 goto put_and_exit;
+1 -1
net/ipv4/datagram.c
··· 73 reuseport_has_conns(sk, true); 74 sk->sk_state = TCP_ESTABLISHED; 75 sk_set_txhash(sk); 76 - inet->inet_id = prandom_u32(); 77 78 sk_dst_set(sk, &rt->dst); 79 err = 0;
··· 73 reuseport_has_conns(sk, true); 74 sk->sk_state = TCP_ESTABLISHED; 75 sk_set_txhash(sk); 76 + inet->inet_id = get_random_u16(); 77 78 sk_dst_set(sk, &rt->dst); 79 err = 0;
+1 -1
net/ipv4/ip_output.c
··· 172 * Avoid using the hashed IP ident generator. 173 */ 174 if (sk->sk_protocol == IPPROTO_TCP) 175 - iph->id = (__force __be16)prandom_u32(); 176 else 177 __ip_select_ident(net, iph, 1); 178 }
··· 172 * Avoid using the hashed IP ident generator. 173 */ 174 if (sk->sk_protocol == IPPROTO_TCP) 175 + iph->id = (__force __be16)get_random_u16(); 176 else 177 __ip_select_ident(net, iph, 1); 178 }
+2 -2
net/ipv4/tcp_ipv4.c
··· 323 inet->inet_daddr); 324 } 325 326 - inet->inet_id = prandom_u32(); 327 328 if (tcp_fastopen_defer_connect(sk, &err)) 329 return err; ··· 1543 inet_csk(newsk)->icsk_ext_hdr_len = 0; 1544 if (inet_opt) 1545 inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen; 1546 - newinet->inet_id = prandom_u32(); 1547 1548 /* Set ToS of the new socket based upon the value of incoming SYN. 1549 * ECT bits are set later in tcp_init_transfer().
··· 323 inet->inet_daddr); 324 } 325 326 + inet->inet_id = get_random_u16(); 327 328 if (tcp_fastopen_defer_connect(sk, &err)) 329 return err; ··· 1543 inet_csk(newsk)->icsk_ext_hdr_len = 0; 1544 if (inet_opt) 1545 inet_csk(newsk)->icsk_ext_hdr_len = inet_opt->opt.optlen; 1546 + newinet->inet_id = get_random_u16(); 1547 1548 /* Set ToS of the new socket based upon the value of incoming SYN. 1549 * ECT bits are set later in tcp_init_transfer().
+1 -1
net/mac80211/scan.c
··· 641 if (flags & IEEE80211_PROBE_FLAG_RANDOM_SN) { 642 struct ieee80211_hdr *hdr = (void *)skb->data; 643 struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); 644 - u16 sn = get_random_u32(); 645 646 info->control.flags |= IEEE80211_TX_CTRL_NO_SEQNO; 647 hdr->seq_ctrl =
··· 641 if (flags & IEEE80211_PROBE_FLAG_RANDOM_SN) { 642 struct ieee80211_hdr *hdr = (void *)skb->data; 643 struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); 644 + u16 sn = get_random_u16(); 645 646 info->control.flags |= IEEE80211_TX_CTRL_NO_SEQNO; 647 hdr->seq_ctrl =
+2 -2
net/netfilter/nf_nat_core.c
··· 468 if (range->flags & NF_NAT_RANGE_PROTO_OFFSET) 469 off = (ntohs(*keyptr) - ntohs(range->base_proto.all)); 470 else 471 - off = prandom_u32(); 472 473 attempts = range_size; 474 if (attempts > max_attempts) ··· 490 if (attempts >= range_size || attempts < 16) 491 return; 492 attempts /= 2; 493 - off = prandom_u32(); 494 goto another_round; 495 } 496
··· 468 if (range->flags & NF_NAT_RANGE_PROTO_OFFSET) 469 off = (ntohs(*keyptr) - ntohs(range->base_proto.all)); 470 else 471 + off = get_random_u16(); 472 473 attempts = range_size; 474 if (attempts > max_attempts) ··· 490 if (attempts >= range_size || attempts < 16) 491 return; 492 attempts /= 2; 493 + off = get_random_u16(); 494 goto another_round; 495 } 496
+3 -3
net/sched/sch_cake.c
··· 2092 2093 WARN_ON(host_load > CAKE_QUEUES); 2094 2095 - /* The shifted prandom_u32() is a way to apply dithering to 2096 - * avoid accumulating roundoff errors 2097 */ 2098 flow->deficit += (b->flow_quantum * quantum_div[host_load] + 2099 - (prandom_u32() >> 16)) >> 16; 2100 list_move_tail(&flow->flowchain, &b->old_flows); 2101 2102 goto retry;
··· 2092 2093 WARN_ON(host_load > CAKE_QUEUES); 2094 2095 + /* The get_random_u16() is a way to apply dithering to avoid 2096 + * accumulating roundoff errors 2097 */ 2098 flow->deficit += (b->flow_quantum * quantum_div[host_load] + 2099 + get_random_u16()) >> 16; 2100 list_move_tail(&flow->flowchain, &b->old_flows); 2101 2102 goto retry;
+1 -1
net/sctp/socket.c
··· 9448 newinet->inet_rcv_saddr = inet->inet_rcv_saddr; 9449 newinet->inet_dport = htons(asoc->peer.port); 9450 newinet->pmtudisc = inet->pmtudisc; 9451 - newinet->inet_id = prandom_u32(); 9452 9453 newinet->uc_ttl = inet->uc_ttl; 9454 newinet->mc_loop = 1;
··· 9448 newinet->inet_rcv_saddr = inet->inet_rcv_saddr; 9449 newinet->inet_dport = htons(asoc->peer.port); 9450 newinet->pmtudisc = inet->pmtudisc; 9451 + newinet->inet_id = get_random_u16(); 9452 9453 newinet->uc_ttl = inet->uc_ttl; 9454 newinet->mc_loop = 1;