Skip to content

Commit 03c2356

Browse files
almostivanNipaLocal
authored andcommitted
net: add sock_rcvbuf_has_space() helper
Let's add helper function that abstract the sk->sk_rcvbuf limits check for wraparound that Kuniyuki Iwashima introduce for udp receive path: commit 5a465a0 ("udp: Fix multiple wraparounds of sk->sk_rmem_alloc.") Note that I copied Kuniyuki Iwashima's comments into sock_rcvbuf_has_space(). Subsequent patches will use this for udp and netlink sockets. Signed-off-by: Jason Baron <[email protected]> Signed-off-by: NipaLocal <nipa@local>
1 parent acf255b commit 03c2356

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

include/net/sock.h

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2484,6 +2484,44 @@ static inline unsigned long sock_wspace(struct sock *sk)
24842484
return amt;
24852485
}
24862486

2487+
static inline bool __sock_rcvbuf_has_space(unsigned int rmem,
2488+
unsigned int rcvbuf,
2489+
unsigned int size)
2490+
{
2491+
/* Immediately drop when the receive queue is full. */
2492+
if (rmem + size > rcvbuf) {
2493+
if (rcvbuf > INT_MAX >> 1)
2494+
return false;
2495+
2496+
/* Always allow at least one packet for small buffer. */
2497+
if (rmem > rcvbuf)
2498+
return false;
2499+
}
2500+
return true;
2501+
}
2502+
2503+
/**
2504+
* sock_rcvbuf_has_space - check if sk->sk_rcvbuf has space
2505+
* @sk: socket
2506+
* @skb: socket buffer
2507+
*
2508+
* Can skb->truesize bytes be added to the socket receive buffer
2509+
* while respecting the sk->sk_rcvbuf limit. Note that rcvbuf and
2510+
* rmem are assigned to unsigned int to avoid wraparound.
2511+
*
2512+
* Return: true if there is space, false otherwise
2513+
*/
2514+
static inline bool sock_rcvbuf_has_space(struct sock *sk, struct sk_buff *skb)
2515+
{
2516+
unsigned int rmem, rcvbuf;
2517+
2518+
/* Cast to unsigned int performs the boundary check for INT_MAX. */
2519+
rmem = atomic_read(&sk->sk_rmem_alloc);
2520+
rcvbuf = READ_ONCE(sk->sk_rcvbuf);
2521+
2522+
return __sock_rcvbuf_has_space(rmem, rcvbuf, skb->truesize);
2523+
}
2524+
24872525
/* Note:
24882526
* We use sk->sk_wq_raw, from contexts knowing this
24892527
* pointer is not NULL and cannot disappear/change.

0 commit comments

Comments
 (0)