Skip to content

Commit f6c8a35

Browse files
Geliang Tangintel-lab-lkp
authored andcommitted
sock: add sock_kmemdup helper
This patch adds the sock version of kmemdup() helper, named sock_kmemdup(), to duplicate a memory block using the socket's option memory buffer. Signed-off-by: Geliang Tang <[email protected]>
1 parent 68dd28e commit f6c8a35

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

include/net/sock.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1793,6 +1793,7 @@ static inline struct sk_buff *sock_alloc_send_skb(struct sock *sk,
17931793
}
17941794

17951795
void *sock_kmalloc(struct sock *sk, int size, gfp_t priority);
1796+
void *sock_kmemdup(struct sock *sk, const void *src, int size, gfp_t priority);
17961797
void sock_kfree_s(struct sock *sk, void *mem, int size);
17971798
void sock_kzfree_s(struct sock *sk, void *mem, int size);
17981799
void sk_send_sigurg(struct sock *sk);

net/core/sock.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2805,6 +2805,29 @@ void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
28052805
}
28062806
EXPORT_SYMBOL(sock_kmalloc);
28072807

2808+
/*
2809+
* Duplicate a memory block using the socket's option memory buffer.
2810+
*/
2811+
void *sock_kmemdup(struct sock *sk, const void *src, int size, gfp_t priority)
2812+
{
2813+
int optmem_max = READ_ONCE(sock_net(sk)->core.sysctl_optmem_max);
2814+
2815+
if ((unsigned int)size <= optmem_max &&
2816+
atomic_read(&sk->sk_omem_alloc) + size < optmem_max) {
2817+
void *mem;
2818+
/* First do the add, to avoid the race if kmalloc
2819+
* might sleep.
2820+
*/
2821+
atomic_add(size, &sk->sk_omem_alloc);
2822+
mem = kmemdup(src, size, priority);
2823+
if (mem)
2824+
return mem;
2825+
atomic_sub(size, &sk->sk_omem_alloc);
2826+
}
2827+
return NULL;
2828+
}
2829+
EXPORT_SYMBOL(sock_kmemdup);
2830+
28082831
/* Free an option memory block. Note, we actually want the inline
28092832
* here as this allows gcc to detect the nullify and fold away the
28102833
* condition entirely.

0 commit comments

Comments
 (0)