root/net/core/filter.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. sk_filter_trim_cap
  2. BPF_CALL_1
  3. BPF_CALL_3
  4. BPF_CALL_3
  5. BPF_CALL_4
  6. BPF_CALL_2
  7. BPF_CALL_4
  8. BPF_CALL_2
  9. BPF_CALL_4
  10. BPF_CALL_2
  11. BPF_CALL_0
  12. convert_skb_access
  13. convert_bpf_extensions
  14. convert_bpf_ld_abs
  15. bpf_convert_filter
  16. check_load_and_stores
  17. chk_code_allowed
  18. bpf_check_basics_ok
  19. bpf_check_classic
  20. bpf_prog_store_orig_filter
  21. bpf_release_orig_filter
  22. __bpf_prog_release
  23. __sk_filter_release
  24. sk_filter_release_rcu
  25. sk_filter_release
  26. sk_filter_uncharge
  27. __sk_filter_charge
  28. sk_filter_charge
  29. bpf_migrate_filter
  30. bpf_prepare_filter
  31. bpf_prog_create
  32. bpf_prog_create_from_user
  33. bpf_prog_destroy
  34. __sk_attach_prog
  35. __get_filter
  36. sk_attach_filter
  37. sk_reuseport_attach_filter
  38. __get_bpf
  39. sk_attach_bpf
  40. sk_reuseport_attach_bpf
  41. sk_reuseport_prog_free
  42. __bpf_try_make_writable
  43. bpf_try_make_writable
  44. bpf_try_make_head_writable
  45. bpf_push_mac_rcsum
  46. bpf_pull_mac_rcsum
  47. BPF_CALL_5
  48. BPF_CALL_4
  49. BPF_CALL_4
  50. BPF_CALL_5
  51. BPF_CALL_2
  52. BPF_CALL_1
  53. sk_skb_try_make_writable
  54. BPF_CALL_2
  55. BPF_CALL_5
  56. BPF_CALL_5
  57. BPF_CALL_5
  58. BPF_CALL_2
  59. __bpf_rx_skb
  60. __bpf_rx_skb_no_mac
  61. __bpf_tx_skb
  62. __bpf_redirect_no_mac
  63. __bpf_redirect_common
  64. __bpf_redirect
  65. BPF_CALL_3
  66. BPF_CALL_2
  67. skb_do_redirect
  68. BPF_CALL_2
  69. BPF_CALL_2
  70. BPF_CALL_4
  71. BPF_CALL_4
  72. sk_msg_shift_left
  73. sk_msg_shift_right
  74. BPF_CALL_4
  75. BPF_CALL_1
  76. BPF_CALL_1
  77. BPF_CALL_1
  78. BPF_CALL_1
  79. BPF_CALL_2
  80. BPF_CALL_3
  81. BPF_CALL_1
  82. bpf_skb_generic_push
  83. bpf_skb_generic_pop
  84. bpf_skb_net_hdr_push
  85. bpf_skb_net_hdr_pop
  86. bpf_skb_proto_4_to_6
  87. bpf_skb_proto_6_to_4
  88. bpf_skb_proto_xlat
  89. BPF_CALL_3
  90. BPF_CALL_2
  91. bpf_skb_net_base_len
  92. bpf_skb_net_grow
  93. bpf_skb_net_shrink
  94. __bpf_skb_max_len
  95. BPF_CALL_4
  96. __bpf_skb_min_len
  97. bpf_skb_grow_rcsum
  98. bpf_skb_trim_rcsum
  99. __bpf_skb_change_tail
  100. BPF_CALL_3
  101. BPF_CALL_3
  102. __bpf_skb_change_head
  103. BPF_CALL_3
  104. BPF_CALL_3
  105. xdp_get_metalen
  106. BPF_CALL_2
  107. BPF_CALL_2
  108. BPF_CALL_2
  109. __bpf_tx_xdp
  110. xdp_do_redirect_slow
  111. __bpf_tx_xdp_map
  112. xdp_do_flush_map
  113. __xdp_map_lookup_elem
  114. bpf_clear_redirect_map
  115. xdp_do_redirect_map
  116. xdp_do_redirect
  117. xdp_do_generic_redirect_map
  118. xdp_do_generic_redirect
  119. BPF_CALL_2
  120. BPF_CALL_3
  121. bpf_skb_copy
  122. BPF_CALL_5
  123. bpf_tunnel_key_af
  124. BPF_CALL_4
  125. BPF_CALL_3
  126. BPF_CALL_4
  127. BPF_CALL_3
  128. bpf_get_skb_set_tunnel_proto
  129. BPF_CALL_3
  130. BPF_CALL_1
  131. BPF_CALL_2
  132. bpf_xdp_copy
  133. BPF_CALL_5
  134. BPF_CALL_1
  135. BPF_CALL_1
  136. BPF_CALL_1
  137. BPF_CALL_1
  138. BPF_CALL_5
  139. BPF_CALL_5
  140. BPF_CALL_5
  141. BPF_CALL_2
  142. BPF_CALL_3
  143. BPF_CALL_5
  144. bpf_fib_set_fwd_params
  145. bpf_ipv4_fib_lookup
  146. bpf_ipv6_fib_lookup
  147. BPF_CALL_4
  148. BPF_CALL_4
  149. bpf_push_seg6_encap
  150. bpf_push_ip_encap
  151. BPF_CALL_4
  152. BPF_CALL_4
  153. BPF_CALL_4
  154. bpf_update_srh_state
  155. BPF_CALL_4
  156. BPF_CALL_3
  157. sk_lookup
  158. __bpf_skc_lookup
  159. __bpf_sk_lookup
  160. bpf_skc_lookup
  161. bpf_sk_lookup
  162. BPF_CALL_5
  163. BPF_CALL_5
  164. BPF_CALL_5
  165. BPF_CALL_1
  166. BPF_CALL_5
  167. BPF_CALL_5
  168. BPF_CALL_5
  169. BPF_CALL_5
  170. BPF_CALL_5
  171. BPF_CALL_5
  172. bpf_tcp_sock_is_valid_access
  173. bpf_tcp_sock_convert_ctx_access
  174. BPF_CALL_1
  175. BPF_CALL_1
  176. BPF_CALL_1
  177. bpf_xdp_sock_is_valid_access
  178. bpf_xdp_sock_convert_ctx_access
  179. BPF_CALL_5
  180. BPF_CALL_5
  181. bpf_helper_changes_pkt_data
  182. bpf_base_func_proto
  183. sock_filter_func_proto
  184. sock_addr_func_proto
  185. sk_filter_func_proto
  186. cg_skb_func_proto
  187. tc_cls_act_func_proto
  188. xdp_func_proto
  189. sock_ops_func_proto
  190. sk_msg_func_proto
  191. sk_skb_func_proto
  192. flow_dissector_func_proto
  193. lwt_out_func_proto
  194. lwt_in_func_proto
  195. lwt_xmit_func_proto
  196. lwt_seg6local_func_proto
  197. bpf_skb_is_valid_access
  198. sk_filter_is_valid_access
  199. cg_skb_is_valid_access
  200. lwt_is_valid_access
  201. __sock_filter_check_attach_type
  202. bpf_sock_common_is_valid_access
  203. bpf_sock_is_valid_access
  204. sock_filter_is_valid_access
  205. bpf_noop_prologue
  206. bpf_unclone_prologue
  207. bpf_gen_ld_abs
  208. tc_cls_act_prologue
  209. tc_cls_act_is_valid_access
  210. __is_valid_xdp_access
  211. xdp_is_valid_access
  212. bpf_warn_invalid_xdp_action
  213. sock_addr_is_valid_access
  214. sock_ops_is_valid_access
  215. sk_skb_prologue
  216. sk_skb_is_valid_access
  217. sk_msg_is_valid_access
  218. flow_dissector_is_valid_access
  219. flow_dissector_convert_ctx_access
  220. bpf_convert_ctx_access
  221. bpf_sock_convert_ctx_access
  222. tc_cls_act_convert_ctx_access
  223. xdp_convert_ctx_access
  224. sock_addr_convert_ctx_access
  225. sock_ops_convert_ctx_access
  226. sk_skb_convert_ctx_access
  227. sk_msg_convert_ctx_access
  228. sk_detach_filter
  229. sk_get_filter
  230. bpf_init_reuseport_kern
  231. bpf_run_sk_reuseport
  232. BPF_CALL_4
  233. BPF_CALL_4
  234. BPF_CALL_5
  235. sk_reuseport_func_proto
  236. sk_reuseport_is_valid_access
  237. sk_reuseport_convert_ctx_access

   1 // SPDX-License-Identifier: GPL-2.0-or-later
   2 /*
   3  * Linux Socket Filter - Kernel level socket filtering
   4  *
   5  * Based on the design of the Berkeley Packet Filter. The new
   6  * internal format has been designed by PLUMgrid:
   7  *
   8  *      Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
   9  *
  10  * Authors:
  11  *
  12  *      Jay Schulist <jschlst@samba.org>
  13  *      Alexei Starovoitov <ast@plumgrid.com>
  14  *      Daniel Borkmann <dborkman@redhat.com>
  15  *
  16  * Andi Kleen - Fix a few bad bugs and races.
  17  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
  18  */
  19 
  20 #include <linux/module.h>
  21 #include <linux/types.h>
  22 #include <linux/mm.h>
  23 #include <linux/fcntl.h>
  24 #include <linux/socket.h>
  25 #include <linux/sock_diag.h>
  26 #include <linux/in.h>
  27 #include <linux/inet.h>
  28 #include <linux/netdevice.h>
  29 #include <linux/if_packet.h>
  30 #include <linux/if_arp.h>
  31 #include <linux/gfp.h>
  32 #include <net/inet_common.h>
  33 #include <net/ip.h>
  34 #include <net/protocol.h>
  35 #include <net/netlink.h>
  36 #include <linux/skbuff.h>
  37 #include <linux/skmsg.h>
  38 #include <net/sock.h>
  39 #include <net/flow_dissector.h>
  40 #include <linux/errno.h>
  41 #include <linux/timer.h>
  42 #include <linux/uaccess.h>
  43 #include <asm/unaligned.h>
  44 #include <asm/cmpxchg.h>
  45 #include <linux/filter.h>
  46 #include <linux/ratelimit.h>
  47 #include <linux/seccomp.h>
  48 #include <linux/if_vlan.h>
  49 #include <linux/bpf.h>
  50 #include <net/sch_generic.h>
  51 #include <net/cls_cgroup.h>
  52 #include <net/dst_metadata.h>
  53 #include <net/dst.h>
  54 #include <net/sock_reuseport.h>
  55 #include <net/busy_poll.h>
  56 #include <net/tcp.h>
  57 #include <net/xfrm.h>
  58 #include <net/udp.h>
  59 #include <linux/bpf_trace.h>
  60 #include <net/xdp_sock.h>
  61 #include <linux/inetdevice.h>
  62 #include <net/inet_hashtables.h>
  63 #include <net/inet6_hashtables.h>
  64 #include <net/ip_fib.h>
  65 #include <net/nexthop.h>
  66 #include <net/flow.h>
  67 #include <net/arp.h>
  68 #include <net/ipv6.h>
  69 #include <net/net_namespace.h>
  70 #include <linux/seg6_local.h>
  71 #include <net/seg6.h>
  72 #include <net/seg6_local.h>
  73 #include <net/lwtunnel.h>
  74 #include <net/ipv6_stubs.h>
  75 #include <net/bpf_sk_storage.h>
  76 
  77 /**
  78  *      sk_filter_trim_cap - run a packet through a socket filter
  79  *      @sk: sock associated with &sk_buff
  80  *      @skb: buffer to filter
  81  *      @cap: limit on how short the eBPF program may trim the packet
  82  *
  83  * Run the eBPF program and then cut skb->data to correct size returned by
  84  * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
  85  * than pkt_len we keep whole skb->data. This is the socket level
  86  * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
  87  * be accepted or -EPERM if the packet should be tossed.
  88  *
  89  */
  90 int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
  91 {
  92         int err;
  93         struct sk_filter *filter;
  94 
  95         /*
  96          * If the skb was allocated from pfmemalloc reserves, only
  97          * allow SOCK_MEMALLOC sockets to use it as this socket is
  98          * helping free memory
  99          */
 100         if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
 101                 NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
 102                 return -ENOMEM;
 103         }
 104         err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
 105         if (err)
 106                 return err;
 107 
 108         err = security_sock_rcv_skb(sk, skb);
 109         if (err)
 110                 return err;
 111 
 112         rcu_read_lock();
 113         filter = rcu_dereference(sk->sk_filter);
 114         if (filter) {
 115                 struct sock *save_sk = skb->sk;
 116                 unsigned int pkt_len;
 117 
 118                 skb->sk = sk;
 119                 pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
 120                 skb->sk = save_sk;
 121                 err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
 122         }
 123         rcu_read_unlock();
 124 
 125         return err;
 126 }
 127 EXPORT_SYMBOL(sk_filter_trim_cap);
 128 
 129 BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
 130 {
 131         return skb_get_poff(skb);
 132 }
 133 
 134 BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
 135 {
 136         struct nlattr *nla;
 137 
 138         if (skb_is_nonlinear(skb))
 139                 return 0;
 140 
 141         if (skb->len < sizeof(struct nlattr))
 142                 return 0;
 143 
 144         if (a > skb->len - sizeof(struct nlattr))
 145                 return 0;
 146 
 147         nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
 148         if (nla)
 149                 return (void *) nla - (void *) skb->data;
 150 
 151         return 0;
 152 }
 153 
 154 BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
 155 {
 156         struct nlattr *nla;
 157 
 158         if (skb_is_nonlinear(skb))
 159                 return 0;
 160 
 161         if (skb->len < sizeof(struct nlattr))
 162                 return 0;
 163 
 164         if (a > skb->len - sizeof(struct nlattr))
 165                 return 0;
 166 
 167         nla = (struct nlattr *) &skb->data[a];
 168         if (nla->nla_len > skb->len - a)
 169                 return 0;
 170 
 171         nla = nla_find_nested(nla, x);
 172         if (nla)
 173                 return (void *) nla - (void *) skb->data;
 174 
 175         return 0;
 176 }
 177 
 178 BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
 179            data, int, headlen, int, offset)
 180 {
 181         u8 tmp, *ptr;
 182         const int len = sizeof(tmp);
 183 
 184         if (offset >= 0) {
 185                 if (headlen - offset >= len)
 186                         return *(u8 *)(data + offset);
 187                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 188                         return tmp;
 189         } else {
 190                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 191                 if (likely(ptr))
 192                         return *(u8 *)ptr;
 193         }
 194 
 195         return -EFAULT;
 196 }
 197 
 198 BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
 199            int, offset)
 200 {
 201         return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
 202                                          offset);
 203 }
 204 
 205 BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
 206            data, int, headlen, int, offset)
 207 {
 208         u16 tmp, *ptr;
 209         const int len = sizeof(tmp);
 210 
 211         if (offset >= 0) {
 212                 if (headlen - offset >= len)
 213                         return get_unaligned_be16(data + offset);
 214                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 215                         return be16_to_cpu(tmp);
 216         } else {
 217                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 218                 if (likely(ptr))
 219                         return get_unaligned_be16(ptr);
 220         }
 221 
 222         return -EFAULT;
 223 }
 224 
 225 BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
 226            int, offset)
 227 {
 228         return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
 229                                           offset);
 230 }
 231 
 232 BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
 233            data, int, headlen, int, offset)
 234 {
 235         u32 tmp, *ptr;
 236         const int len = sizeof(tmp);
 237 
 238         if (likely(offset >= 0)) {
 239                 if (headlen - offset >= len)
 240                         return get_unaligned_be32(data + offset);
 241                 if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
 242                         return be32_to_cpu(tmp);
 243         } else {
 244                 ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
 245                 if (likely(ptr))
 246                         return get_unaligned_be32(ptr);
 247         }
 248 
 249         return -EFAULT;
 250 }
 251 
 252 BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
 253            int, offset)
 254 {
 255         return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
 256                                           offset);
 257 }
 258 
 259 BPF_CALL_0(bpf_get_raw_cpu_id)
 260 {
 261         return raw_smp_processor_id();
 262 }
 263 
 264 static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
 265         .func           = bpf_get_raw_cpu_id,
 266         .gpl_only       = false,
 267         .ret_type       = RET_INTEGER,
 268 };
 269 
 270 static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
 271                               struct bpf_insn *insn_buf)
 272 {
 273         struct bpf_insn *insn = insn_buf;
 274 
 275         switch (skb_field) {
 276         case SKF_AD_MARK:
 277                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);
 278 
 279                 *insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
 280                                       offsetof(struct sk_buff, mark));
 281                 break;
 282 
 283         case SKF_AD_PKTTYPE:
 284                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
 285                 *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
 286 #ifdef __BIG_ENDIAN_BITFIELD
 287                 *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
 288 #endif
 289                 break;
 290 
 291         case SKF_AD_QUEUE:
 292                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);
 293 
 294                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 295                                       offsetof(struct sk_buff, queue_mapping));
 296                 break;
 297 
 298         case SKF_AD_VLAN_TAG:
 299                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
 300 
 301                 /* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
 302                 *insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
 303                                       offsetof(struct sk_buff, vlan_tci));
 304                 break;
 305         case SKF_AD_VLAN_TAG_PRESENT:
 306                 *insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_VLAN_PRESENT_OFFSET());
 307                 if (PKT_VLAN_PRESENT_BIT)
 308                         *insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, PKT_VLAN_PRESENT_BIT);
 309                 if (PKT_VLAN_PRESENT_BIT < 7)
 310                         *insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
 311                 break;
 312         }
 313 
 314         return insn - insn_buf;
 315 }
 316 
 317 static bool convert_bpf_extensions(struct sock_filter *fp,
 318                                    struct bpf_insn **insnp)
 319 {
 320         struct bpf_insn *insn = *insnp;
 321         u32 cnt;
 322 
 323         switch (fp->k) {
 324         case SKF_AD_OFF + SKF_AD_PROTOCOL:
 325                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);
 326 
 327                 /* A = *(u16 *) (CTX + offsetof(protocol)) */
 328                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 329                                       offsetof(struct sk_buff, protocol));
 330                 /* A = ntohs(A) [emitting a nop or swap16] */
 331                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 332                 break;
 333 
 334         case SKF_AD_OFF + SKF_AD_PKTTYPE:
 335                 cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
 336                 insn += cnt - 1;
 337                 break;
 338 
 339         case SKF_AD_OFF + SKF_AD_IFINDEX:
 340         case SKF_AD_OFF + SKF_AD_HATYPE:
 341                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
 342                 BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
 343 
 344                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
 345                                       BPF_REG_TMP, BPF_REG_CTX,
 346                                       offsetof(struct sk_buff, dev));
 347                 /* if (tmp != 0) goto pc + 1 */
 348                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
 349                 *insn++ = BPF_EXIT_INSN();
 350                 if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
 351                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
 352                                             offsetof(struct net_device, ifindex));
 353                 else
 354                         *insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
 355                                             offsetof(struct net_device, type));
 356                 break;
 357 
 358         case SKF_AD_OFF + SKF_AD_MARK:
 359                 cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
 360                 insn += cnt - 1;
 361                 break;
 362 
 363         case SKF_AD_OFF + SKF_AD_RXHASH:
 364                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);
 365 
 366                 *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
 367                                     offsetof(struct sk_buff, hash));
 368                 break;
 369 
 370         case SKF_AD_OFF + SKF_AD_QUEUE:
 371                 cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
 372                 insn += cnt - 1;
 373                 break;
 374 
 375         case SKF_AD_OFF + SKF_AD_VLAN_TAG:
 376                 cnt = convert_skb_access(SKF_AD_VLAN_TAG,
 377                                          BPF_REG_A, BPF_REG_CTX, insn);
 378                 insn += cnt - 1;
 379                 break;
 380 
 381         case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
 382                 cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
 383                                          BPF_REG_A, BPF_REG_CTX, insn);
 384                 insn += cnt - 1;
 385                 break;
 386 
 387         case SKF_AD_OFF + SKF_AD_VLAN_TPID:
 388                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);
 389 
 390                 /* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
 391                 *insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
 392                                       offsetof(struct sk_buff, vlan_proto));
 393                 /* A = ntohs(A) [emitting a nop or swap16] */
 394                 *insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
 395                 break;
 396 
 397         case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 398         case SKF_AD_OFF + SKF_AD_NLATTR:
 399         case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 400         case SKF_AD_OFF + SKF_AD_CPU:
 401         case SKF_AD_OFF + SKF_AD_RANDOM:
 402                 /* arg1 = CTX */
 403                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 404                 /* arg2 = A */
 405                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
 406                 /* arg3 = X */
 407                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
 408                 /* Emit call(arg1=CTX, arg2=A, arg3=X) */
 409                 switch (fp->k) {
 410                 case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
 411                         *insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
 412                         break;
 413                 case SKF_AD_OFF + SKF_AD_NLATTR:
 414                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
 415                         break;
 416                 case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
 417                         *insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
 418                         break;
 419                 case SKF_AD_OFF + SKF_AD_CPU:
 420                         *insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
 421                         break;
 422                 case SKF_AD_OFF + SKF_AD_RANDOM:
 423                         *insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
 424                         bpf_user_rnd_init_once();
 425                         break;
 426                 }
 427                 break;
 428 
 429         case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
 430                 /* A ^= X */
 431                 *insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
 432                 break;
 433 
 434         default:
 435                 /* This is just a dummy call to avoid letting the compiler
 436                  * evict __bpf_call_base() as an optimization. Placed here
 437                  * where no-one bothers.
 438                  */
 439                 BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
 440                 return false;
 441         }
 442 
 443         *insnp = insn;
 444         return true;
 445 }
 446 
 447 static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
 448 {
 449         const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
 450         int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
 451         bool endian = BPF_SIZE(fp->code) == BPF_H ||
 452                       BPF_SIZE(fp->code) == BPF_W;
 453         bool indirect = BPF_MODE(fp->code) == BPF_IND;
 454         const int ip_align = NET_IP_ALIGN;
 455         struct bpf_insn *insn = *insnp;
 456         int offset = fp->k;
 457 
 458         if (!indirect &&
 459             ((unaligned_ok && offset >= 0) ||
 460              (!unaligned_ok && offset >= 0 &&
 461               offset + ip_align >= 0 &&
 462               offset + ip_align % size == 0))) {
 463                 bool ldx_off_ok = offset <= S16_MAX;
 464 
 465                 *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
 466                 if (offset)
 467                         *insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
 468                 *insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
 469                                       size, 2 + endian + (!ldx_off_ok * 2));
 470                 if (ldx_off_ok) {
 471                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 472                                               BPF_REG_D, offset);
 473                 } else {
 474                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
 475                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
 476                         *insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
 477                                               BPF_REG_TMP, 0);
 478                 }
 479                 if (endian)
 480                         *insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
 481                 *insn++ = BPF_JMP_A(8);
 482         }
 483 
 484         *insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
 485         *insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
 486         *insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
 487         if (!indirect) {
 488                 *insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
 489         } else {
 490                 *insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
 491                 if (fp->k)
 492                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
 493         }
 494 
 495         switch (BPF_SIZE(fp->code)) {
 496         case BPF_B:
 497                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
 498                 break;
 499         case BPF_H:
 500                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
 501                 break;
 502         case BPF_W:
 503                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
 504                 break;
 505         default:
 506                 return false;
 507         }
 508 
 509         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
 510         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 511         *insn   = BPF_EXIT_INSN();
 512 
 513         *insnp = insn;
 514         return true;
 515 }
 516 
 517 /**
 518  *      bpf_convert_filter - convert filter program
 519  *      @prog: the user passed filter program
 520  *      @len: the length of the user passed filter program
 521  *      @new_prog: allocated 'struct bpf_prog' or NULL
 522  *      @new_len: pointer to store length of converted program
 523  *      @seen_ld_abs: bool whether we've seen ld_abs/ind
 524  *
 525  * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
 526  * style extended BPF (eBPF).
 527  * Conversion workflow:
 528  *
 529  * 1) First pass for calculating the new program length:
 530  *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
 531  *
 532  * 2) 2nd pass to remap in two passes: 1st pass finds new
 533  *    jump offsets, 2nd pass remapping:
 534  *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
 535  */
 536 static int bpf_convert_filter(struct sock_filter *prog, int len,
 537                               struct bpf_prog *new_prog, int *new_len,
 538                               bool *seen_ld_abs)
 539 {
 540         int new_flen = 0, pass = 0, target, i, stack_off;
 541         struct bpf_insn *new_insn, *first_insn = NULL;
 542         struct sock_filter *fp;
 543         int *addrs = NULL;
 544         u8 bpf_src;
 545 
 546         BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
 547         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
 548 
 549         if (len <= 0 || len > BPF_MAXINSNS)
 550                 return -EINVAL;
 551 
 552         if (new_prog) {
 553                 first_insn = new_prog->insnsi;
 554                 addrs = kcalloc(len, sizeof(*addrs),
 555                                 GFP_KERNEL | __GFP_NOWARN);
 556                 if (!addrs)
 557                         return -ENOMEM;
 558         }
 559 
 560 do_pass:
 561         new_insn = first_insn;
 562         fp = prog;
 563 
 564         /* Classic BPF related prologue emission. */
 565         if (new_prog) {
 566                 /* Classic BPF expects A and X to be reset first. These need
 567                  * to be guaranteed to be the first two instructions.
 568                  */
 569                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 570                 *new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
 571 
 572                 /* All programs must keep CTX in callee saved BPF_REG_CTX.
 573                  * In eBPF case it's done by the compiler, here we need to
 574                  * do this ourself. Initial CTX is present in BPF_REG_ARG1.
 575                  */
 576                 *new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
 577                 if (*seen_ld_abs) {
 578                         /* For packet access in classic BPF, cache skb->data
 579                          * in callee-saved BPF R8 and skb->len - skb->data_len
 580                          * (headlen) in BPF R9. Since classic BPF is read-only
 581                          * on CTX, we only need to cache it once.
 582                          */
 583                         *new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
 584                                                   BPF_REG_D, BPF_REG_CTX,
 585                                                   offsetof(struct sk_buff, data));
 586                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
 587                                                   offsetof(struct sk_buff, len));
 588                         *new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
 589                                                   offsetof(struct sk_buff, data_len));
 590                         *new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
 591                 }
 592         } else {
 593                 new_insn += 3;
 594         }
 595 
 596         for (i = 0; i < len; fp++, i++) {
 597                 struct bpf_insn tmp_insns[32] = { };
 598                 struct bpf_insn *insn = tmp_insns;
 599 
 600                 if (addrs)
 601                         addrs[i] = new_insn - first_insn;
 602 
 603                 switch (fp->code) {
 604                 /* All arithmetic insns and skb loads map as-is. */
 605                 case BPF_ALU | BPF_ADD | BPF_X:
 606                 case BPF_ALU | BPF_ADD | BPF_K:
 607                 case BPF_ALU | BPF_SUB | BPF_X:
 608                 case BPF_ALU | BPF_SUB | BPF_K:
 609                 case BPF_ALU | BPF_AND | BPF_X:
 610                 case BPF_ALU | BPF_AND | BPF_K:
 611                 case BPF_ALU | BPF_OR | BPF_X:
 612                 case BPF_ALU | BPF_OR | BPF_K:
 613                 case BPF_ALU | BPF_LSH | BPF_X:
 614                 case BPF_ALU | BPF_LSH | BPF_K:
 615                 case BPF_ALU | BPF_RSH | BPF_X:
 616                 case BPF_ALU | BPF_RSH | BPF_K:
 617                 case BPF_ALU | BPF_XOR | BPF_X:
 618                 case BPF_ALU | BPF_XOR | BPF_K:
 619                 case BPF_ALU | BPF_MUL | BPF_X:
 620                 case BPF_ALU | BPF_MUL | BPF_K:
 621                 case BPF_ALU | BPF_DIV | BPF_X:
 622                 case BPF_ALU | BPF_DIV | BPF_K:
 623                 case BPF_ALU | BPF_MOD | BPF_X:
 624                 case BPF_ALU | BPF_MOD | BPF_K:
 625                 case BPF_ALU | BPF_NEG:
 626                 case BPF_LD | BPF_ABS | BPF_W:
 627                 case BPF_LD | BPF_ABS | BPF_H:
 628                 case BPF_LD | BPF_ABS | BPF_B:
 629                 case BPF_LD | BPF_IND | BPF_W:
 630                 case BPF_LD | BPF_IND | BPF_H:
 631                 case BPF_LD | BPF_IND | BPF_B:
 632                         /* Check for overloaded BPF extension and
 633                          * directly convert it if found, otherwise
 634                          * just move on with mapping.
 635                          */
 636                         if (BPF_CLASS(fp->code) == BPF_LD &&
 637                             BPF_MODE(fp->code) == BPF_ABS &&
 638                             convert_bpf_extensions(fp, &insn))
 639                                 break;
 640                         if (BPF_CLASS(fp->code) == BPF_LD &&
 641                             convert_bpf_ld_abs(fp, &insn)) {
 642                                 *seen_ld_abs = true;
 643                                 break;
 644                         }
 645 
 646                         if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
 647                             fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
 648                                 *insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
 649                                 /* Error with exception code on div/mod by 0.
 650                                  * For cBPF programs, this was always return 0.
 651                                  */
 652                                 *insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
 653                                 *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
 654                                 *insn++ = BPF_EXIT_INSN();
 655                         }
 656 
 657                         *insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
 658                         break;
 659 
 660                 /* Jump transformation cannot use BPF block macros
 661                  * everywhere as offset calculation and target updates
 662                  * require a bit more work than the rest, i.e. jump
 663                  * opcodes map as-is, but offsets need adjustment.
 664                  */
 665 
 666 #define BPF_EMIT_JMP                                                    \
 667         do {                                                            \
 668                 const s32 off_min = S16_MIN, off_max = S16_MAX;         \
 669                 s32 off;                                                \
 670                                                                         \
 671                 if (target >= len || target < 0)                        \
 672                         goto err;                                       \
 673                 off = addrs ? addrs[target] - addrs[i] - 1 : 0;         \
 674                 /* Adjust pc relative offset for 2nd or 3rd insn. */    \
 675                 off -= insn - tmp_insns;                                \
 676                 /* Reject anything not fitting into insn->off. */       \
 677                 if (off < off_min || off > off_max)                     \
 678                         goto err;                                       \
 679                 insn->off = off;                                        \
 680         } while (0)
 681 
 682                 case BPF_JMP | BPF_JA:
 683                         target = i + fp->k + 1;
 684                         insn->code = fp->code;
 685                         BPF_EMIT_JMP;
 686                         break;
 687 
 688                 case BPF_JMP | BPF_JEQ | BPF_K:
 689                 case BPF_JMP | BPF_JEQ | BPF_X:
 690                 case BPF_JMP | BPF_JSET | BPF_K:
 691                 case BPF_JMP | BPF_JSET | BPF_X:
 692                 case BPF_JMP | BPF_JGT | BPF_K:
 693                 case BPF_JMP | BPF_JGT | BPF_X:
 694                 case BPF_JMP | BPF_JGE | BPF_K:
 695                 case BPF_JMP | BPF_JGE | BPF_X:
 696                         if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
 697                                 /* BPF immediates are signed, zero extend
 698                                  * immediate into tmp register and use it
 699                                  * in compare insn.
 700                                  */
 701                                 *insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
 702 
 703                                 insn->dst_reg = BPF_REG_A;
 704                                 insn->src_reg = BPF_REG_TMP;
 705                                 bpf_src = BPF_X;
 706                         } else {
 707                                 insn->dst_reg = BPF_REG_A;
 708                                 insn->imm = fp->k;
 709                                 bpf_src = BPF_SRC(fp->code);
 710                                 insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
 711                         }
 712 
 713                         /* Common case where 'jump_false' is next insn. */
 714                         if (fp->jf == 0) {
 715                                 insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 716                                 target = i + fp->jt + 1;
 717                                 BPF_EMIT_JMP;
 718                                 break;
 719                         }
 720 
 721                         /* Convert some jumps when 'jump_true' is next insn. */
 722                         if (fp->jt == 0) {
 723                                 switch (BPF_OP(fp->code)) {
 724                                 case BPF_JEQ:
 725                                         insn->code = BPF_JMP | BPF_JNE | bpf_src;
 726                                         break;
 727                                 case BPF_JGT:
 728                                         insn->code = BPF_JMP | BPF_JLE | bpf_src;
 729                                         break;
 730                                 case BPF_JGE:
 731                                         insn->code = BPF_JMP | BPF_JLT | bpf_src;
 732                                         break;
 733                                 default:
 734                                         goto jmp_rest;
 735                                 }
 736 
 737                                 target = i + fp->jf + 1;
 738                                 BPF_EMIT_JMP;
 739                                 break;
 740                         }
 741 jmp_rest:
 742                         /* Other jumps are mapped into two insns: Jxx and JA. */
 743                         target = i + fp->jt + 1;
 744                         insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
 745                         BPF_EMIT_JMP;
 746                         insn++;
 747 
 748                         insn->code = BPF_JMP | BPF_JA;
 749                         target = i + fp->jf + 1;
 750                         BPF_EMIT_JMP;
 751                         break;
 752 
 753                 /* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
 754                 case BPF_LDX | BPF_MSH | BPF_B: {
 755                         struct sock_filter tmp = {
 756                                 .code   = BPF_LD | BPF_ABS | BPF_B,
 757                                 .k      = fp->k,
 758                         };
 759 
 760                         *seen_ld_abs = true;
 761 
 762                         /* X = A */
 763                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 764                         /* A = BPF_R0 = *(u8 *) (skb->data + K) */
 765                         convert_bpf_ld_abs(&tmp, &insn);
 766                         insn++;
 767                         /* A &= 0xf */
 768                         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
 769                         /* A <<= 2 */
 770                         *insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
 771                         /* tmp = X */
 772                         *insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
 773                         /* X = A */
 774                         *insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 775                         /* A = tmp */
 776                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
 777                         break;
 778                 }
 779                 /* RET_K is remaped into 2 insns. RET_A case doesn't need an
 780                  * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
 781                  */
 782                 case BPF_RET | BPF_A:
 783                 case BPF_RET | BPF_K:
 784                         if (BPF_RVAL(fp->code) == BPF_K)
 785                                 *insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
 786                                                         0, fp->k);
 787                         *insn = BPF_EXIT_INSN();
 788                         break;
 789 
 790                 /* Store to stack. */
 791                 case BPF_ST:
 792                 case BPF_STX:
 793                         stack_off = fp->k * 4  + 4;
 794                         *insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
 795                                             BPF_ST ? BPF_REG_A : BPF_REG_X,
 796                                             -stack_off);
 797                         /* check_load_and_stores() verifies that classic BPF can
 798                          * load from stack only after write, so tracking
 799                          * stack_depth for ST|STX insns is enough
 800                          */
 801                         if (new_prog && new_prog->aux->stack_depth < stack_off)
 802                                 new_prog->aux->stack_depth = stack_off;
 803                         break;
 804 
 805                 /* Load from stack. */
 806                 case BPF_LD | BPF_MEM:
 807                 case BPF_LDX | BPF_MEM:
 808                         stack_off = fp->k * 4  + 4;
 809                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
 810                                             BPF_REG_A : BPF_REG_X, BPF_REG_FP,
 811                                             -stack_off);
 812                         break;
 813 
 814                 /* A = K or X = K */
 815                 case BPF_LD | BPF_IMM:
 816                 case BPF_LDX | BPF_IMM:
 817                         *insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
 818                                               BPF_REG_A : BPF_REG_X, fp->k);
 819                         break;
 820 
 821                 /* X = A */
 822                 case BPF_MISC | BPF_TAX:
 823                         *insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
 824                         break;
 825 
 826                 /* A = X */
 827                 case BPF_MISC | BPF_TXA:
 828                         *insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
 829                         break;
 830 
 831                 /* A = skb->len or X = skb->len */
 832                 case BPF_LD | BPF_W | BPF_LEN:
 833                 case BPF_LDX | BPF_W | BPF_LEN:
 834                         *insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
 835                                             BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
 836                                             offsetof(struct sk_buff, len));
 837                         break;
 838 
 839                 /* Access seccomp_data fields. */
 840                 case BPF_LDX | BPF_ABS | BPF_W:
 841                         /* A = *(u32 *) (ctx + K) */
 842                         *insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
 843                         break;
 844 
 845                 /* Unknown instruction. */
 846                 default:
 847                         goto err;
 848                 }
 849 
 850                 insn++;
 851                 if (new_prog)
 852                         memcpy(new_insn, tmp_insns,
 853                                sizeof(*insn) * (insn - tmp_insns));
 854                 new_insn += insn - tmp_insns;
 855         }
 856 
 857         if (!new_prog) {
 858                 /* Only calculating new length. */
 859                 *new_len = new_insn - first_insn;
 860                 if (*seen_ld_abs)
 861                         *new_len += 4; /* Prologue bits. */
 862                 return 0;
 863         }
 864 
 865         pass++;
 866         if (new_flen != new_insn - first_insn) {
 867                 new_flen = new_insn - first_insn;
 868                 if (pass > 2)
 869                         goto err;
 870                 goto do_pass;
 871         }
 872 
 873         kfree(addrs);
 874         BUG_ON(*new_len != new_flen);
 875         return 0;
 876 err:
 877         kfree(addrs);
 878         return -EINVAL;
 879 }
 880 
 881 /* Security:
 882  *
 883  * As we dont want to clear mem[] array for each packet going through
 884  * __bpf_prog_run(), we check that filter loaded by user never try to read
 885  * a cell if not previously written, and we check all branches to be sure
 886  * a malicious user doesn't try to abuse us.
 887  */
 888 static int check_load_and_stores(const struct sock_filter *filter, int flen)
 889 {
 890         u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
 891         int pc, ret = 0;
 892 
 893         BUILD_BUG_ON(BPF_MEMWORDS > 16);
 894 
 895         masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
 896         if (!masks)
 897                 return -ENOMEM;
 898 
 899         memset(masks, 0xff, flen * sizeof(*masks));
 900 
 901         for (pc = 0; pc < flen; pc++) {
 902                 memvalid &= masks[pc];
 903 
 904                 switch (filter[pc].code) {
 905                 case BPF_ST:
 906                 case BPF_STX:
 907                         memvalid |= (1 << filter[pc].k);
 908                         break;
 909                 case BPF_LD | BPF_MEM:
 910                 case BPF_LDX | BPF_MEM:
 911                         if (!(memvalid & (1 << filter[pc].k))) {
 912                                 ret = -EINVAL;
 913                                 goto error;
 914                         }
 915                         break;
 916                 case BPF_JMP | BPF_JA:
 917                         /* A jump must set masks on target */
 918                         masks[pc + 1 + filter[pc].k] &= memvalid;
 919                         memvalid = ~0;
 920                         break;
 921                 case BPF_JMP | BPF_JEQ | BPF_K:
 922                 case BPF_JMP | BPF_JEQ | BPF_X:
 923                 case BPF_JMP | BPF_JGE | BPF_K:
 924                 case BPF_JMP | BPF_JGE | BPF_X:
 925                 case BPF_JMP | BPF_JGT | BPF_K:
 926                 case BPF_JMP | BPF_JGT | BPF_X:
 927                 case BPF_JMP | BPF_JSET | BPF_K:
 928                 case BPF_JMP | BPF_JSET | BPF_X:
 929                         /* A jump must set masks on targets */
 930                         masks[pc + 1 + filter[pc].jt] &= memvalid;
 931                         masks[pc + 1 + filter[pc].jf] &= memvalid;
 932                         memvalid = ~0;
 933                         break;
 934                 }
 935         }
 936 error:
 937         kfree(masks);
 938         return ret;
 939 }
 940 
 941 static bool chk_code_allowed(u16 code_to_probe)
 942 {
 943         static const bool codes[] = {
 944                 /* 32 bit ALU operations */
 945                 [BPF_ALU | BPF_ADD | BPF_K] = true,
 946                 [BPF_ALU | BPF_ADD | BPF_X] = true,
 947                 [BPF_ALU | BPF_SUB | BPF_K] = true,
 948                 [BPF_ALU | BPF_SUB | BPF_X] = true,
 949                 [BPF_ALU | BPF_MUL | BPF_K] = true,
 950                 [BPF_ALU | BPF_MUL | BPF_X] = true,
 951                 [BPF_ALU | BPF_DIV | BPF_K] = true,
 952                 [BPF_ALU | BPF_DIV | BPF_X] = true,
 953                 [BPF_ALU | BPF_MOD | BPF_K] = true,
 954                 [BPF_ALU | BPF_MOD | BPF_X] = true,
 955                 [BPF_ALU | BPF_AND | BPF_K] = true,
 956                 [BPF_ALU | BPF_AND | BPF_X] = true,
 957                 [BPF_ALU | BPF_OR | BPF_K] = true,
 958                 [BPF_ALU | BPF_OR | BPF_X] = true,
 959                 [BPF_ALU | BPF_XOR | BPF_K] = true,
 960                 [BPF_ALU | BPF_XOR | BPF_X] = true,
 961                 [BPF_ALU | BPF_LSH | BPF_K] = true,
 962                 [BPF_ALU | BPF_LSH | BPF_X] = true,
 963                 [BPF_ALU | BPF_RSH | BPF_K] = true,
 964                 [BPF_ALU | BPF_RSH | BPF_X] = true,
 965                 [BPF_ALU | BPF_NEG] = true,
 966                 /* Load instructions */
 967                 [BPF_LD | BPF_W | BPF_ABS] = true,
 968                 [BPF_LD | BPF_H | BPF_ABS] = true,
 969                 [BPF_LD | BPF_B | BPF_ABS] = true,
 970                 [BPF_LD | BPF_W | BPF_LEN] = true,
 971                 [BPF_LD | BPF_W | BPF_IND] = true,
 972                 [BPF_LD | BPF_H | BPF_IND] = true,
 973                 [BPF_LD | BPF_B | BPF_IND] = true,
 974                 [BPF_LD | BPF_IMM] = true,
 975                 [BPF_LD | BPF_MEM] = true,
 976                 [BPF_LDX | BPF_W | BPF_LEN] = true,
 977                 [BPF_LDX | BPF_B | BPF_MSH] = true,
 978                 [BPF_LDX | BPF_IMM] = true,
 979                 [BPF_LDX | BPF_MEM] = true,
 980                 /* Store instructions */
 981                 [BPF_ST] = true,
 982                 [BPF_STX] = true,
 983                 /* Misc instructions */
 984                 [BPF_MISC | BPF_TAX] = true,
 985                 [BPF_MISC | BPF_TXA] = true,
 986                 /* Return instructions */
 987                 [BPF_RET | BPF_K] = true,
 988                 [BPF_RET | BPF_A] = true,
 989                 /* Jump instructions */
 990                 [BPF_JMP | BPF_JA] = true,
 991                 [BPF_JMP | BPF_JEQ | BPF_K] = true,
 992                 [BPF_JMP | BPF_JEQ | BPF_X] = true,
 993                 [BPF_JMP | BPF_JGE | BPF_K] = true,
 994                 [BPF_JMP | BPF_JGE | BPF_X] = true,
 995                 [BPF_JMP | BPF_JGT | BPF_K] = true,
 996                 [BPF_JMP | BPF_JGT | BPF_X] = true,
 997                 [BPF_JMP | BPF_JSET | BPF_K] = true,
 998                 [BPF_JMP | BPF_JSET | BPF_X] = true,
 999         };
1000 
1001         if (code_to_probe >= ARRAY_SIZE(codes))
1002                 return false;
1003 
1004         return codes[code_to_probe];
1005 }
1006 
1007 static bool bpf_check_basics_ok(const struct sock_filter *filter,
1008                                 unsigned int flen)
1009 {
1010         if (filter == NULL)
1011                 return false;
1012         if (flen == 0 || flen > BPF_MAXINSNS)
1013                 return false;
1014 
1015         return true;
1016 }
1017 
1018 /**
1019  *      bpf_check_classic - verify socket filter code
1020  *      @filter: filter to verify
1021  *      @flen: length of filter
1022  *
1023  * Check the user's filter code. If we let some ugly
1024  * filter code slip through kaboom! The filter must contain
1025  * no references or jumps that are out of range, no illegal
1026  * instructions, and must end with a RET instruction.
1027  *
1028  * All jumps are forward as they are not signed.
1029  *
1030  * Returns 0 if the rule set is legal or -EINVAL if not.
1031  */
1032 static int bpf_check_classic(const struct sock_filter *filter,
1033                              unsigned int flen)
1034 {
1035         bool anc_found;
1036         int pc;
1037 
1038         /* Check the filter code now */
1039         for (pc = 0; pc < flen; pc++) {
1040                 const struct sock_filter *ftest = &filter[pc];
1041 
1042                 /* May we actually operate on this code? */
1043                 if (!chk_code_allowed(ftest->code))
1044                         return -EINVAL;
1045 
1046                 /* Some instructions need special checks */
1047                 switch (ftest->code) {
1048                 case BPF_ALU | BPF_DIV | BPF_K:
1049                 case BPF_ALU | BPF_MOD | BPF_K:
1050                         /* Check for division by zero */
1051                         if (ftest->k == 0)
1052                                 return -EINVAL;
1053                         break;
1054                 case BPF_ALU | BPF_LSH | BPF_K:
1055                 case BPF_ALU | BPF_RSH | BPF_K:
1056                         if (ftest->k >= 32)
1057                                 return -EINVAL;
1058                         break;
1059                 case BPF_LD | BPF_MEM:
1060                 case BPF_LDX | BPF_MEM:
1061                 case BPF_ST:
1062                 case BPF_STX:
1063                         /* Check for invalid memory addresses */
1064                         if (ftest->k >= BPF_MEMWORDS)
1065                                 return -EINVAL;
1066                         break;
1067                 case BPF_JMP | BPF_JA:
1068                         /* Note, the large ftest->k might cause loops.
1069                          * Compare this with conditional jumps below,
1070                          * where offsets are limited. --ANK (981016)
1071                          */
1072                         if (ftest->k >= (unsigned int)(flen - pc - 1))
1073                                 return -EINVAL;
1074                         break;
1075                 case BPF_JMP | BPF_JEQ | BPF_K:
1076                 case BPF_JMP | BPF_JEQ | BPF_X:
1077                 case BPF_JMP | BPF_JGE | BPF_K:
1078                 case BPF_JMP | BPF_JGE | BPF_X:
1079                 case BPF_JMP | BPF_JGT | BPF_K:
1080                 case BPF_JMP | BPF_JGT | BPF_X:
1081                 case BPF_JMP | BPF_JSET | BPF_K:
1082                 case BPF_JMP | BPF_JSET | BPF_X:
1083                         /* Both conditionals must be safe */
1084                         if (pc + ftest->jt + 1 >= flen ||
1085                             pc + ftest->jf + 1 >= flen)
1086                                 return -EINVAL;
1087                         break;
1088                 case BPF_LD | BPF_W | BPF_ABS:
1089                 case BPF_LD | BPF_H | BPF_ABS:
1090                 case BPF_LD | BPF_B | BPF_ABS:
1091                         anc_found = false;
1092                         if (bpf_anc_helper(ftest) & BPF_ANC)
1093                                 anc_found = true;
1094                         /* Ancillary operation unknown or unsupported */
1095                         if (anc_found == false && ftest->k >= SKF_AD_OFF)
1096                                 return -EINVAL;
1097                 }
1098         }
1099 
1100         /* Last instruction must be a RET code */
1101         switch (filter[flen - 1].code) {
1102         case BPF_RET | BPF_K:
1103         case BPF_RET | BPF_A:
1104                 return check_load_and_stores(filter, flen);
1105         }
1106 
1107         return -EINVAL;
1108 }
1109 
1110 static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
1111                                       const struct sock_fprog *fprog)
1112 {
1113         unsigned int fsize = bpf_classic_proglen(fprog);
1114         struct sock_fprog_kern *fkprog;
1115 
1116         fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
1117         if (!fp->orig_prog)
1118                 return -ENOMEM;
1119 
1120         fkprog = fp->orig_prog;
1121         fkprog->len = fprog->len;
1122 
1123         fkprog->filter = kmemdup(fp->insns, fsize,
1124                                  GFP_KERNEL | __GFP_NOWARN);
1125         if (!fkprog->filter) {
1126                 kfree(fp->orig_prog);
1127                 return -ENOMEM;
1128         }
1129 
1130         return 0;
1131 }
1132 
1133 static void bpf_release_orig_filter(struct bpf_prog *fp)
1134 {
1135         struct sock_fprog_kern *fprog = fp->orig_prog;
1136 
1137         if (fprog) {
1138                 kfree(fprog->filter);
1139                 kfree(fprog);
1140         }
1141 }
1142 
1143 static void __bpf_prog_release(struct bpf_prog *prog)
1144 {
1145         if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1146                 bpf_prog_put(prog);
1147         } else {
1148                 bpf_release_orig_filter(prog);
1149                 bpf_prog_free(prog);
1150         }
1151 }
1152 
1153 static void __sk_filter_release(struct sk_filter *fp)
1154 {
1155         __bpf_prog_release(fp->prog);
1156         kfree(fp);
1157 }
1158 
1159 /**
1160  *      sk_filter_release_rcu - Release a socket filter by rcu_head
1161  *      @rcu: rcu_head that contains the sk_filter to free
1162  */
1163 static void sk_filter_release_rcu(struct rcu_head *rcu)
1164 {
1165         struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);
1166 
1167         __sk_filter_release(fp);
1168 }
1169 
1170 /**
1171  *      sk_filter_release - release a socket filter
1172  *      @fp: filter to remove
1173  *
1174  *      Remove a filter from a socket and release its resources.
1175  */
1176 static void sk_filter_release(struct sk_filter *fp)
1177 {
1178         if (refcount_dec_and_test(&fp->refcnt))
1179                 call_rcu(&fp->rcu, sk_filter_release_rcu);
1180 }
1181 
1182 void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
1183 {
1184         u32 filter_size = bpf_prog_size(fp->prog->len);
1185 
1186         atomic_sub(filter_size, &sk->sk_omem_alloc);
1187         sk_filter_release(fp);
1188 }
1189 
1190 /* try to charge the socket memory if there is space available
1191  * return true on success
1192  */
1193 static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1194 {
1195         u32 filter_size = bpf_prog_size(fp->prog->len);
1196 
1197         /* same check as in sock_kmalloc() */
1198         if (filter_size <= sysctl_optmem_max &&
1199             atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
1200                 atomic_add(filter_size, &sk->sk_omem_alloc);
1201                 return true;
1202         }
1203         return false;
1204 }
1205 
1206 bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1207 {
1208         if (!refcount_inc_not_zero(&fp->refcnt))
1209                 return false;
1210 
1211         if (!__sk_filter_charge(sk, fp)) {
1212                 sk_filter_release(fp);
1213                 return false;
1214         }
1215         return true;
1216 }
1217 
1218 static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1219 {
1220         struct sock_filter *old_prog;
1221         struct bpf_prog *old_fp;
1222         int err, new_len, old_len = fp->len;
1223         bool seen_ld_abs = false;
1224 
1225         /* We are free to overwrite insns et al right here as it
1226          * won't be used at this point in time anymore internally
1227          * after the migration to the internal BPF instruction
1228          * representation.
1229          */
1230         BUILD_BUG_ON(sizeof(struct sock_filter) !=
1231                      sizeof(struct bpf_insn));
1232 
1233         /* Conversion cannot happen on overlapping memory areas,
1234          * so we need to keep the user BPF around until the 2nd
1235          * pass. At this time, the user BPF is stored in fp->insns.
1236          */
1237         old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1238                            GFP_KERNEL | __GFP_NOWARN);
1239         if (!old_prog) {
1240                 err = -ENOMEM;
1241                 goto out_err;
1242         }
1243 
1244         /* 1st pass: calculate the new program length. */
1245         err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
1246                                  &seen_ld_abs);
1247         if (err)
1248                 goto out_err_free;
1249 
1250         /* Expand fp for appending the new filter representation. */
1251         old_fp = fp;
1252         fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1253         if (!fp) {
1254                 /* The old_fp is still around in case we couldn't
1255                  * allocate new memory, so uncharge on that one.
1256                  */
1257                 fp = old_fp;
1258                 err = -ENOMEM;
1259                 goto out_err_free;
1260         }
1261 
1262         fp->len = new_len;
1263 
1264         /* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1265         err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
1266                                  &seen_ld_abs);
1267         if (err)
1268                 /* 2nd bpf_convert_filter() can fail only if it fails
1269                  * to allocate memory, remapping must succeed. Note,
1270                  * that at this time old_fp has already been released
1271                  * by krealloc().
1272                  */
1273                 goto out_err_free;
1274 
1275         fp = bpf_prog_select_runtime(fp, &err);
1276         if (err)
1277                 goto out_err_free;
1278 
1279         kfree(old_prog);
1280         return fp;
1281 
1282 out_err_free:
1283         kfree(old_prog);
1284 out_err:
1285         __bpf_prog_release(fp);
1286         return ERR_PTR(err);
1287 }
1288 
1289 static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
1290                                            bpf_aux_classic_check_t trans)
1291 {
1292         int err;
1293 
1294         fp->bpf_func = NULL;
1295         fp->jited = 0;
1296 
1297         err = bpf_check_classic(fp->insns, fp->len);
1298         if (err) {
1299                 __bpf_prog_release(fp);
1300                 return ERR_PTR(err);
1301         }
1302 
1303         /* There might be additional checks and transformations
1304          * needed on classic filters, f.e. in case of seccomp.
1305          */
1306         if (trans) {
1307                 err = trans(fp->insns, fp->len);
1308                 if (err) {
1309                         __bpf_prog_release(fp);
1310                         return ERR_PTR(err);
1311                 }
1312         }
1313 
1314         /* Probe if we can JIT compile the filter and if so, do
1315          * the compilation of the filter.
1316          */
1317         bpf_jit_compile(fp);
1318 
1319         /* JIT compiler couldn't process this filter, so do the
1320          * internal BPF translation for the optimized interpreter.
1321          */
1322         if (!fp->jited)
1323                 fp = bpf_migrate_filter(fp);
1324 
1325         return fp;
1326 }
1327 
1328 /**
1329  *      bpf_prog_create - create an unattached filter
1330  *      @pfp: the unattached filter that is created
1331  *      @fprog: the filter program
1332  *
1333  * Create a filter independent of any socket. We first run some
1334  * sanity checks on it to make sure it does not explode on us later.
1335  * If an error occurs or there is insufficient memory for the filter
1336  * a negative errno code is returned. On success the return is zero.
1337  */
1338 int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1339 {
1340         unsigned int fsize = bpf_classic_proglen(fprog);
1341         struct bpf_prog *fp;
1342 
1343         /* Make sure new filter is there and in the right amounts. */
1344         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1345                 return -EINVAL;
1346 
1347         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1348         if (!fp)
1349                 return -ENOMEM;
1350 
1351         memcpy(fp->insns, fprog->filter, fsize);
1352 
1353         fp->len = fprog->len;
1354         /* Since unattached filters are not copied back to user
1355          * space through sk_get_filter(), we do not need to hold
1356          * a copy here, and can spare us the work.
1357          */
1358         fp->orig_prog = NULL;
1359 
1360         /* bpf_prepare_filter() already takes care of freeing
1361          * memory in case something goes wrong.
1362          */
1363         fp = bpf_prepare_filter(fp, NULL);
1364         if (IS_ERR(fp))
1365                 return PTR_ERR(fp);
1366 
1367         *pfp = fp;
1368         return 0;
1369 }
1370 EXPORT_SYMBOL_GPL(bpf_prog_create);
1371 
1372 /**
1373  *      bpf_prog_create_from_user - create an unattached filter from user buffer
1374  *      @pfp: the unattached filter that is created
1375  *      @fprog: the filter program
1376  *      @trans: post-classic verifier transformation handler
1377  *      @save_orig: save classic BPF program
1378  *
1379  * This function effectively does the same as bpf_prog_create(), only
1380  * that it builds up its insns buffer from user space provided buffer.
1381  * It also allows for passing a bpf_aux_classic_check_t handler.
1382  */
1383 int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1384                               bpf_aux_classic_check_t trans, bool save_orig)
1385 {
1386         unsigned int fsize = bpf_classic_proglen(fprog);
1387         struct bpf_prog *fp;
1388         int err;
1389 
1390         /* Make sure new filter is there and in the right amounts. */
1391         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1392                 return -EINVAL;
1393 
1394         fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1395         if (!fp)
1396                 return -ENOMEM;
1397 
1398         if (copy_from_user(fp->insns, fprog->filter, fsize)) {
1399                 __bpf_prog_free(fp);
1400                 return -EFAULT;
1401         }
1402 
1403         fp->len = fprog->len;
1404         fp->orig_prog = NULL;
1405 
1406         if (save_orig) {
1407                 err = bpf_prog_store_orig_filter(fp, fprog);
1408                 if (err) {
1409                         __bpf_prog_free(fp);
1410                         return -ENOMEM;
1411                 }
1412         }
1413 
1414         /* bpf_prepare_filter() already takes care of freeing
1415          * memory in case something goes wrong.
1416          */
1417         fp = bpf_prepare_filter(fp, trans);
1418         if (IS_ERR(fp))
1419                 return PTR_ERR(fp);
1420 
1421         *pfp = fp;
1422         return 0;
1423 }
1424 EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1425 
1426 void bpf_prog_destroy(struct bpf_prog *fp)
1427 {
1428         __bpf_prog_release(fp);
1429 }
1430 EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1431 
1432 static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1433 {
1434         struct sk_filter *fp, *old_fp;
1435 
1436         fp = kmalloc(sizeof(*fp), GFP_KERNEL);
1437         if (!fp)
1438                 return -ENOMEM;
1439 
1440         fp->prog = prog;
1441 
1442         if (!__sk_filter_charge(sk, fp)) {
1443                 kfree(fp);
1444                 return -ENOMEM;
1445         }
1446         refcount_set(&fp->refcnt, 1);
1447 
1448         old_fp = rcu_dereference_protected(sk->sk_filter,
1449                                            lockdep_sock_is_held(sk));
1450         rcu_assign_pointer(sk->sk_filter, fp);
1451 
1452         if (old_fp)
1453                 sk_filter_uncharge(sk, old_fp);
1454 
1455         return 0;
1456 }
1457 
1458 static
1459 struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
1460 {
1461         unsigned int fsize = bpf_classic_proglen(fprog);
1462         struct bpf_prog *prog;
1463         int err;
1464 
1465         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1466                 return ERR_PTR(-EPERM);
1467 
1468         /* Make sure new filter is there and in the right amounts. */
1469         if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1470                 return ERR_PTR(-EINVAL);
1471 
1472         prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1473         if (!prog)
1474                 return ERR_PTR(-ENOMEM);
1475 
1476         if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1477                 __bpf_prog_free(prog);
1478                 return ERR_PTR(-EFAULT);
1479         }
1480 
1481         prog->len = fprog->len;
1482 
1483         err = bpf_prog_store_orig_filter(prog, fprog);
1484         if (err) {
1485                 __bpf_prog_free(prog);
1486                 return ERR_PTR(-ENOMEM);
1487         }
1488 
1489         /* bpf_prepare_filter() already takes care of freeing
1490          * memory in case something goes wrong.
1491          */
1492         return bpf_prepare_filter(prog, NULL);
1493 }
1494 
1495 /**
1496  *      sk_attach_filter - attach a socket filter
1497  *      @fprog: the filter program
1498  *      @sk: the socket to use
1499  *
1500  * Attach the user's filter code. We first run some sanity checks on
1501  * it to make sure it does not explode on us later. If an error
1502  * occurs or there is insufficient memory for the filter a negative
1503  * errno code is returned. On success the return is zero.
1504  */
1505 int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1506 {
1507         struct bpf_prog *prog = __get_filter(fprog, sk);
1508         int err;
1509 
1510         if (IS_ERR(prog))
1511                 return PTR_ERR(prog);
1512 
1513         err = __sk_attach_prog(prog, sk);
1514         if (err < 0) {
1515                 __bpf_prog_release(prog);
1516                 return err;
1517         }
1518 
1519         return 0;
1520 }
1521 EXPORT_SYMBOL_GPL(sk_attach_filter);
1522 
1523 int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1524 {
1525         struct bpf_prog *prog = __get_filter(fprog, sk);
1526         int err;
1527 
1528         if (IS_ERR(prog))
1529                 return PTR_ERR(prog);
1530 
1531         if (bpf_prog_size(prog->len) > sysctl_optmem_max)
1532                 err = -ENOMEM;
1533         else
1534                 err = reuseport_attach_prog(sk, prog);
1535 
1536         if (err)
1537                 __bpf_prog_release(prog);
1538 
1539         return err;
1540 }
1541 
1542 static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
1543 {
1544         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1545                 return ERR_PTR(-EPERM);
1546 
1547         return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1548 }
1549 
1550 int sk_attach_bpf(u32 ufd, struct sock *sk)
1551 {
1552         struct bpf_prog *prog = __get_bpf(ufd, sk);
1553         int err;
1554 
1555         if (IS_ERR(prog))
1556                 return PTR_ERR(prog);
1557 
1558         err = __sk_attach_prog(prog, sk);
1559         if (err < 0) {
1560                 bpf_prog_put(prog);
1561                 return err;
1562         }
1563 
1564         return 0;
1565 }
1566 
1567 int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
1568 {
1569         struct bpf_prog *prog;
1570         int err;
1571 
1572         if (sock_flag(sk, SOCK_FILTER_LOCKED))
1573                 return -EPERM;
1574 
1575         prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1576         if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
1577                 prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1578         if (IS_ERR(prog))
1579                 return PTR_ERR(prog);
1580 
1581         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
1582                 /* Like other non BPF_PROG_TYPE_SOCKET_FILTER
1583                  * bpf prog (e.g. sockmap).  It depends on the
1584                  * limitation imposed by bpf_prog_load().
1585                  * Hence, sysctl_optmem_max is not checked.
1586                  */
1587                 if ((sk->sk_type != SOCK_STREAM &&
1588                      sk->sk_type != SOCK_DGRAM) ||
1589                     (sk->sk_protocol != IPPROTO_UDP &&
1590                      sk->sk_protocol != IPPROTO_TCP) ||
1591                     (sk->sk_family != AF_INET &&
1592                      sk->sk_family != AF_INET6)) {
1593                         err = -ENOTSUPP;
1594                         goto err_prog_put;
1595                 }
1596         } else {
1597                 /* BPF_PROG_TYPE_SOCKET_FILTER */
1598                 if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
1599                         err = -ENOMEM;
1600                         goto err_prog_put;
1601                 }
1602         }
1603 
1604         err = reuseport_attach_prog(sk, prog);
1605 err_prog_put:
1606         if (err)
1607                 bpf_prog_put(prog);
1608 
1609         return err;
1610 }
1611 
1612 void sk_reuseport_prog_free(struct bpf_prog *prog)
1613 {
1614         if (!prog)
1615                 return;
1616 
1617         if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
1618                 bpf_prog_put(prog);
1619         else
1620                 bpf_prog_destroy(prog);
1621 }
1622 
1623 struct bpf_scratchpad {
1624         union {
1625                 __be32 diff[MAX_BPF_STACK / sizeof(__be32)];
1626                 u8     buff[MAX_BPF_STACK];
1627         };
1628 };
1629 
1630 static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1631 
1632 static inline int __bpf_try_make_writable(struct sk_buff *skb,
1633                                           unsigned int write_len)
1634 {
1635         return skb_ensure_writable(skb, write_len);
1636 }
1637 
1638 static inline int bpf_try_make_writable(struct sk_buff *skb,
1639                                         unsigned int write_len)
1640 {
1641         int err = __bpf_try_make_writable(skb, write_len);
1642 
1643         bpf_compute_data_pointers(skb);
1644         return err;
1645 }
1646 
1647 static int bpf_try_make_head_writable(struct sk_buff *skb)
1648 {
1649         return bpf_try_make_writable(skb, skb_headlen(skb));
1650 }
1651 
1652 static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
1653 {
1654         if (skb_at_tc_ingress(skb))
1655                 skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1656 }
1657 
1658 static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
1659 {
1660         if (skb_at_tc_ingress(skb))
1661                 skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
1662 }
1663 
1664 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
1665            const void *, from, u32, len, u64, flags)
1666 {
1667         void *ptr;
1668 
1669         if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1670                 return -EINVAL;
1671         if (unlikely(offset > 0xffff))
1672                 return -EFAULT;
1673         if (unlikely(bpf_try_make_writable(skb, offset + len)))
1674                 return -EFAULT;
1675 
1676         ptr = skb->data + offset;
1677         if (flags & BPF_F_RECOMPUTE_CSUM)
1678                 __skb_postpull_rcsum(skb, ptr, len, offset);
1679 
1680         memcpy(ptr, from, len);
1681 
1682         if (flags & BPF_F_RECOMPUTE_CSUM)
1683                 __skb_postpush_rcsum(skb, ptr, len, offset);
1684         if (flags & BPF_F_INVALIDATE_HASH)
1685                 skb_clear_hash(skb);
1686 
1687         return 0;
1688 }
1689 
1690 static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1691         .func           = bpf_skb_store_bytes,
1692         .gpl_only       = false,
1693         .ret_type       = RET_INTEGER,
1694         .arg1_type      = ARG_PTR_TO_CTX,
1695         .arg2_type      = ARG_ANYTHING,
1696         .arg3_type      = ARG_PTR_TO_MEM,
1697         .arg4_type      = ARG_CONST_SIZE,
1698         .arg5_type      = ARG_ANYTHING,
1699 };
1700 
1701 BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
1702            void *, to, u32, len)
1703 {
1704         void *ptr;
1705 
1706         if (unlikely(offset > 0xffff))
1707                 goto err_clear;
1708 
1709         ptr = skb_header_pointer(skb, offset, len, to);
1710         if (unlikely(!ptr))
1711                 goto err_clear;
1712         if (ptr != to)
1713                 memcpy(to, ptr, len);
1714 
1715         return 0;
1716 err_clear:
1717         memset(to, 0, len);
1718         return -EFAULT;
1719 }
1720 
1721 static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1722         .func           = bpf_skb_load_bytes,
1723         .gpl_only       = false,
1724         .ret_type       = RET_INTEGER,
1725         .arg1_type      = ARG_PTR_TO_CTX,
1726         .arg2_type      = ARG_ANYTHING,
1727         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1728         .arg4_type      = ARG_CONST_SIZE,
1729 };
1730 
1731 BPF_CALL_4(bpf_flow_dissector_load_bytes,
1732            const struct bpf_flow_dissector *, ctx, u32, offset,
1733            void *, to, u32, len)
1734 {
1735         void *ptr;
1736 
1737         if (unlikely(offset > 0xffff))
1738                 goto err_clear;
1739 
1740         if (unlikely(!ctx->skb))
1741                 goto err_clear;
1742 
1743         ptr = skb_header_pointer(ctx->skb, offset, len, to);
1744         if (unlikely(!ptr))
1745                 goto err_clear;
1746         if (ptr != to)
1747                 memcpy(to, ptr, len);
1748 
1749         return 0;
1750 err_clear:
1751         memset(to, 0, len);
1752         return -EFAULT;
1753 }
1754 
1755 static const struct bpf_func_proto bpf_flow_dissector_load_bytes_proto = {
1756         .func           = bpf_flow_dissector_load_bytes,
1757         .gpl_only       = false,
1758         .ret_type       = RET_INTEGER,
1759         .arg1_type      = ARG_PTR_TO_CTX,
1760         .arg2_type      = ARG_ANYTHING,
1761         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1762         .arg4_type      = ARG_CONST_SIZE,
1763 };
1764 
1765 BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
1766            u32, offset, void *, to, u32, len, u32, start_header)
1767 {
1768         u8 *end = skb_tail_pointer(skb);
1769         u8 *net = skb_network_header(skb);
1770         u8 *mac = skb_mac_header(skb);
1771         u8 *ptr;
1772 
1773         if (unlikely(offset > 0xffff || len > (end - mac)))
1774                 goto err_clear;
1775 
1776         switch (start_header) {
1777         case BPF_HDR_START_MAC:
1778                 ptr = mac + offset;
1779                 break;
1780         case BPF_HDR_START_NET:
1781                 ptr = net + offset;
1782                 break;
1783         default:
1784                 goto err_clear;
1785         }
1786 
1787         if (likely(ptr >= mac && ptr + len <= end)) {
1788                 memcpy(to, ptr, len);
1789                 return 0;
1790         }
1791 
1792 err_clear:
1793         memset(to, 0, len);
1794         return -EFAULT;
1795 }
1796 
1797 static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
1798         .func           = bpf_skb_load_bytes_relative,
1799         .gpl_only       = false,
1800         .ret_type       = RET_INTEGER,
1801         .arg1_type      = ARG_PTR_TO_CTX,
1802         .arg2_type      = ARG_ANYTHING,
1803         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
1804         .arg4_type      = ARG_CONST_SIZE,
1805         .arg5_type      = ARG_ANYTHING,
1806 };
1807 
1808 BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
1809 {
1810         /* Idea is the following: should the needed direct read/write
1811          * test fail during runtime, we can pull in more data and redo
1812          * again, since implicitly, we invalidate previous checks here.
1813          *
1814          * Or, since we know how much we need to make read/writeable,
1815          * this can be done once at the program beginning for direct
1816          * access case. By this we overcome limitations of only current
1817          * headroom being accessible.
1818          */
1819         return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
1820 }
1821 
1822 static const struct bpf_func_proto bpf_skb_pull_data_proto = {
1823         .func           = bpf_skb_pull_data,
1824         .gpl_only       = false,
1825         .ret_type       = RET_INTEGER,
1826         .arg1_type      = ARG_PTR_TO_CTX,
1827         .arg2_type      = ARG_ANYTHING,
1828 };
1829 
1830 BPF_CALL_1(bpf_sk_fullsock, struct sock *, sk)
1831 {
1832         return sk_fullsock(sk) ? (unsigned long)sk : (unsigned long)NULL;
1833 }
1834 
1835 static const struct bpf_func_proto bpf_sk_fullsock_proto = {
1836         .func           = bpf_sk_fullsock,
1837         .gpl_only       = false,
1838         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
1839         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
1840 };
1841 
1842 static inline int sk_skb_try_make_writable(struct sk_buff *skb,
1843                                            unsigned int write_len)
1844 {
1845         int err = __bpf_try_make_writable(skb, write_len);
1846 
1847         bpf_compute_data_end_sk_skb(skb);
1848         return err;
1849 }
1850 
1851 BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
1852 {
1853         /* Idea is the following: should the needed direct read/write
1854          * test fail during runtime, we can pull in more data and redo
1855          * again, since implicitly, we invalidate previous checks here.
1856          *
1857          * Or, since we know how much we need to make read/writeable,
1858          * this can be done once at the program beginning for direct
1859          * access case. By this we overcome limitations of only current
1860          * headroom being accessible.
1861          */
1862         return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
1863 }
1864 
1865 static const struct bpf_func_proto sk_skb_pull_data_proto = {
1866         .func           = sk_skb_pull_data,
1867         .gpl_only       = false,
1868         .ret_type       = RET_INTEGER,
1869         .arg1_type      = ARG_PTR_TO_CTX,
1870         .arg2_type      = ARG_ANYTHING,
1871 };
1872 
1873 BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
1874            u64, from, u64, to, u64, flags)
1875 {
1876         __sum16 *ptr;
1877 
1878         if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
1879                 return -EINVAL;
1880         if (unlikely(offset > 0xffff || offset & 1))
1881                 return -EFAULT;
1882         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1883                 return -EFAULT;
1884 
1885         ptr = (__sum16 *)(skb->data + offset);
1886         switch (flags & BPF_F_HDR_FIELD_MASK) {
1887         case 0:
1888                 if (unlikely(from != 0))
1889                         return -EINVAL;
1890 
1891                 csum_replace_by_diff(ptr, to);
1892                 break;
1893         case 2:
1894                 csum_replace2(ptr, from, to);
1895                 break;
1896         case 4:
1897                 csum_replace4(ptr, from, to);
1898                 break;
1899         default:
1900                 return -EINVAL;
1901         }
1902 
1903         return 0;
1904 }
1905 
1906 static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1907         .func           = bpf_l3_csum_replace,
1908         .gpl_only       = false,
1909         .ret_type       = RET_INTEGER,
1910         .arg1_type      = ARG_PTR_TO_CTX,
1911         .arg2_type      = ARG_ANYTHING,
1912         .arg3_type      = ARG_ANYTHING,
1913         .arg4_type      = ARG_ANYTHING,
1914         .arg5_type      = ARG_ANYTHING,
1915 };
1916 
1917 BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
1918            u64, from, u64, to, u64, flags)
1919 {
1920         bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1921         bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1922         bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1923         __sum16 *ptr;
1924 
1925         if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
1926                                BPF_F_PSEUDO_HDR | BPF_F_HDR_FIELD_MASK)))
1927                 return -EINVAL;
1928         if (unlikely(offset > 0xffff || offset & 1))
1929                 return -EFAULT;
1930         if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1931                 return -EFAULT;
1932 
1933         ptr = (__sum16 *)(skb->data + offset);
1934         if (is_mmzero && !do_mforce && !*ptr)
1935                 return 0;
1936 
1937         switch (flags & BPF_F_HDR_FIELD_MASK) {
1938         case 0:
1939                 if (unlikely(from != 0))
1940                         return -EINVAL;
1941 
1942                 inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
1943                 break;
1944         case 2:
1945                 inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
1946                 break;
1947         case 4:
1948                 inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
1949                 break;
1950         default:
1951                 return -EINVAL;
1952         }
1953 
1954         if (is_mmzero && !*ptr)
1955                 *ptr = CSUM_MANGLED_0;
1956         return 0;
1957 }
1958 
1959 static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1960         .func           = bpf_l4_csum_replace,
1961         .gpl_only       = false,
1962         .ret_type       = RET_INTEGER,
1963         .arg1_type      = ARG_PTR_TO_CTX,
1964         .arg2_type      = ARG_ANYTHING,
1965         .arg3_type      = ARG_ANYTHING,
1966         .arg4_type      = ARG_ANYTHING,
1967         .arg5_type      = ARG_ANYTHING,
1968 };
1969 
1970 BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
1971            __be32 *, to, u32, to_size, __wsum, seed)
1972 {
1973         struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1974         u32 diff_size = from_size + to_size;
1975         int i, j = 0;
1976 
1977         /* This is quite flexible, some examples:
1978          *
1979          * from_size == 0, to_size > 0,  seed := csum --> pushing data
1980          * from_size > 0,  to_size == 0, seed := csum --> pulling data
1981          * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
1982          *
1983          * Even for diffing, from_size and to_size don't need to be equal.
1984          */
1985         if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
1986                      diff_size > sizeof(sp->diff)))
1987                 return -EINVAL;
1988 
1989         for (i = 0; i < from_size / sizeof(__be32); i++, j++)
1990                 sp->diff[j] = ~from[i];
1991         for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
1992                 sp->diff[j] = to[i];
1993 
1994         return csum_partial(sp->diff, diff_size, seed);
1995 }
1996 
1997 static const struct bpf_func_proto bpf_csum_diff_proto = {
1998         .func           = bpf_csum_diff,
1999         .gpl_only       = false,
2000         .pkt_access     = true,
2001         .ret_type       = RET_INTEGER,
2002         .arg1_type      = ARG_PTR_TO_MEM_OR_NULL,
2003         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
2004         .arg3_type      = ARG_PTR_TO_MEM_OR_NULL,
2005         .arg4_type      = ARG_CONST_SIZE_OR_ZERO,
2006         .arg5_type      = ARG_ANYTHING,
2007 };
2008 
2009 BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
2010 {
2011         /* The interface is to be used in combination with bpf_csum_diff()
2012          * for direct packet writes. csum rotation for alignment as well
2013          * as emulating csum_sub() can be done from the eBPF program.
2014          */
2015         if (skb->ip_summed == CHECKSUM_COMPLETE)
2016                 return (skb->csum = csum_add(skb->csum, csum));
2017 
2018         return -ENOTSUPP;
2019 }
2020 
2021 static const struct bpf_func_proto bpf_csum_update_proto = {
2022         .func           = bpf_csum_update,
2023         .gpl_only       = false,
2024         .ret_type       = RET_INTEGER,
2025         .arg1_type      = ARG_PTR_TO_CTX,
2026         .arg2_type      = ARG_ANYTHING,
2027 };
2028 
2029 static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
2030 {
2031         return dev_forward_skb(dev, skb);
2032 }
2033 
2034 static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
2035                                       struct sk_buff *skb)
2036 {
2037         int ret = ____dev_forward_skb(dev, skb);
2038 
2039         if (likely(!ret)) {
2040                 skb->dev = dev;
2041                 ret = netif_rx(skb);
2042         }
2043 
2044         return ret;
2045 }
2046 
2047 static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
2048 {
2049         int ret;
2050 
2051         if (dev_xmit_recursion()) {
2052                 net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
2053                 kfree_skb(skb);
2054                 return -ENETDOWN;
2055         }
2056 
2057         skb->dev = dev;
2058         skb->tstamp = 0;
2059 
2060         dev_xmit_recursion_inc();
2061         ret = dev_queue_xmit(skb);
2062         dev_xmit_recursion_dec();
2063 
2064         return ret;
2065 }
2066 
2067 static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
2068                                  u32 flags)
2069 {
2070         unsigned int mlen = skb_network_offset(skb);
2071 
2072         if (mlen) {
2073                 __skb_pull(skb, mlen);
2074 
2075                 /* At ingress, the mac header has already been pulled once.
2076                  * At egress, skb_pospull_rcsum has to be done in case that
2077                  * the skb is originated from ingress (i.e. a forwarded skb)
2078                  * to ensure that rcsum starts at net header.
2079                  */
2080                 if (!skb_at_tc_ingress(skb))
2081                         skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
2082         }
2083         skb_pop_mac_header(skb);
2084         skb_reset_mac_len(skb);
2085         return flags & BPF_F_INGRESS ?
2086                __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
2087 }
2088 
2089 static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
2090                                  u32 flags)
2091 {
2092         /* Verify that a link layer header is carried */
2093         if (unlikely(skb->mac_header >= skb->network_header)) {
2094                 kfree_skb(skb);
2095                 return -ERANGE;
2096         }
2097 
2098         bpf_push_mac_rcsum(skb);
2099         return flags & BPF_F_INGRESS ?
2100                __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
2101 }
2102 
2103 static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
2104                           u32 flags)
2105 {
2106         if (dev_is_mac_header_xmit(dev))
2107                 return __bpf_redirect_common(skb, dev, flags);
2108         else
2109                 return __bpf_redirect_no_mac(skb, dev, flags);
2110 }
2111 
2112 BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2113 {
2114         struct net_device *dev;
2115         struct sk_buff *clone;
2116         int ret;
2117 
2118         if (unlikely(flags & ~(BPF_F_INGRESS)))
2119                 return -EINVAL;
2120 
2121         dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
2122         if (unlikely(!dev))
2123                 return -EINVAL;
2124 
2125         clone = skb_clone(skb, GFP_ATOMIC);
2126         if (unlikely(!clone))
2127                 return -ENOMEM;
2128 
2129         /* For direct write, we need to keep the invariant that the skbs
2130          * we're dealing with need to be uncloned. Should uncloning fail
2131          * here, we need to free the just generated clone to unclone once
2132          * again.
2133          */
2134         ret = bpf_try_make_head_writable(skb);
2135         if (unlikely(ret)) {
2136                 kfree_skb(clone);
2137                 return -ENOMEM;
2138         }
2139 
2140         return __bpf_redirect(clone, dev, flags);
2141 }
2142 
2143 static const struct bpf_func_proto bpf_clone_redirect_proto = {
2144         .func           = bpf_clone_redirect,
2145         .gpl_only       = false,
2146         .ret_type       = RET_INTEGER,
2147         .arg1_type      = ARG_PTR_TO_CTX,
2148         .arg2_type      = ARG_ANYTHING,
2149         .arg3_type      = ARG_ANYTHING,
2150 };
2151 
2152 DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
2153 EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2154 
2155 BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2156 {
2157         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2158 
2159         if (unlikely(flags & ~(BPF_F_INGRESS)))
2160                 return TC_ACT_SHOT;
2161 
2162         ri->flags = flags;
2163         ri->tgt_index = ifindex;
2164 
2165         return TC_ACT_REDIRECT;
2166 }
2167 
2168 int skb_do_redirect(struct sk_buff *skb)
2169 {
2170         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2171         struct net_device *dev;
2172 
2173         dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->tgt_index);
2174         ri->tgt_index = 0;
2175         if (unlikely(!dev)) {
2176                 kfree_skb(skb);
2177                 return -EINVAL;
2178         }
2179 
2180         return __bpf_redirect(skb, dev, ri->flags);
2181 }
2182 
2183 static const struct bpf_func_proto bpf_redirect_proto = {
2184         .func           = bpf_redirect,
2185         .gpl_only       = false,
2186         .ret_type       = RET_INTEGER,
2187         .arg1_type      = ARG_ANYTHING,
2188         .arg2_type      = ARG_ANYTHING,
2189 };
2190 
2191 BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg *, msg, u32, bytes)
2192 {
2193         msg->apply_bytes = bytes;
2194         return 0;
2195 }
2196 
2197 static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
2198         .func           = bpf_msg_apply_bytes,
2199         .gpl_only       = false,
2200         .ret_type       = RET_INTEGER,
2201         .arg1_type      = ARG_PTR_TO_CTX,
2202         .arg2_type      = ARG_ANYTHING,
2203 };
2204 
2205 BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg *, msg, u32, bytes)
2206 {
2207         msg->cork_bytes = bytes;
2208         return 0;
2209 }
2210 
2211 static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
2212         .func           = bpf_msg_cork_bytes,
2213         .gpl_only       = false,
2214         .ret_type       = RET_INTEGER,
2215         .arg1_type      = ARG_PTR_TO_CTX,
2216         .arg2_type      = ARG_ANYTHING,
2217 };
2218 
2219 BPF_CALL_4(bpf_msg_pull_data, struct sk_msg *, msg, u32, start,
2220            u32, end, u64, flags)
2221 {
2222         u32 len = 0, offset = 0, copy = 0, poffset = 0, bytes = end - start;
2223         u32 first_sge, last_sge, i, shift, bytes_sg_total;
2224         struct scatterlist *sge;
2225         u8 *raw, *to, *from;
2226         struct page *page;
2227 
2228         if (unlikely(flags || end <= start))
2229                 return -EINVAL;
2230 
2231         /* First find the starting scatterlist element */
2232         i = msg->sg.start;
2233         do {
2234                 offset += len;
2235                 len = sk_msg_elem(msg, i)->length;
2236                 if (start < offset + len)
2237                         break;
2238                 sk_msg_iter_var_next(i);
2239         } while (i != msg->sg.end);
2240 
2241         if (unlikely(start >= offset + len))
2242                 return -EINVAL;
2243 
2244         first_sge = i;
2245         /* The start may point into the sg element so we need to also
2246          * account for the headroom.
2247          */
2248         bytes_sg_total = start - offset + bytes;
2249         if (!msg->sg.copy[i] && bytes_sg_total <= len)
2250                 goto out;
2251 
2252         /* At this point we need to linearize multiple scatterlist
2253          * elements or a single shared page. Either way we need to
2254          * copy into a linear buffer exclusively owned by BPF. Then
2255          * place the buffer in the scatterlist and fixup the original
2256          * entries by removing the entries now in the linear buffer
2257          * and shifting the remaining entries. For now we do not try
2258          * to copy partial entries to avoid complexity of running out
2259          * of sg_entry slots. The downside is reading a single byte
2260          * will copy the entire sg entry.
2261          */
2262         do {
2263                 copy += sk_msg_elem(msg, i)->length;
2264                 sk_msg_iter_var_next(i);
2265                 if (bytes_sg_total <= copy)
2266                         break;
2267         } while (i != msg->sg.end);
2268         last_sge = i;
2269 
2270         if (unlikely(bytes_sg_total > copy))
2271                 return -EINVAL;
2272 
2273         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2274                            get_order(copy));
2275         if (unlikely(!page))
2276                 return -ENOMEM;
2277 
2278         raw = page_address(page);
2279         i = first_sge;
2280         do {
2281                 sge = sk_msg_elem(msg, i);
2282                 from = sg_virt(sge);
2283                 len = sge->length;
2284                 to = raw + poffset;
2285 
2286                 memcpy(to, from, len);
2287                 poffset += len;
2288                 sge->length = 0;
2289                 put_page(sg_page(sge));
2290 
2291                 sk_msg_iter_var_next(i);
2292         } while (i != last_sge);
2293 
2294         sg_set_page(&msg->sg.data[first_sge], page, copy, 0);
2295 
2296         /* To repair sg ring we need to shift entries. If we only
2297          * had a single entry though we can just replace it and
2298          * be done. Otherwise walk the ring and shift the entries.
2299          */
2300         WARN_ON_ONCE(last_sge == first_sge);
2301         shift = last_sge > first_sge ?
2302                 last_sge - first_sge - 1 :
2303                 NR_MSG_FRAG_IDS - first_sge + last_sge - 1;
2304         if (!shift)
2305                 goto out;
2306 
2307         i = first_sge;
2308         sk_msg_iter_var_next(i);
2309         do {
2310                 u32 move_from;
2311 
2312                 if (i + shift >= NR_MSG_FRAG_IDS)
2313                         move_from = i + shift - NR_MSG_FRAG_IDS;
2314                 else
2315                         move_from = i + shift;
2316                 if (move_from == msg->sg.end)
2317                         break;
2318 
2319                 msg->sg.data[i] = msg->sg.data[move_from];
2320                 msg->sg.data[move_from].length = 0;
2321                 msg->sg.data[move_from].page_link = 0;
2322                 msg->sg.data[move_from].offset = 0;
2323                 sk_msg_iter_var_next(i);
2324         } while (1);
2325 
2326         msg->sg.end = msg->sg.end - shift > msg->sg.end ?
2327                       msg->sg.end - shift + NR_MSG_FRAG_IDS :
2328                       msg->sg.end - shift;
2329 out:
2330         msg->data = sg_virt(&msg->sg.data[first_sge]) + start - offset;
2331         msg->data_end = msg->data + bytes;
2332         return 0;
2333 }
2334 
2335 static const struct bpf_func_proto bpf_msg_pull_data_proto = {
2336         .func           = bpf_msg_pull_data,
2337         .gpl_only       = false,
2338         .ret_type       = RET_INTEGER,
2339         .arg1_type      = ARG_PTR_TO_CTX,
2340         .arg2_type      = ARG_ANYTHING,
2341         .arg3_type      = ARG_ANYTHING,
2342         .arg4_type      = ARG_ANYTHING,
2343 };
2344 
2345 BPF_CALL_4(bpf_msg_push_data, struct sk_msg *, msg, u32, start,
2346            u32, len, u64, flags)
2347 {
2348         struct scatterlist sge, nsge, nnsge, rsge = {0}, *psge;
2349         u32 new, i = 0, l = 0, space, copy = 0, offset = 0;
2350         u8 *raw, *to, *from;
2351         struct page *page;
2352 
2353         if (unlikely(flags))
2354                 return -EINVAL;
2355 
2356         /* First find the starting scatterlist element */
2357         i = msg->sg.start;
2358         do {
2359                 offset += l;
2360                 l = sk_msg_elem(msg, i)->length;
2361 
2362                 if (start < offset + l)
2363                         break;
2364                 sk_msg_iter_var_next(i);
2365         } while (i != msg->sg.end);
2366 
2367         if (start >= offset + l)
2368                 return -EINVAL;
2369 
2370         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2371 
2372         /* If no space available will fallback to copy, we need at
2373          * least one scatterlist elem available to push data into
2374          * when start aligns to the beginning of an element or two
2375          * when it falls inside an element. We handle the start equals
2376          * offset case because its the common case for inserting a
2377          * header.
2378          */
2379         if (!space || (space == 1 && start != offset))
2380                 copy = msg->sg.data[i].length;
2381 
2382         page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC | __GFP_COMP,
2383                            get_order(copy + len));
2384         if (unlikely(!page))
2385                 return -ENOMEM;
2386 
2387         if (copy) {
2388                 int front, back;
2389 
2390                 raw = page_address(page);
2391 
2392                 psge = sk_msg_elem(msg, i);
2393                 front = start - offset;
2394                 back = psge->length - front;
2395                 from = sg_virt(psge);
2396 
2397                 if (front)
2398                         memcpy(raw, from, front);
2399 
2400                 if (back) {
2401                         from += front;
2402                         to = raw + front + len;
2403 
2404                         memcpy(to, from, back);
2405                 }
2406 
2407                 put_page(sg_page(psge));
2408         } else if (start - offset) {
2409                 psge = sk_msg_elem(msg, i);
2410                 rsge = sk_msg_elem_cpy(msg, i);
2411 
2412                 psge->length = start - offset;
2413                 rsge.length -= psge->length;
2414                 rsge.offset += start;
2415 
2416                 sk_msg_iter_var_next(i);
2417                 sg_unmark_end(psge);
2418                 sg_unmark_end(&rsge);
2419                 sk_msg_iter_next(msg, end);
2420         }
2421 
2422         /* Slot(s) to place newly allocated data */
2423         new = i;
2424 
2425         /* Shift one or two slots as needed */
2426         if (!copy) {
2427                 sge = sk_msg_elem_cpy(msg, i);
2428 
2429                 sk_msg_iter_var_next(i);
2430                 sg_unmark_end(&sge);
2431                 sk_msg_iter_next(msg, end);
2432 
2433                 nsge = sk_msg_elem_cpy(msg, i);
2434                 if (rsge.length) {
2435                         sk_msg_iter_var_next(i);
2436                         nnsge = sk_msg_elem_cpy(msg, i);
2437                 }
2438 
2439                 while (i != msg->sg.end) {
2440                         msg->sg.data[i] = sge;
2441                         sge = nsge;
2442                         sk_msg_iter_var_next(i);
2443                         if (rsge.length) {
2444                                 nsge = nnsge;
2445                                 nnsge = sk_msg_elem_cpy(msg, i);
2446                         } else {
2447                                 nsge = sk_msg_elem_cpy(msg, i);
2448                         }
2449                 }
2450         }
2451 
2452         /* Place newly allocated data buffer */
2453         sk_mem_charge(msg->sk, len);
2454         msg->sg.size += len;
2455         msg->sg.copy[new] = false;
2456         sg_set_page(&msg->sg.data[new], page, len + copy, 0);
2457         if (rsge.length) {
2458                 get_page(sg_page(&rsge));
2459                 sk_msg_iter_var_next(new);
2460                 msg->sg.data[new] = rsge;
2461         }
2462 
2463         sk_msg_compute_data_pointers(msg);
2464         return 0;
2465 }
2466 
2467 static const struct bpf_func_proto bpf_msg_push_data_proto = {
2468         .func           = bpf_msg_push_data,
2469         .gpl_only       = false,
2470         .ret_type       = RET_INTEGER,
2471         .arg1_type      = ARG_PTR_TO_CTX,
2472         .arg2_type      = ARG_ANYTHING,
2473         .arg3_type      = ARG_ANYTHING,
2474         .arg4_type      = ARG_ANYTHING,
2475 };
2476 
2477 static void sk_msg_shift_left(struct sk_msg *msg, int i)
2478 {
2479         int prev;
2480 
2481         do {
2482                 prev = i;
2483                 sk_msg_iter_var_next(i);
2484                 msg->sg.data[prev] = msg->sg.data[i];
2485         } while (i != msg->sg.end);
2486 
2487         sk_msg_iter_prev(msg, end);
2488 }
2489 
2490 static void sk_msg_shift_right(struct sk_msg *msg, int i)
2491 {
2492         struct scatterlist tmp, sge;
2493 
2494         sk_msg_iter_next(msg, end);
2495         sge = sk_msg_elem_cpy(msg, i);
2496         sk_msg_iter_var_next(i);
2497         tmp = sk_msg_elem_cpy(msg, i);
2498 
2499         while (i != msg->sg.end) {
2500                 msg->sg.data[i] = sge;
2501                 sk_msg_iter_var_next(i);
2502                 sge = tmp;
2503                 tmp = sk_msg_elem_cpy(msg, i);
2504         }
2505 }
2506 
2507 BPF_CALL_4(bpf_msg_pop_data, struct sk_msg *, msg, u32, start,
2508            u32, len, u64, flags)
2509 {
2510         u32 i = 0, l = 0, space, offset = 0;
2511         u64 last = start + len;
2512         int pop;
2513 
2514         if (unlikely(flags))
2515                 return -EINVAL;
2516 
2517         /* First find the starting scatterlist element */
2518         i = msg->sg.start;
2519         do {
2520                 offset += l;
2521                 l = sk_msg_elem(msg, i)->length;
2522 
2523                 if (start < offset + l)
2524                         break;
2525                 sk_msg_iter_var_next(i);
2526         } while (i != msg->sg.end);
2527 
2528         /* Bounds checks: start and pop must be inside message */
2529         if (start >= offset + l || last >= msg->sg.size)
2530                 return -EINVAL;
2531 
2532         space = MAX_MSG_FRAGS - sk_msg_elem_used(msg);
2533 
2534         pop = len;
2535         /* --------------| offset
2536          * -| start      |-------- len -------|
2537          *
2538          *  |----- a ----|-------- pop -------|----- b ----|
2539          *  |______________________________________________| length
2540          *
2541          *
2542          * a:   region at front of scatter element to save
2543          * b:   region at back of scatter element to save when length > A + pop
2544          * pop: region to pop from element, same as input 'pop' here will be
2545          *      decremented below per iteration.
2546          *
2547          * Two top-level cases to handle when start != offset, first B is non
2548          * zero and second B is zero corresponding to when a pop includes more
2549          * than one element.
2550          *
2551          * Then if B is non-zero AND there is no space allocate space and
2552          * compact A, B regions into page. If there is space shift ring to
2553          * the rigth free'ing the next element in ring to place B, leaving
2554          * A untouched except to reduce length.
2555          */
2556         if (start != offset) {
2557                 struct scatterlist *nsge, *sge = sk_msg_elem(msg, i);
2558                 int a = start;
2559                 int b = sge->length - pop - a;
2560 
2561                 sk_msg_iter_var_next(i);
2562 
2563                 if (pop < sge->length - a) {
2564                         if (space) {
2565                                 sge->length = a;
2566                                 sk_msg_shift_right(msg, i);
2567                                 nsge = sk_msg_elem(msg, i);
2568                                 get_page(sg_page(sge));
2569                                 sg_set_page(nsge,
2570                                             sg_page(sge),
2571                                             b, sge->offset + pop + a);
2572                         } else {
2573                                 struct page *page, *orig;
2574                                 u8 *to, *from;
2575 
2576                                 page = alloc_pages(__GFP_NOWARN |
2577                                                    __GFP_COMP   | GFP_ATOMIC,
2578                                                    get_order(a + b));
2579                                 if (unlikely(!page))
2580                                         return -ENOMEM;
2581 
2582                                 sge->length = a;
2583                                 orig = sg_page(sge);
2584                                 from = sg_virt(sge);
2585                                 to = page_address(page);
2586                                 memcpy(to, from, a);
2587                                 memcpy(to + a, from + a + pop, b);
2588                                 sg_set_page(sge, page, a + b, 0);
2589                                 put_page(orig);
2590                         }
2591                         pop = 0;
2592                 } else if (pop >= sge->length - a) {
2593                         pop -= (sge->length - a);
2594                         sge->length = a;
2595                 }
2596         }
2597 
2598         /* From above the current layout _must_ be as follows,
2599          *
2600          * -| offset
2601          * -| start
2602          *
2603          *  |---- pop ---|---------------- b ------------|
2604          *  |____________________________________________| length
2605          *
2606          * Offset and start of the current msg elem are equal because in the
2607          * previous case we handled offset != start and either consumed the
2608          * entire element and advanced to the next element OR pop == 0.
2609          *
2610          * Two cases to handle here are first pop is less than the length
2611          * leaving some remainder b above. Simply adjust the element's layout
2612          * in this case. Or pop >= length of the element so that b = 0. In this
2613          * case advance to next element decrementing pop.
2614          */
2615         while (pop) {
2616                 struct scatterlist *sge = sk_msg_elem(msg, i);
2617 
2618                 if (pop < sge->length) {
2619                         sge->length -= pop;
2620                         sge->offset += pop;
2621                         pop = 0;
2622                 } else {
2623                         pop -= sge->length;
2624                         sk_msg_shift_left(msg, i);
2625                 }
2626                 sk_msg_iter_var_next(i);
2627         }
2628 
2629         sk_mem_uncharge(msg->sk, len - pop);
2630         msg->sg.size -= (len - pop);
2631         sk_msg_compute_data_pointers(msg);
2632         return 0;
2633 }
2634 
2635 static const struct bpf_func_proto bpf_msg_pop_data_proto = {
2636         .func           = bpf_msg_pop_data,
2637         .gpl_only       = false,
2638         .ret_type       = RET_INTEGER,
2639         .arg1_type      = ARG_PTR_TO_CTX,
2640         .arg2_type      = ARG_ANYTHING,
2641         .arg3_type      = ARG_ANYTHING,
2642         .arg4_type      = ARG_ANYTHING,
2643 };
2644 
2645 BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2646 {
2647         return task_get_classid(skb);
2648 }
2649 
2650 static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
2651         .func           = bpf_get_cgroup_classid,
2652         .gpl_only       = false,
2653         .ret_type       = RET_INTEGER,
2654         .arg1_type      = ARG_PTR_TO_CTX,
2655 };
2656 
2657 BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2658 {
2659         return dst_tclassid(skb);
2660 }
2661 
2662 static const struct bpf_func_proto bpf_get_route_realm_proto = {
2663         .func           = bpf_get_route_realm,
2664         .gpl_only       = false,
2665         .ret_type       = RET_INTEGER,
2666         .arg1_type      = ARG_PTR_TO_CTX,
2667 };
2668 
2669 BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2670 {
2671         /* If skb_clear_hash() was called due to mangling, we can
2672          * trigger SW recalculation here. Later access to hash
2673          * can then use the inline skb->hash via context directly
2674          * instead of calling this helper again.
2675          */
2676         return skb_get_hash(skb);
2677 }
2678 
2679 static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
2680         .func           = bpf_get_hash_recalc,
2681         .gpl_only       = false,
2682         .ret_type       = RET_INTEGER,
2683         .arg1_type      = ARG_PTR_TO_CTX,
2684 };
2685 
2686 BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
2687 {
2688         /* After all direct packet write, this can be used once for
2689          * triggering a lazy recalc on next skb_get_hash() invocation.
2690          */
2691         skb_clear_hash(skb);
2692         return 0;
2693 }
2694 
2695 static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
2696         .func           = bpf_set_hash_invalid,
2697         .gpl_only       = false,
2698         .ret_type       = RET_INTEGER,
2699         .arg1_type      = ARG_PTR_TO_CTX,
2700 };
2701 
2702 BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
2703 {
2704         /* Set user specified hash as L4(+), so that it gets returned
2705          * on skb_get_hash() call unless BPF prog later on triggers a
2706          * skb_clear_hash().
2707          */
2708         __skb_set_sw_hash(skb, hash, true);
2709         return 0;
2710 }
2711 
2712 static const struct bpf_func_proto bpf_set_hash_proto = {
2713         .func           = bpf_set_hash,
2714         .gpl_only       = false,
2715         .ret_type       = RET_INTEGER,
2716         .arg1_type      = ARG_PTR_TO_CTX,
2717         .arg2_type      = ARG_ANYTHING,
2718 };
2719 
2720 BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
2721            u16, vlan_tci)
2722 {
2723         int ret;
2724 
2725         if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
2726                      vlan_proto != htons(ETH_P_8021AD)))
2727                 vlan_proto = htons(ETH_P_8021Q);
2728 
2729         bpf_push_mac_rcsum(skb);
2730         ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2731         bpf_pull_mac_rcsum(skb);
2732 
2733         bpf_compute_data_pointers(skb);
2734         return ret;
2735 }
2736 
2737 static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2738         .func           = bpf_skb_vlan_push,
2739         .gpl_only       = false,
2740         .ret_type       = RET_INTEGER,
2741         .arg1_type      = ARG_PTR_TO_CTX,
2742         .arg2_type      = ARG_ANYTHING,
2743         .arg3_type      = ARG_ANYTHING,
2744 };
2745 
2746 BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2747 {
2748         int ret;
2749 
2750         bpf_push_mac_rcsum(skb);
2751         ret = skb_vlan_pop(skb);
2752         bpf_pull_mac_rcsum(skb);
2753 
2754         bpf_compute_data_pointers(skb);
2755         return ret;
2756 }
2757 
2758 static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2759         .func           = bpf_skb_vlan_pop,
2760         .gpl_only       = false,
2761         .ret_type       = RET_INTEGER,
2762         .arg1_type      = ARG_PTR_TO_CTX,
2763 };
2764 
2765 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
2766 {
2767         /* Caller already did skb_cow() with len as headroom,
2768          * so no need to do it here.
2769          */
2770         skb_push(skb, len);
2771         memmove(skb->data, skb->data + len, off);
2772         memset(skb->data + off, 0, len);
2773 
2774         /* No skb_postpush_rcsum(skb, skb->data + off, len)
2775          * needed here as it does not change the skb->csum
2776          * result for checksum complete when summing over
2777          * zeroed blocks.
2778          */
2779         return 0;
2780 }
2781 
2782 static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
2783 {
2784         /* skb_ensure_writable() is not needed here, as we're
2785          * already working on an uncloned skb.
2786          */
2787         if (unlikely(!pskb_may_pull(skb, off + len)))
2788                 return -ENOMEM;
2789 
2790         skb_postpull_rcsum(skb, skb->data + off, len);
2791         memmove(skb->data + len, skb->data, off);
2792         __skb_pull(skb, len);
2793 
2794         return 0;
2795 }
2796 
2797 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
2798 {
2799         bool trans_same = skb->transport_header == skb->network_header;
2800         int ret;
2801 
2802         /* There's no need for __skb_push()/__skb_pull() pair to
2803          * get to the start of the mac header as we're guaranteed
2804          * to always start from here under eBPF.
2805          */
2806         ret = bpf_skb_generic_push(skb, off, len);
2807         if (likely(!ret)) {
2808                 skb->mac_header -= len;
2809                 skb->network_header -= len;
2810                 if (trans_same)
2811                         skb->transport_header = skb->network_header;
2812         }
2813 
2814         return ret;
2815 }
2816 
2817 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
2818 {
2819         bool trans_same = skb->transport_header == skb->network_header;
2820         int ret;
2821 
2822         /* Same here, __skb_push()/__skb_pull() pair not needed. */
2823         ret = bpf_skb_generic_pop(skb, off, len);
2824         if (likely(!ret)) {
2825                 skb->mac_header += len;
2826                 skb->network_header += len;
2827                 if (trans_same)
2828                         skb->transport_header = skb->network_header;
2829         }
2830 
2831         return ret;
2832 }
2833 
2834 static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
2835 {
2836         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2837         u32 off = skb_mac_header_len(skb);
2838         int ret;
2839 
2840         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2841                 return -ENOTSUPP;
2842 
2843         ret = skb_cow(skb, len_diff);
2844         if (unlikely(ret < 0))
2845                 return ret;
2846 
2847         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
2848         if (unlikely(ret < 0))
2849                 return ret;
2850 
2851         if (skb_is_gso(skb)) {
2852                 struct skb_shared_info *shinfo = skb_shinfo(skb);
2853 
2854                 /* SKB_GSO_TCPV4 needs to be changed into
2855                  * SKB_GSO_TCPV6.
2856                  */
2857                 if (shinfo->gso_type & SKB_GSO_TCPV4) {
2858                         shinfo->gso_type &= ~SKB_GSO_TCPV4;
2859                         shinfo->gso_type |=  SKB_GSO_TCPV6;
2860                 }
2861 
2862                 /* Due to IPv6 header, MSS needs to be downgraded. */
2863                 skb_decrease_gso_size(shinfo, len_diff);
2864                 /* Header must be checked, and gso_segs recomputed. */
2865                 shinfo->gso_type |= SKB_GSO_DODGY;
2866                 shinfo->gso_segs = 0;
2867         }
2868 
2869         skb->protocol = htons(ETH_P_IPV6);
2870         skb_clear_hash(skb);
2871 
2872         return 0;
2873 }
2874 
2875 static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
2876 {
2877         const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2878         u32 off = skb_mac_header_len(skb);
2879         int ret;
2880 
2881         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb))
2882                 return -ENOTSUPP;
2883 
2884         ret = skb_unclone(skb, GFP_ATOMIC);
2885         if (unlikely(ret < 0))
2886                 return ret;
2887 
2888         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
2889         if (unlikely(ret < 0))
2890                 return ret;
2891 
2892         if (skb_is_gso(skb)) {
2893                 struct skb_shared_info *shinfo = skb_shinfo(skb);
2894 
2895                 /* SKB_GSO_TCPV6 needs to be changed into
2896                  * SKB_GSO_TCPV4.
2897                  */
2898                 if (shinfo->gso_type & SKB_GSO_TCPV6) {
2899                         shinfo->gso_type &= ~SKB_GSO_TCPV6;
2900                         shinfo->gso_type |=  SKB_GSO_TCPV4;
2901                 }
2902 
2903                 /* Due to IPv4 header, MSS can be upgraded. */
2904                 skb_increase_gso_size(shinfo, len_diff);
2905                 /* Header must be checked, and gso_segs recomputed. */
2906                 shinfo->gso_type |= SKB_GSO_DODGY;
2907                 shinfo->gso_segs = 0;
2908         }
2909 
2910         skb->protocol = htons(ETH_P_IP);
2911         skb_clear_hash(skb);
2912 
2913         return 0;
2914 }
2915 
2916 static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
2917 {
2918         __be16 from_proto = skb->protocol;
2919 
2920         if (from_proto == htons(ETH_P_IP) &&
2921               to_proto == htons(ETH_P_IPV6))
2922                 return bpf_skb_proto_4_to_6(skb);
2923 
2924         if (from_proto == htons(ETH_P_IPV6) &&
2925               to_proto == htons(ETH_P_IP))
2926                 return bpf_skb_proto_6_to_4(skb);
2927 
2928         return -ENOTSUPP;
2929 }
2930 
2931 BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
2932            u64, flags)
2933 {
2934         int ret;
2935 
2936         if (unlikely(flags))
2937                 return -EINVAL;
2938 
2939         /* General idea is that this helper does the basic groundwork
2940          * needed for changing the protocol, and eBPF program fills the
2941          * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
2942          * and other helpers, rather than passing a raw buffer here.
2943          *
2944          * The rationale is to keep this minimal and without a need to
2945          * deal with raw packet data. F.e. even if we would pass buffers
2946          * here, the program still needs to call the bpf_lX_csum_replace()
2947          * helpers anyway. Plus, this way we keep also separation of
2948          * concerns, since f.e. bpf_skb_store_bytes() should only take
2949          * care of stores.
2950          *
2951          * Currently, additional options and extension header space are
2952          * not supported, but flags register is reserved so we can adapt
2953          * that. For offloads, we mark packet as dodgy, so that headers
2954          * need to be verified first.
2955          */
2956         ret = bpf_skb_proto_xlat(skb, proto);
2957         bpf_compute_data_pointers(skb);
2958         return ret;
2959 }
2960 
2961 static const struct bpf_func_proto bpf_skb_change_proto_proto = {
2962         .func           = bpf_skb_change_proto,
2963         .gpl_only       = false,
2964         .ret_type       = RET_INTEGER,
2965         .arg1_type      = ARG_PTR_TO_CTX,
2966         .arg2_type      = ARG_ANYTHING,
2967         .arg3_type      = ARG_ANYTHING,
2968 };
2969 
2970 BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2971 {
2972         /* We only allow a restricted subset to be changed for now. */
2973         if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
2974                      !skb_pkt_type_ok(pkt_type)))
2975                 return -EINVAL;
2976 
2977         skb->pkt_type = pkt_type;
2978         return 0;
2979 }
2980 
2981 static const struct bpf_func_proto bpf_skb_change_type_proto = {
2982         .func           = bpf_skb_change_type,
2983         .gpl_only       = false,
2984         .ret_type       = RET_INTEGER,
2985         .arg1_type      = ARG_PTR_TO_CTX,
2986         .arg2_type      = ARG_ANYTHING,
2987 };
2988 
2989 static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
2990 {
2991         switch (skb->protocol) {
2992         case htons(ETH_P_IP):
2993                 return sizeof(struct iphdr);
2994         case htons(ETH_P_IPV6):
2995                 return sizeof(struct ipv6hdr);
2996         default:
2997                 return ~0U;
2998         }
2999 }
3000 
3001 #define BPF_F_ADJ_ROOM_ENCAP_L3_MASK    (BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 | \
3002                                          BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3003 
3004 #define BPF_F_ADJ_ROOM_MASK             (BPF_F_ADJ_ROOM_FIXED_GSO | \
3005                                          BPF_F_ADJ_ROOM_ENCAP_L3_MASK | \
3006                                          BPF_F_ADJ_ROOM_ENCAP_L4_GRE | \
3007                                          BPF_F_ADJ_ROOM_ENCAP_L4_UDP | \
3008                                          BPF_F_ADJ_ROOM_ENCAP_L2( \
3009                                           BPF_ADJ_ROOM_ENCAP_L2_MASK))
3010 
3011 static int bpf_skb_net_grow(struct sk_buff *skb, u32 off, u32 len_diff,
3012                             u64 flags)
3013 {
3014         u8 inner_mac_len = flags >> BPF_ADJ_ROOM_ENCAP_L2_SHIFT;
3015         bool encap = flags & BPF_F_ADJ_ROOM_ENCAP_L3_MASK;
3016         u16 mac_len = 0, inner_net = 0, inner_trans = 0;
3017         unsigned int gso_type = SKB_GSO_DODGY;
3018         int ret;
3019 
3020         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3021                 /* udp gso_size delineates datagrams, only allow if fixed */
3022                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3023                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3024                         return -ENOTSUPP;
3025         }
3026 
3027         ret = skb_cow_head(skb, len_diff);
3028         if (unlikely(ret < 0))
3029                 return ret;
3030 
3031         if (encap) {
3032                 if (skb->protocol != htons(ETH_P_IP) &&
3033                     skb->protocol != htons(ETH_P_IPV6))
3034                         return -ENOTSUPP;
3035 
3036                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 &&
3037                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3038                         return -EINVAL;
3039 
3040                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE &&
3041                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3042                         return -EINVAL;
3043 
3044                 if (skb->encapsulation)
3045                         return -EALREADY;
3046 
3047                 mac_len = skb->network_header - skb->mac_header;
3048                 inner_net = skb->network_header;
3049                 if (inner_mac_len > len_diff)
3050                         return -EINVAL;
3051                 inner_trans = skb->transport_header;
3052         }
3053 
3054         ret = bpf_skb_net_hdr_push(skb, off, len_diff);
3055         if (unlikely(ret < 0))
3056                 return ret;
3057 
3058         if (encap) {
3059                 skb->inner_mac_header = inner_net - inner_mac_len;
3060                 skb->inner_network_header = inner_net;
3061                 skb->inner_transport_header = inner_trans;
3062                 skb_set_inner_protocol(skb, skb->protocol);
3063 
3064                 skb->encapsulation = 1;
3065                 skb_set_network_header(skb, mac_len);
3066 
3067                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP)
3068                         gso_type |= SKB_GSO_UDP_TUNNEL;
3069                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE)
3070                         gso_type |= SKB_GSO_GRE;
3071                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3072                         gso_type |= SKB_GSO_IPXIP6;
3073                 else if (flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3074                         gso_type |= SKB_GSO_IPXIP4;
3075 
3076                 if (flags & BPF_F_ADJ_ROOM_ENCAP_L4_GRE ||
3077                     flags & BPF_F_ADJ_ROOM_ENCAP_L4_UDP) {
3078                         int nh_len = flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 ?
3079                                         sizeof(struct ipv6hdr) :
3080                                         sizeof(struct iphdr);
3081 
3082                         skb_set_transport_header(skb, mac_len + nh_len);
3083                 }
3084 
3085                 /* Match skb->protocol to new outer l3 protocol */
3086                 if (skb->protocol == htons(ETH_P_IP) &&
3087                     flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV6)
3088                         skb->protocol = htons(ETH_P_IPV6);
3089                 else if (skb->protocol == htons(ETH_P_IPV6) &&
3090                          flags & BPF_F_ADJ_ROOM_ENCAP_L3_IPV4)
3091                         skb->protocol = htons(ETH_P_IP);
3092         }
3093 
3094         if (skb_is_gso(skb)) {
3095                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3096 
3097                 /* Due to header grow, MSS needs to be downgraded. */
3098                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3099                         skb_decrease_gso_size(shinfo, len_diff);
3100 
3101                 /* Header must be checked, and gso_segs recomputed. */
3102                 shinfo->gso_type |= gso_type;
3103                 shinfo->gso_segs = 0;
3104         }
3105 
3106         return 0;
3107 }
3108 
3109 static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
3110                               u64 flags)
3111 {
3112         int ret;
3113 
3114         if (flags & ~BPF_F_ADJ_ROOM_FIXED_GSO)
3115                 return -EINVAL;
3116 
3117         if (skb_is_gso(skb) && !skb_is_gso_tcp(skb)) {
3118                 /* udp gso_size delineates datagrams, only allow if fixed */
3119                 if (!(skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4) ||
3120                     !(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3121                         return -ENOTSUPP;
3122         }
3123 
3124         ret = skb_unclone(skb, GFP_ATOMIC);
3125         if (unlikely(ret < 0))
3126                 return ret;
3127 
3128         ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
3129         if (unlikely(ret < 0))
3130                 return ret;
3131 
3132         if (skb_is_gso(skb)) {
3133                 struct skb_shared_info *shinfo = skb_shinfo(skb);
3134 
3135                 /* Due to header shrink, MSS can be upgraded. */
3136                 if (!(flags & BPF_F_ADJ_ROOM_FIXED_GSO))
3137                         skb_increase_gso_size(shinfo, len_diff);
3138 
3139                 /* Header must be checked, and gso_segs recomputed. */
3140                 shinfo->gso_type |= SKB_GSO_DODGY;
3141                 shinfo->gso_segs = 0;
3142         }
3143 
3144         return 0;
3145 }
3146 
3147 static u32 __bpf_skb_max_len(const struct sk_buff *skb)
3148 {
3149         return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
3150                           SKB_MAX_ALLOC;
3151 }
3152 
3153 BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
3154            u32, mode, u64, flags)
3155 {
3156         u32 len_cur, len_diff_abs = abs(len_diff);
3157         u32 len_min = bpf_skb_net_base_len(skb);
3158         u32 len_max = __bpf_skb_max_len(skb);
3159         __be16 proto = skb->protocol;
3160         bool shrink = len_diff < 0;
3161         u32 off;
3162         int ret;
3163 
3164         if (unlikely(flags & ~BPF_F_ADJ_ROOM_MASK))
3165                 return -EINVAL;
3166         if (unlikely(len_diff_abs > 0xfffU))
3167                 return -EFAULT;
3168         if (unlikely(proto != htons(ETH_P_IP) &&
3169                      proto != htons(ETH_P_IPV6)))
3170                 return -ENOTSUPP;
3171 
3172         off = skb_mac_header_len(skb);
3173         switch (mode) {
3174         case BPF_ADJ_ROOM_NET:
3175                 off += bpf_skb_net_base_len(skb);
3176                 break;
3177         case BPF_ADJ_ROOM_MAC:
3178                 break;
3179         default:
3180                 return -ENOTSUPP;
3181         }
3182 
3183         len_cur = skb->len - skb_network_offset(skb);
3184         if ((shrink && (len_diff_abs >= len_cur ||
3185                         len_cur - len_diff_abs < len_min)) ||
3186             (!shrink && (skb->len + len_diff_abs > len_max &&
3187                          !skb_is_gso(skb))))
3188                 return -ENOTSUPP;
3189 
3190         ret = shrink ? bpf_skb_net_shrink(skb, off, len_diff_abs, flags) :
3191                        bpf_skb_net_grow(skb, off, len_diff_abs, flags);
3192 
3193         bpf_compute_data_pointers(skb);
3194         return ret;
3195 }
3196 
3197 static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
3198         .func           = bpf_skb_adjust_room,
3199         .gpl_only       = false,
3200         .ret_type       = RET_INTEGER,
3201         .arg1_type      = ARG_PTR_TO_CTX,
3202         .arg2_type      = ARG_ANYTHING,
3203         .arg3_type      = ARG_ANYTHING,
3204         .arg4_type      = ARG_ANYTHING,
3205 };
3206 
3207 static u32 __bpf_skb_min_len(const struct sk_buff *skb)
3208 {
3209         u32 min_len = skb_network_offset(skb);
3210 
3211         if (skb_transport_header_was_set(skb))
3212                 min_len = skb_transport_offset(skb);
3213         if (skb->ip_summed == CHECKSUM_PARTIAL)
3214                 min_len = skb_checksum_start_offset(skb) +
3215                           skb->csum_offset + sizeof(__sum16);
3216         return min_len;
3217 }
3218 
3219 static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
3220 {
3221         unsigned int old_len = skb->len;
3222         int ret;
3223 
3224         ret = __skb_grow_rcsum(skb, new_len);
3225         if (!ret)
3226                 memset(skb->data + old_len, 0, new_len - old_len);
3227         return ret;
3228 }
3229 
3230 static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
3231 {
3232         return __skb_trim_rcsum(skb, new_len);
3233 }
3234 
3235 static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
3236                                         u64 flags)
3237 {
3238         u32 max_len = __bpf_skb_max_len(skb);
3239         u32 min_len = __bpf_skb_min_len(skb);
3240         int ret;
3241 
3242         if (unlikely(flags || new_len > max_len || new_len < min_len))
3243                 return -EINVAL;
3244         if (skb->encapsulation)
3245                 return -ENOTSUPP;
3246 
3247         /* The basic idea of this helper is that it's performing the
3248          * needed work to either grow or trim an skb, and eBPF program
3249          * rewrites the rest via helpers like bpf_skb_store_bytes(),
3250          * bpf_lX_csum_replace() and others rather than passing a raw
3251          * buffer here. This one is a slow path helper and intended
3252          * for replies with control messages.
3253          *
3254          * Like in bpf_skb_change_proto(), we want to keep this rather
3255          * minimal and without protocol specifics so that we are able
3256          * to separate concerns as in bpf_skb_store_bytes() should only
3257          * be the one responsible for writing buffers.
3258          *
3259          * It's really expected to be a slow path operation here for
3260          * control message replies, so we're implicitly linearizing,
3261          * uncloning and drop offloads from the skb by this.
3262          */
3263         ret = __bpf_try_make_writable(skb, skb->len);
3264         if (!ret) {
3265                 if (new_len > skb->len)
3266                         ret = bpf_skb_grow_rcsum(skb, new_len);
3267                 else if (new_len < skb->len)
3268                         ret = bpf_skb_trim_rcsum(skb, new_len);
3269                 if (!ret && skb_is_gso(skb))
3270                         skb_gso_reset(skb);
3271         }
3272         return ret;
3273 }
3274 
3275 BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3276            u64, flags)
3277 {
3278         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3279 
3280         bpf_compute_data_pointers(skb);
3281         return ret;
3282 }
3283 
3284 static const struct bpf_func_proto bpf_skb_change_tail_proto = {
3285         .func           = bpf_skb_change_tail,
3286         .gpl_only       = false,
3287         .ret_type       = RET_INTEGER,
3288         .arg1_type      = ARG_PTR_TO_CTX,
3289         .arg2_type      = ARG_ANYTHING,
3290         .arg3_type      = ARG_ANYTHING,
3291 };
3292 
3293 BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
3294            u64, flags)
3295 {
3296         int ret = __bpf_skb_change_tail(skb, new_len, flags);
3297 
3298         bpf_compute_data_end_sk_skb(skb);
3299         return ret;
3300 }
3301 
3302 static const struct bpf_func_proto sk_skb_change_tail_proto = {
3303         .func           = sk_skb_change_tail,
3304         .gpl_only       = false,
3305         .ret_type       = RET_INTEGER,
3306         .arg1_type      = ARG_PTR_TO_CTX,
3307         .arg2_type      = ARG_ANYTHING,
3308         .arg3_type      = ARG_ANYTHING,
3309 };
3310 
3311 static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
3312                                         u64 flags)
3313 {
3314         u32 max_len = __bpf_skb_max_len(skb);
3315         u32 new_len = skb->len + head_room;
3316         int ret;
3317 
3318         if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
3319                      new_len < skb->len))
3320                 return -EINVAL;
3321 
3322         ret = skb_cow(skb, head_room);
3323         if (likely(!ret)) {
3324                 /* Idea for this helper is that we currently only
3325                  * allow to expand on mac header. This means that
3326                  * skb->protocol network header, etc, stay as is.
3327                  * Compared to bpf_skb_change_tail(), we're more
3328                  * flexible due to not needing to linearize or
3329                  * reset GSO. Intention for this helper is to be
3330                  * used by an L3 skb that needs to push mac header
3331                  * for redirection into L2 device.
3332                  */
3333                 __skb_push(skb, head_room);
3334                 memset(skb->data, 0, head_room);
3335                 skb_reset_mac_header(skb);
3336         }
3337 
3338         return ret;
3339 }
3340 
3341 BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
3342            u64, flags)
3343 {
3344         int ret = __bpf_skb_change_head(skb, head_room, flags);
3345 
3346         bpf_compute_data_pointers(skb);
3347         return ret;
3348 }
3349 
3350 static const struct bpf_func_proto bpf_skb_change_head_proto = {
3351         .func           = bpf_skb_change_head,
3352         .gpl_only       = false,
3353         .ret_type       = RET_INTEGER,
3354         .arg1_type      = ARG_PTR_TO_CTX,
3355         .arg2_type      = ARG_ANYTHING,
3356         .arg3_type      = ARG_ANYTHING,
3357 };
3358 
3359 BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
3360            u64, flags)
3361 {
3362         int ret = __bpf_skb_change_head(skb, head_room, flags);
3363 
3364         bpf_compute_data_end_sk_skb(skb);
3365         return ret;
3366 }
3367 
3368 static const struct bpf_func_proto sk_skb_change_head_proto = {
3369         .func           = sk_skb_change_head,
3370         .gpl_only       = false,
3371         .ret_type       = RET_INTEGER,
3372         .arg1_type      = ARG_PTR_TO_CTX,
3373         .arg2_type      = ARG_ANYTHING,
3374         .arg3_type      = ARG_ANYTHING,
3375 };
3376 static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
3377 {
3378         return xdp_data_meta_unsupported(xdp) ? 0 :
3379                xdp->data - xdp->data_meta;
3380 }
3381 
3382 BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
3383 {
3384         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3385         unsigned long metalen = xdp_get_metalen(xdp);
3386         void *data_start = xdp_frame_end + metalen;
3387         void *data = xdp->data + offset;
3388 
3389         if (unlikely(data < data_start ||
3390                      data > xdp->data_end - ETH_HLEN))
3391                 return -EINVAL;
3392 
3393         if (metalen)
3394                 memmove(xdp->data_meta + offset,
3395                         xdp->data_meta, metalen);
3396         xdp->data_meta += offset;
3397         xdp->data = data;
3398 
3399         return 0;
3400 }
3401 
3402 static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
3403         .func           = bpf_xdp_adjust_head,
3404         .gpl_only       = false,
3405         .ret_type       = RET_INTEGER,
3406         .arg1_type      = ARG_PTR_TO_CTX,
3407         .arg2_type      = ARG_ANYTHING,
3408 };
3409 
3410 BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
3411 {
3412         void *data_end = xdp->data_end + offset;
3413 
3414         /* only shrinking is allowed for now. */
3415         if (unlikely(offset >= 0))
3416                 return -EINVAL;
3417 
3418         if (unlikely(data_end < xdp->data + ETH_HLEN))
3419                 return -EINVAL;
3420 
3421         xdp->data_end = data_end;
3422 
3423         return 0;
3424 }
3425 
3426 static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
3427         .func           = bpf_xdp_adjust_tail,
3428         .gpl_only       = false,
3429         .ret_type       = RET_INTEGER,
3430         .arg1_type      = ARG_PTR_TO_CTX,
3431         .arg2_type      = ARG_ANYTHING,
3432 };
3433 
3434 BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
3435 {
3436         void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3437         void *meta = xdp->data_meta + offset;
3438         unsigned long metalen = xdp->data - meta;
3439 
3440         if (xdp_data_meta_unsupported(xdp))
3441                 return -ENOTSUPP;
3442         if (unlikely(meta < xdp_frame_end ||
3443                      meta > xdp->data))
3444                 return -EINVAL;
3445         if (unlikely((metalen & (sizeof(__u32) - 1)) ||
3446                      (metalen > 32)))
3447                 return -EACCES;
3448 
3449         xdp->data_meta = meta;
3450 
3451         return 0;
3452 }
3453 
3454 static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
3455         .func           = bpf_xdp_adjust_meta,
3456         .gpl_only       = false,
3457         .ret_type       = RET_INTEGER,
3458         .arg1_type      = ARG_PTR_TO_CTX,
3459         .arg2_type      = ARG_ANYTHING,
3460 };
3461 
3462 static int __bpf_tx_xdp(struct net_device *dev,
3463                         struct bpf_map *map,
3464                         struct xdp_buff *xdp,
3465                         u32 index)
3466 {
3467         struct xdp_frame *xdpf;
3468         int err, sent;
3469 
3470         if (!dev->netdev_ops->ndo_xdp_xmit) {
3471                 return -EOPNOTSUPP;
3472         }
3473 
3474         err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
3475         if (unlikely(err))
3476                 return err;
3477 
3478         xdpf = convert_to_xdp_frame(xdp);
3479         if (unlikely(!xdpf))
3480                 return -EOVERFLOW;
3481 
3482         sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3483         if (sent <= 0)
3484                 return sent;
3485         return 0;
3486 }
3487 
3488 static noinline int
3489 xdp_do_redirect_slow(struct net_device *dev, struct xdp_buff *xdp,
3490                      struct bpf_prog *xdp_prog, struct bpf_redirect_info *ri)
3491 {
3492         struct net_device *fwd;
3493         u32 index = ri->tgt_index;
3494         int err;
3495 
3496         fwd = dev_get_by_index_rcu(dev_net(dev), index);
3497         ri->tgt_index = 0;
3498         if (unlikely(!fwd)) {
3499                 err = -EINVAL;
3500                 goto err;
3501         }
3502 
3503         err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3504         if (unlikely(err))
3505                 goto err;
3506 
3507         _trace_xdp_redirect(dev, xdp_prog, index);
3508         return 0;
3509 err:
3510         _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3511         return err;
3512 }
3513 
3514 static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
3515                             struct bpf_map *map,
3516                             struct xdp_buff *xdp,
3517                             u32 index)
3518 {
3519         int err;
3520 
3521         switch (map->map_type) {
3522         case BPF_MAP_TYPE_DEVMAP:
3523         case BPF_MAP_TYPE_DEVMAP_HASH: {
3524                 struct bpf_dtab_netdev *dst = fwd;
3525 
3526                 err = dev_map_enqueue(dst, xdp, dev_rx);
3527                 if (unlikely(err))
3528                         return err;
3529                 break;
3530         }
3531         case BPF_MAP_TYPE_CPUMAP: {
3532                 struct bpf_cpu_map_entry *rcpu = fwd;
3533 
3534                 err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3535                 if (unlikely(err))
3536                         return err;
3537                 break;
3538         }
3539         case BPF_MAP_TYPE_XSKMAP: {
3540                 struct xdp_sock *xs = fwd;
3541 
3542                 err = __xsk_map_redirect(map, xdp, xs);
3543                 return err;
3544         }
3545         default:
3546                 return -EBADRQC;
3547         }
3548         return 0;
3549 }
3550 
3551 void xdp_do_flush_map(void)
3552 {
3553         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3554         struct bpf_map *map = ri->map_to_flush;
3555 
3556         ri->map_to_flush = NULL;
3557         if (map) {
3558                 switch (map->map_type) {
3559                 case BPF_MAP_TYPE_DEVMAP:
3560                 case BPF_MAP_TYPE_DEVMAP_HASH:
3561                         __dev_map_flush(map);
3562                         break;
3563                 case BPF_MAP_TYPE_CPUMAP:
3564                         __cpu_map_flush(map);
3565                         break;
3566                 case BPF_MAP_TYPE_XSKMAP:
3567                         __xsk_map_flush(map);
3568                         break;
3569                 default:
3570                         break;
3571                 }
3572         }
3573 }
3574 EXPORT_SYMBOL_GPL(xdp_do_flush_map);
3575 
3576 static inline void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
3577 {
3578         switch (map->map_type) {
3579         case BPF_MAP_TYPE_DEVMAP:
3580                 return __dev_map_lookup_elem(map, index);
3581         case BPF_MAP_TYPE_DEVMAP_HASH:
3582                 return __dev_map_hash_lookup_elem(map, index);
3583         case BPF_MAP_TYPE_CPUMAP:
3584                 return __cpu_map_lookup_elem(map, index);
3585         case BPF_MAP_TYPE_XSKMAP:
3586                 return __xsk_map_lookup_elem(map, index);
3587         default:
3588                 return NULL;
3589         }
3590 }
3591 
3592 void bpf_clear_redirect_map(struct bpf_map *map)
3593 {
3594         struct bpf_redirect_info *ri;
3595         int cpu;
3596 
3597         for_each_possible_cpu(cpu) {
3598                 ri = per_cpu_ptr(&bpf_redirect_info, cpu);
3599                 /* Avoid polluting remote cacheline due to writes if
3600                  * not needed. Once we pass this test, we need the
3601                  * cmpxchg() to make sure it hasn't been changed in
3602                  * the meantime by remote CPU.
3603                  */
3604                 if (unlikely(READ_ONCE(ri->map) == map))
3605                         cmpxchg(&ri->map, map, NULL);
3606         }
3607 }
3608 
3609 static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3610                                struct bpf_prog *xdp_prog, struct bpf_map *map,
3611                                struct bpf_redirect_info *ri)
3612 {
3613         u32 index = ri->tgt_index;
3614         void *fwd = ri->tgt_value;
3615         int err;
3616 
3617         ri->tgt_index = 0;
3618         ri->tgt_value = NULL;
3619         WRITE_ONCE(ri->map, NULL);
3620 
3621         if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3622                 xdp_do_flush_map();
3623 
3624         err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3625         if (unlikely(err))
3626                 goto err;
3627 
3628         ri->map_to_flush = map;
3629         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3630         return 0;
3631 err:
3632         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3633         return err;
3634 }
3635 
3636 int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
3637                     struct bpf_prog *xdp_prog)
3638 {
3639         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3640         struct bpf_map *map = READ_ONCE(ri->map);
3641 
3642         if (likely(map))
3643                 return xdp_do_redirect_map(dev, xdp, xdp_prog, map, ri);
3644 
3645         return xdp_do_redirect_slow(dev, xdp, xdp_prog, ri);
3646 }
3647 EXPORT_SYMBOL_GPL(xdp_do_redirect);
3648 
3649 static int xdp_do_generic_redirect_map(struct net_device *dev,
3650                                        struct sk_buff *skb,
3651                                        struct xdp_buff *xdp,
3652                                        struct bpf_prog *xdp_prog,
3653                                        struct bpf_map *map)
3654 {
3655         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3656         u32 index = ri->tgt_index;
3657         void *fwd = ri->tgt_value;
3658         int err = 0;
3659 
3660         ri->tgt_index = 0;
3661         ri->tgt_value = NULL;
3662         WRITE_ONCE(ri->map, NULL);
3663 
3664         if (map->map_type == BPF_MAP_TYPE_DEVMAP ||
3665             map->map_type == BPF_MAP_TYPE_DEVMAP_HASH) {
3666                 struct bpf_dtab_netdev *dst = fwd;
3667 
3668                 err = dev_map_generic_redirect(dst, skb, xdp_prog);
3669                 if (unlikely(err))
3670                         goto err;
3671         } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
3672                 struct xdp_sock *xs = fwd;
3673 
3674                 err = xsk_generic_rcv(xs, xdp);
3675                 if (err)
3676                         goto err;
3677                 consume_skb(skb);
3678         } else {
3679                 /* TODO: Handle BPF_MAP_TYPE_CPUMAP */
3680                 err = -EBADRQC;
3681                 goto err;
3682         }
3683 
3684         _trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3685         return 0;
3686 err:
3687         _trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3688         return err;
3689 }
3690 
3691 int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3692                             struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3693 {
3694         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3695         struct bpf_map *map = READ_ONCE(ri->map);
3696         u32 index = ri->tgt_index;
3697         struct net_device *fwd;
3698         int err = 0;
3699 
3700         if (map)
3701                 return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
3702                                                    map);
3703         ri->tgt_index = 0;
3704         fwd = dev_get_by_index_rcu(dev_net(dev), index);
3705         if (unlikely(!fwd)) {
3706                 err = -EINVAL;
3707                 goto err;
3708         }
3709 
3710         err = xdp_ok_fwd_dev(fwd, skb->len);
3711         if (unlikely(err))
3712                 goto err;
3713 
3714         skb->dev = fwd;
3715         _trace_xdp_redirect(dev, xdp_prog, index);
3716         generic_xdp_tx(skb, xdp_prog);
3717         return 0;
3718 err:
3719         _trace_xdp_redirect_err(dev, xdp_prog, index, err);
3720         return err;
3721 }
3722 EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);
3723 
3724 BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
3725 {
3726         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3727 
3728         if (unlikely(flags))
3729                 return XDP_ABORTED;
3730 
3731         ri->flags = flags;
3732         ri->tgt_index = ifindex;
3733         ri->tgt_value = NULL;
3734         WRITE_ONCE(ri->map, NULL);
3735 
3736         return XDP_REDIRECT;
3737 }
3738 
3739 static const struct bpf_func_proto bpf_xdp_redirect_proto = {
3740         .func           = bpf_xdp_redirect,
3741         .gpl_only       = false,
3742         .ret_type       = RET_INTEGER,
3743         .arg1_type      = ARG_ANYTHING,
3744         .arg2_type      = ARG_ANYTHING,
3745 };
3746 
3747 BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
3748            u64, flags)
3749 {
3750         struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3751 
3752         /* Lower bits of the flags are used as return code on lookup failure */
3753         if (unlikely(flags > XDP_TX))
3754                 return XDP_ABORTED;
3755 
3756         ri->tgt_value = __xdp_map_lookup_elem(map, ifindex);
3757         if (unlikely(!ri->tgt_value)) {
3758                 /* If the lookup fails we want to clear out the state in the
3759                  * redirect_info struct completely, so that if an eBPF program
3760                  * performs multiple lookups, the last one always takes
3761                  * precedence.
3762                  */
3763                 WRITE_ONCE(ri->map, NULL);
3764                 return flags;
3765         }
3766 
3767         ri->flags = flags;
3768         ri->tgt_index = ifindex;
3769         WRITE_ONCE(ri->map, map);
3770 
3771         return XDP_REDIRECT;
3772 }
3773 
3774 static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
3775         .func           = bpf_xdp_redirect_map,
3776         .gpl_only       = false,
3777         .ret_type       = RET_INTEGER,
3778         .arg1_type      = ARG_CONST_MAP_PTR,
3779         .arg2_type      = ARG_ANYTHING,
3780         .arg3_type      = ARG_ANYTHING,
3781 };
3782 
3783 static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3784                                   unsigned long off, unsigned long len)
3785 {
3786         void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3787 
3788         if (unlikely(!ptr))
3789                 return len;
3790         if (ptr != dst_buff)
3791                 memcpy(dst_buff, ptr, len);
3792 
3793         return 0;
3794 }
3795 
3796 BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
3797            u64, flags, void *, meta, u64, meta_size)
3798 {
3799         u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
3800 
3801         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
3802                 return -EINVAL;
3803         if (unlikely(skb_size > skb->len))
3804                 return -EFAULT;
3805 
3806         return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
3807                                 bpf_skb_copy);
3808 }
3809 
3810 static const struct bpf_func_proto bpf_skb_event_output_proto = {
3811         .func           = bpf_skb_event_output,
3812         .gpl_only       = true,
3813         .ret_type       = RET_INTEGER,
3814         .arg1_type      = ARG_PTR_TO_CTX,
3815         .arg2_type      = ARG_CONST_MAP_PTR,
3816         .arg3_type      = ARG_ANYTHING,
3817         .arg4_type      = ARG_PTR_TO_MEM,
3818         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
3819 };
3820 
3821 static unsigned short bpf_tunnel_key_af(u64 flags)
3822 {
3823         return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
3824 }
3825 
3826 BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
3827            u32, size, u64, flags)
3828 {
3829         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3830         u8 compat[sizeof(struct bpf_tunnel_key)];
3831         void *to_orig = to;
3832         int err;
3833 
3834         if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
3835                 err = -EINVAL;
3836                 goto err_clear;
3837         }
3838         if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
3839                 err = -EPROTO;
3840                 goto err_clear;
3841         }
3842         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3843                 err = -EINVAL;
3844                 switch (size) {
3845                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3846                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3847                         goto set_compat;
3848                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3849                         /* Fixup deprecated structure layouts here, so we have
3850                          * a common path later on.
3851                          */
3852                         if (ip_tunnel_info_af(info) != AF_INET)
3853                                 goto err_clear;
3854 set_compat:
3855                         to = (struct bpf_tunnel_key *)compat;
3856                         break;
3857                 default:
3858                         goto err_clear;
3859                 }
3860         }
3861 
3862         to->tunnel_id = be64_to_cpu(info->key.tun_id);
3863         to->tunnel_tos = info->key.tos;
3864         to->tunnel_ttl = info->key.ttl;
3865         to->tunnel_ext = 0;
3866 
3867         if (flags & BPF_F_TUNINFO_IPV6) {
3868                 memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
3869                        sizeof(to->remote_ipv6));
3870                 to->tunnel_label = be32_to_cpu(info->key.label);
3871         } else {
3872                 to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3873                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
3874                 to->tunnel_label = 0;
3875         }
3876 
3877         if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3878                 memcpy(to_orig, to, size);
3879 
3880         return 0;
3881 err_clear:
3882         memset(to_orig, 0, size);
3883         return err;
3884 }
3885 
3886 static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3887         .func           = bpf_skb_get_tunnel_key,
3888         .gpl_only       = false,
3889         .ret_type       = RET_INTEGER,
3890         .arg1_type      = ARG_PTR_TO_CTX,
3891         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3892         .arg3_type      = ARG_CONST_SIZE,
3893         .arg4_type      = ARG_ANYTHING,
3894 };
3895 
3896 BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3897 {
3898         const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3899         int err;
3900 
3901         if (unlikely(!info ||
3902                      !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
3903                 err = -ENOENT;
3904                 goto err_clear;
3905         }
3906         if (unlikely(size < info->options_len)) {
3907                 err = -ENOMEM;
3908                 goto err_clear;
3909         }
3910 
3911         ip_tunnel_info_opts_get(to, info);
3912         if (size > info->options_len)
3913                 memset(to + info->options_len, 0, size - info->options_len);
3914 
3915         return info->options_len;
3916 err_clear:
3917         memset(to, 0, size);
3918         return err;
3919 }
3920 
3921 static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
3922         .func           = bpf_skb_get_tunnel_opt,
3923         .gpl_only       = false,
3924         .ret_type       = RET_INTEGER,
3925         .arg1_type      = ARG_PTR_TO_CTX,
3926         .arg2_type      = ARG_PTR_TO_UNINIT_MEM,
3927         .arg3_type      = ARG_CONST_SIZE,
3928 };
3929 
3930 static struct metadata_dst __percpu *md_dst;
3931 
3932 BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
3933            const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3934 {
3935         struct metadata_dst *md = this_cpu_ptr(md_dst);
3936         u8 compat[sizeof(struct bpf_tunnel_key)];
3937         struct ip_tunnel_info *info;
3938 
3939         if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3940                                BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3941                 return -EINVAL;
3942         if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3943                 switch (size) {
3944                 case offsetof(struct bpf_tunnel_key, tunnel_label):
3945                 case offsetof(struct bpf_tunnel_key, tunnel_ext):
3946                 case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
3947                         /* Fixup deprecated structure layouts here, so we have
3948                          * a common path later on.
3949                          */
3950                         memcpy(compat, from, size);
3951                         memset(compat + size, 0, sizeof(compat) - size);
3952                         from = (const struct bpf_tunnel_key *) compat;
3953                         break;
3954                 default:
3955                         return -EINVAL;
3956                 }
3957         }
3958         if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
3959                      from->tunnel_ext))
3960                 return -EINVAL;
3961 
3962         skb_dst_drop(skb);
3963         dst_hold((struct dst_entry *) md);
3964         skb_dst_set(skb, (struct dst_entry *) md);
3965 
3966         info = &md->u.tun_info;
3967         memset(info, 0, sizeof(*info));
3968         info->mode = IP_TUNNEL_INFO_TX;
3969 
3970         info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3971         if (flags & BPF_F_DONT_FRAGMENT)
3972                 info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
3973         if (flags & BPF_F_ZERO_CSUM_TX)
3974                 info->key.tun_flags &= ~TUNNEL_CSUM;
3975         if (flags & BPF_F_SEQ_NUMBER)
3976                 info->key.tun_flags |= TUNNEL_SEQ;
3977 
3978         info->key.tun_id = cpu_to_be64(from->tunnel_id);
3979         info->key.tos = from->tunnel_tos;
3980         info->key.ttl = from->tunnel_ttl;
3981 
3982         if (flags & BPF_F_TUNINFO_IPV6) {
3983                 info->mode |= IP_TUNNEL_INFO_IPV6;
3984                 memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
3985                        sizeof(from->remote_ipv6));
3986                 info->key.label = cpu_to_be32(from->tunnel_label) &
3987                                   IPV6_FLOWLABEL_MASK;
3988         } else {
3989                 info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
3990         }
3991 
3992         return 0;
3993 }
3994 
3995 static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3996         .func           = bpf_skb_set_tunnel_key,
3997         .gpl_only       = false,
3998         .ret_type       = RET_INTEGER,
3999         .arg1_type      = ARG_PTR_TO_CTX,
4000         .arg2_type      = ARG_PTR_TO_MEM,
4001         .arg3_type      = ARG_CONST_SIZE,
4002         .arg4_type      = ARG_ANYTHING,
4003 };
4004 
4005 BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
4006            const u8 *, from, u32, size)
4007 {
4008         struct ip_tunnel_info *info = skb_tunnel_info(skb);
4009         const struct metadata_dst *md = this_cpu_ptr(md_dst);
4010 
4011         if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
4012                 return -EINVAL;
4013         if (unlikely(size > IP_TUNNEL_OPTS_MAX))
4014                 return -ENOMEM;
4015 
4016         ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
4017 
4018         return 0;
4019 }
4020 
4021 static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
4022         .func           = bpf_skb_set_tunnel_opt,
4023         .gpl_only       = false,
4024         .ret_type       = RET_INTEGER,
4025         .arg1_type      = ARG_PTR_TO_CTX,
4026         .arg2_type      = ARG_PTR_TO_MEM,
4027         .arg3_type      = ARG_CONST_SIZE,
4028 };
4029 
4030 static const struct bpf_func_proto *
4031 bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
4032 {
4033         if (!md_dst) {
4034                 struct metadata_dst __percpu *tmp;
4035 
4036                 tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
4037                                                 METADATA_IP_TUNNEL,
4038                                                 GFP_KERNEL);
4039                 if (!tmp)
4040                         return NULL;
4041                 if (cmpxchg(&md_dst, NULL, tmp))
4042                         metadata_dst_free_percpu(tmp);
4043         }
4044 
4045         switch (which) {
4046         case BPF_FUNC_skb_set_tunnel_key:
4047                 return &bpf_skb_set_tunnel_key_proto;
4048         case BPF_FUNC_skb_set_tunnel_opt:
4049                 return &bpf_skb_set_tunnel_opt_proto;
4050         default:
4051                 return NULL;
4052         }
4053 }
4054 
4055 BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
4056            u32, idx)
4057 {
4058         struct bpf_array *array = container_of(map, struct bpf_array, map);
4059         struct cgroup *cgrp;
4060         struct sock *sk;
4061 
4062         sk = skb_to_full_sk(skb);
4063         if (!sk || !sk_fullsock(sk))
4064                 return -ENOENT;
4065         if (unlikely(idx >= array->map.max_entries))
4066                 return -E2BIG;
4067 
4068         cgrp = READ_ONCE(array->ptrs[idx]);
4069         if (unlikely(!cgrp))
4070                 return -EAGAIN;
4071 
4072         return sk_under_cgroup_hierarchy(sk, cgrp);
4073 }
4074 
4075 static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
4076         .func           = bpf_skb_under_cgroup,
4077         .gpl_only       = false,
4078         .ret_type       = RET_INTEGER,
4079         .arg1_type      = ARG_PTR_TO_CTX,
4080         .arg2_type      = ARG_CONST_MAP_PTR,
4081         .arg3_type      = ARG_ANYTHING,
4082 };
4083 
4084 #ifdef CONFIG_SOCK_CGROUP_DATA
4085 BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
4086 {
4087         struct sock *sk = skb_to_full_sk(skb);
4088         struct cgroup *cgrp;
4089 
4090         if (!sk || !sk_fullsock(sk))
4091                 return 0;
4092 
4093         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4094         return cgrp->kn->id.id;
4095 }
4096 
4097 static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
4098         .func           = bpf_skb_cgroup_id,
4099         .gpl_only       = false,
4100         .ret_type       = RET_INTEGER,
4101         .arg1_type      = ARG_PTR_TO_CTX,
4102 };
4103 
4104 BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
4105            ancestor_level)
4106 {
4107         struct sock *sk = skb_to_full_sk(skb);
4108         struct cgroup *ancestor;
4109         struct cgroup *cgrp;
4110 
4111         if (!sk || !sk_fullsock(sk))
4112                 return 0;
4113 
4114         cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
4115         ancestor = cgroup_ancestor(cgrp, ancestor_level);
4116         if (!ancestor)
4117                 return 0;
4118 
4119         return ancestor->kn->id.id;
4120 }
4121 
4122 static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
4123         .func           = bpf_skb_ancestor_cgroup_id,
4124         .gpl_only       = false,
4125         .ret_type       = RET_INTEGER,
4126         .arg1_type      = ARG_PTR_TO_CTX,
4127         .arg2_type      = ARG_ANYTHING,
4128 };
4129 #endif
4130 
4131 static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
4132                                   unsigned long off, unsigned long len)
4133 {
4134         memcpy(dst_buff, src_buff + off, len);
4135         return 0;
4136 }
4137 
4138 BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
4139            u64, flags, void *, meta, u64, meta_size)
4140 {
4141         u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;
4142 
4143         if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
4144                 return -EINVAL;
4145         if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
4146                 return -EFAULT;
4147 
4148         return bpf_event_output(map, flags, meta, meta_size, xdp->data,
4149                                 xdp_size, bpf_xdp_copy);
4150 }
4151 
4152 static const struct bpf_func_proto bpf_xdp_event_output_proto = {
4153         .func           = bpf_xdp_event_output,
4154         .gpl_only       = true,
4155         .ret_type       = RET_INTEGER,
4156         .arg1_type      = ARG_PTR_TO_CTX,
4157         .arg2_type      = ARG_CONST_MAP_PTR,
4158         .arg3_type      = ARG_ANYTHING,
4159         .arg4_type      = ARG_PTR_TO_MEM,
4160         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4161 };
4162 
4163 BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
4164 {
4165         return skb->sk ? sock_gen_cookie(skb->sk) : 0;
4166 }
4167 
4168 static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
4169         .func           = bpf_get_socket_cookie,
4170         .gpl_only       = false,
4171         .ret_type       = RET_INTEGER,
4172         .arg1_type      = ARG_PTR_TO_CTX,
4173 };
4174 
4175 BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
4176 {
4177         return sock_gen_cookie(ctx->sk);
4178 }
4179 
4180 static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
4181         .func           = bpf_get_socket_cookie_sock_addr,
4182         .gpl_only       = false,
4183         .ret_type       = RET_INTEGER,
4184         .arg1_type      = ARG_PTR_TO_CTX,
4185 };
4186 
4187 BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
4188 {
4189         return sock_gen_cookie(ctx->sk);
4190 }
4191 
4192 static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
4193         .func           = bpf_get_socket_cookie_sock_ops,
4194         .gpl_only       = false,
4195         .ret_type       = RET_INTEGER,
4196         .arg1_type      = ARG_PTR_TO_CTX,
4197 };
4198 
4199 BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
4200 {
4201         struct sock *sk = sk_to_full_sk(skb->sk);
4202         kuid_t kuid;
4203 
4204         if (!sk || !sk_fullsock(sk))
4205                 return overflowuid;
4206         kuid = sock_net_uid(sock_net(sk), sk);
4207         return from_kuid_munged(sock_net(sk)->user_ns, kuid);
4208 }
4209 
4210 static const struct bpf_func_proto bpf_get_socket_uid_proto = {
4211         .func           = bpf_get_socket_uid,
4212         .gpl_only       = false,
4213         .ret_type       = RET_INTEGER,
4214         .arg1_type      = ARG_PTR_TO_CTX,
4215 };
4216 
4217 BPF_CALL_5(bpf_sockopt_event_output, struct bpf_sock_ops_kern *, bpf_sock,
4218            struct bpf_map *, map, u64, flags, void *, data, u64, size)
4219 {
4220         if (unlikely(flags & ~(BPF_F_INDEX_MASK)))
4221                 return -EINVAL;
4222 
4223         return bpf_event_output(map, flags, data, size, NULL, 0, NULL);
4224 }
4225 
4226 static const struct bpf_func_proto bpf_sockopt_event_output_proto =  {
4227         .func           = bpf_sockopt_event_output,
4228         .gpl_only       = true,
4229         .ret_type       = RET_INTEGER,
4230         .arg1_type      = ARG_PTR_TO_CTX,
4231         .arg2_type      = ARG_CONST_MAP_PTR,
4232         .arg3_type      = ARG_ANYTHING,
4233         .arg4_type      = ARG_PTR_TO_MEM,
4234         .arg5_type      = ARG_CONST_SIZE_OR_ZERO,
4235 };
4236 
4237 BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4238            int, level, int, optname, char *, optval, int, optlen)
4239 {
4240         struct sock *sk = bpf_sock->sk;
4241         int ret = 0;
4242         int val;
4243 
4244         if (!sk_fullsock(sk))
4245                 return -EINVAL;
4246 
4247         if (level == SOL_SOCKET) {
4248                 if (optlen != sizeof(int))
4249                         return -EINVAL;
4250                 val = *((int *)optval);
4251 
4252                 /* Only some socketops are supported */
4253                 switch (optname) {
4254                 case SO_RCVBUF:
4255                         val = min_t(u32, val, sysctl_rmem_max);
4256                         sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
4257                         WRITE_ONCE(sk->sk_rcvbuf,
4258                                    max_t(int, val * 2, SOCK_MIN_RCVBUF));
4259                         break;
4260                 case SO_SNDBUF:
4261                         val = min_t(u32, val, sysctl_wmem_max);
4262                         sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
4263                         WRITE_ONCE(sk->sk_sndbuf,
4264                                    max_t(int, val * 2, SOCK_MIN_SNDBUF));
4265                         break;
4266                 case SO_MAX_PACING_RATE: /* 32bit version */
4267                         if (val != ~0U)
4268                                 cmpxchg(&sk->sk_pacing_status,
4269                                         SK_PACING_NONE,
4270                                         SK_PACING_NEEDED);
4271                         sk->sk_max_pacing_rate = (val == ~0U) ? ~0UL : val;
4272                         sk->sk_pacing_rate = min(sk->sk_pacing_rate,
4273                                                  sk->sk_max_pacing_rate);
4274                         break;
4275                 case SO_PRIORITY:
4276                         sk->sk_priority = val;
4277                         break;
4278                 case SO_RCVLOWAT:
4279                         if (val < 0)
4280                                 val = INT_MAX;
4281                         WRITE_ONCE(sk->sk_rcvlowat, val ? : 1);
4282                         break;
4283                 case SO_MARK:
4284                         if (sk->sk_mark != val) {
4285                                 sk->sk_mark = val;
4286                                 sk_dst_reset(sk);
4287                         }
4288                         break;
4289                 default:
4290                         ret = -EINVAL;
4291                 }
4292 #ifdef CONFIG_INET
4293         } else if (level == SOL_IP) {
4294                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4295                         return -EINVAL;
4296 
4297                 val = *((int *)optval);
4298                 /* Only some options are supported */
4299                 switch (optname) {
4300                 case IP_TOS:
4301                         if (val < -1 || val > 0xff) {
4302                                 ret = -EINVAL;
4303                         } else {
4304                                 struct inet_sock *inet = inet_sk(sk);
4305 
4306                                 if (val == -1)
4307                                         val = 0;
4308                                 inet->tos = val;
4309                         }
4310                         break;
4311                 default:
4312                         ret = -EINVAL;
4313                 }
4314 #if IS_ENABLED(CONFIG_IPV6)
4315         } else if (level == SOL_IPV6) {
4316                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4317                         return -EINVAL;
4318 
4319                 val = *((int *)optval);
4320                 /* Only some options are supported */
4321                 switch (optname) {
4322                 case IPV6_TCLASS:
4323                         if (val < -1 || val > 0xff) {
4324                                 ret = -EINVAL;
4325                         } else {
4326                                 struct ipv6_pinfo *np = inet6_sk(sk);
4327 
4328                                 if (val == -1)
4329                                         val = 0;
4330                                 np->tclass = val;
4331                         }
4332                         break;
4333                 default:
4334                         ret = -EINVAL;
4335                 }
4336 #endif
4337         } else if (level == SOL_TCP &&
4338                    sk->sk_prot->setsockopt == tcp_setsockopt) {
4339                 if (optname == TCP_CONGESTION) {
4340                         char name[TCP_CA_NAME_MAX];
4341                         bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
4342 
4343                         strncpy(name, optval, min_t(long, optlen,
4344                                                     TCP_CA_NAME_MAX-1));
4345                         name[TCP_CA_NAME_MAX-1] = 0;
4346                         ret = tcp_set_congestion_control(sk, name, false,
4347                                                          reinit, true);
4348                 } else {
4349                         struct tcp_sock *tp = tcp_sk(sk);
4350 
4351                         if (optlen != sizeof(int))
4352                                 return -EINVAL;
4353 
4354                         val = *((int *)optval);
4355                         /* Only some options are supported */
4356                         switch (optname) {
4357                         case TCP_BPF_IW:
4358                                 if (val <= 0 || tp->data_segs_out > tp->syn_data)
4359                                         ret = -EINVAL;
4360                                 else
4361                                         tp->snd_cwnd = val;
4362                                 break;
4363                         case TCP_BPF_SNDCWND_CLAMP:
4364                                 if (val <= 0) {
4365                                         ret = -EINVAL;
4366                                 } else {
4367                                         tp->snd_cwnd_clamp = val;
4368                                         tp->snd_ssthresh = val;
4369                                 }
4370                                 break;
4371                         case TCP_SAVE_SYN:
4372                                 if (val < 0 || val > 1)
4373                                         ret = -EINVAL;
4374                                 else
4375                                         tp->save_syn = val;
4376                                 break;
4377                         default:
4378                                 ret = -EINVAL;
4379                         }
4380                 }
4381 #endif
4382         } else {
4383                 ret = -EINVAL;
4384         }
4385         return ret;
4386 }
4387 
4388 static const struct bpf_func_proto bpf_setsockopt_proto = {
4389         .func           = bpf_setsockopt,
4390         .gpl_only       = false,
4391         .ret_type       = RET_INTEGER,
4392         .arg1_type      = ARG_PTR_TO_CTX,
4393         .arg2_type      = ARG_ANYTHING,
4394         .arg3_type      = ARG_ANYTHING,
4395         .arg4_type      = ARG_PTR_TO_MEM,
4396         .arg5_type      = ARG_CONST_SIZE,
4397 };
4398 
4399 BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
4400            int, level, int, optname, char *, optval, int, optlen)
4401 {
4402         struct sock *sk = bpf_sock->sk;
4403 
4404         if (!sk_fullsock(sk))
4405                 goto err_clear;
4406 #ifdef CONFIG_INET
4407         if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4408                 struct inet_connection_sock *icsk;
4409                 struct tcp_sock *tp;
4410 
4411                 switch (optname) {
4412                 case TCP_CONGESTION:
4413                         icsk = inet_csk(sk);
4414 
4415                         if (!icsk->icsk_ca_ops || optlen <= 1)
4416                                 goto err_clear;
4417                         strncpy(optval, icsk->icsk_ca_ops->name, optlen);
4418                         optval[optlen - 1] = 0;
4419                         break;
4420                 case TCP_SAVED_SYN:
4421                         tp = tcp_sk(sk);
4422 
4423                         if (optlen <= 0 || !tp->saved_syn ||
4424                             optlen > tp->saved_syn[0])
4425                                 goto err_clear;
4426                         memcpy(optval, tp->saved_syn + 1, optlen);
4427                         break;
4428                 default:
4429                         goto err_clear;
4430                 }
4431         } else if (level == SOL_IP) {
4432                 struct inet_sock *inet = inet_sk(sk);
4433 
4434                 if (optlen != sizeof(int) || sk->sk_family != AF_INET)
4435                         goto err_clear;
4436 
4437                 /* Only some options are supported */
4438                 switch (optname) {
4439                 case IP_TOS:
4440                         *((int *)optval) = (int)inet->tos;
4441                         break;
4442                 default:
4443                         goto err_clear;
4444                 }
4445 #if IS_ENABLED(CONFIG_IPV6)
4446         } else if (level == SOL_IPV6) {
4447                 struct ipv6_pinfo *np = inet6_sk(sk);
4448 
4449                 if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
4450                         goto err_clear;
4451 
4452                 /* Only some options are supported */
4453                 switch (optname) {
4454                 case IPV6_TCLASS:
4455                         *((int *)optval) = (int)np->tclass;
4456                         break;
4457                 default:
4458                         goto err_clear;
4459                 }
4460 #endif
4461         } else {
4462                 goto err_clear;
4463         }
4464         return 0;
4465 #endif
4466 err_clear:
4467         memset(optval, 0, optlen);
4468         return -EINVAL;
4469 }
4470 
4471 static const struct bpf_func_proto bpf_getsockopt_proto = {
4472         .func           = bpf_getsockopt,
4473         .gpl_only       = false,
4474         .ret_type       = RET_INTEGER,
4475         .arg1_type      = ARG_PTR_TO_CTX,
4476         .arg2_type      = ARG_ANYTHING,
4477         .arg3_type      = ARG_ANYTHING,
4478         .arg4_type      = ARG_PTR_TO_UNINIT_MEM,
4479         .arg5_type      = ARG_CONST_SIZE,
4480 };
4481 
4482 BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
4483            int, argval)
4484 {
4485         struct sock *sk = bpf_sock->sk;
4486         int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;
4487 
4488         if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4489                 return -EINVAL;
4490 
4491         tcp_sk(sk)->bpf_sock_ops_cb_flags = val;
4492 
4493         return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
4494 }
4495 
4496 static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
4497         .func           = bpf_sock_ops_cb_flags_set,
4498         .gpl_only       = false,
4499         .ret_type       = RET_INTEGER,
4500         .arg1_type      = ARG_PTR_TO_CTX,
4501         .arg2_type      = ARG_ANYTHING,
4502 };
4503 
4504 const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
4505 EXPORT_SYMBOL_GPL(ipv6_bpf_stub);
4506 
4507 BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
4508            int, addr_len)
4509 {
4510 #ifdef CONFIG_INET
4511         struct sock *sk = ctx->sk;
4512         int err;
4513 
4514         /* Binding to port can be expensive so it's prohibited in the helper.
4515          * Only binding to IP is supported.
4516          */
4517         err = -EINVAL;
4518         if (addr_len < offsetofend(struct sockaddr, sa_family))
4519                 return err;
4520         if (addr->sa_family == AF_INET) {
4521                 if (addr_len < sizeof(struct sockaddr_in))
4522                         return err;
4523                 if (((struct sockaddr_in *)addr)->sin_port != htons(0))
4524                         return err;
4525                 return __inet_bind(sk, addr, addr_len, true, false);
4526 #if IS_ENABLED(CONFIG_IPV6)
4527         } else if (addr->sa_family == AF_INET6) {
4528                 if (addr_len < SIN6_LEN_RFC2133)
4529                         return err;
4530                 if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
4531                         return err;
4532                 /* ipv6_bpf_stub cannot be NULL, since it's called from
4533                  * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
4534                  */
4535                 return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
4536 #endif /* CONFIG_IPV6 */
4537         }
4538 #endif /* CONFIG_INET */
4539 
4540         return -EAFNOSUPPORT;
4541 }
4542 
4543 static const struct bpf_func_proto bpf_bind_proto = {
4544         .func           = bpf_bind,
4545         .gpl_only       = false,
4546         .ret_type       = RET_INTEGER,
4547         .arg1_type      = ARG_PTR_TO_CTX,
4548         .arg2_type      = ARG_PTR_TO_MEM,
4549         .arg3_type      = ARG_CONST_SIZE,
4550 };
4551 
4552 #ifdef CONFIG_XFRM
4553 BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
4554            struct bpf_xfrm_state *, to, u32, size, u64, flags)
4555 {
4556         const struct sec_path *sp = skb_sec_path(skb);
4557         const struct xfrm_state *x;
4558 
4559         if (!sp || unlikely(index >= sp->len || flags))
4560                 goto err_clear;
4561 
4562         x = sp->xvec[index];
4563 
4564         if (unlikely(size != sizeof(struct bpf_xfrm_state)))
4565                 goto err_clear;
4566 
4567         to->reqid = x->props.reqid;
4568         to->spi = x->id.spi;
4569         to->family = x->props.family;
4570         to->ext = 0;
4571 
4572         if (to->family == AF_INET6) {
4573                 memcpy(to->remote_ipv6, x->props.saddr.a6,
4574                        sizeof(to->remote_ipv6));
4575         } else {
4576                 to->remote_ipv4 = x->props.saddr.a4;
4577                 memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4578         }
4579 
4580         return 0;
4581 err_clear:
4582         memset(to, 0, size);
4583         return -EINVAL;
4584 }
4585 
4586 static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
4587         .func           = bpf_skb_get_xfrm_state,
4588         .gpl_only       = false,
4589         .ret_type       = RET_INTEGER,
4590         .arg1_type      = ARG_PTR_TO_CTX,
4591         .arg2_type      = ARG_ANYTHING,
4592         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
4593         .arg4_type      = ARG_CONST_SIZE,
4594         .arg5_type      = ARG_ANYTHING,
4595 };
4596 #endif
4597 
4598 #if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
4599 static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
4600                                   const struct neighbour *neigh,
4601                                   const struct net_device *dev)
4602 {
4603         memcpy(params->dmac, neigh->ha, ETH_ALEN);
4604         memcpy(params->smac, dev->dev_addr, ETH_ALEN);
4605         params->h_vlan_TCI = 0;
4606         params->h_vlan_proto = 0;
4607         params->ifindex = dev->ifindex;
4608 
4609         return 0;
4610 }
4611 #endif
4612 
4613 #if IS_ENABLED(CONFIG_INET)
4614 static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4615                                u32 flags, bool check_mtu)
4616 {
4617         struct fib_nh_common *nhc;
4618         struct in_device *in_dev;
4619         struct neighbour *neigh;
4620         struct net_device *dev;
4621         struct fib_result res;
4622         struct flowi4 fl4;
4623         int err;
4624         u32 mtu;
4625 
4626         dev = dev_get_by_index_rcu(net, params->ifindex);
4627         if (unlikely(!dev))
4628                 return -ENODEV;
4629 
4630         /* verify forwarding is enabled on this interface */
4631         in_dev = __in_dev_get_rcu(dev);
4632         if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4633                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4634 
4635         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4636                 fl4.flowi4_iif = 1;
4637                 fl4.flowi4_oif = params->ifindex;
4638         } else {
4639                 fl4.flowi4_iif = params->ifindex;
4640                 fl4.flowi4_oif = 0;
4641         }
4642         fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
4643         fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
4644         fl4.flowi4_flags = 0;
4645 
4646         fl4.flowi4_proto = params->l4_protocol;
4647         fl4.daddr = params->ipv4_dst;
4648         fl4.saddr = params->ipv4_src;
4649         fl4.fl4_sport = params->sport;
4650         fl4.fl4_dport = params->dport;
4651 
4652         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4653                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4654                 struct fib_table *tb;
4655 
4656                 tb = fib_get_table(net, tbid);
4657                 if (unlikely(!tb))
4658                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4659 
4660                 err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
4661         } else {
4662                 fl4.flowi4_mark = 0;
4663                 fl4.flowi4_secid = 0;
4664                 fl4.flowi4_tun_key.tun_id = 0;
4665                 fl4.flowi4_uid = sock_net_uid(net, NULL);
4666 
4667                 err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
4668         }
4669 
4670         if (err) {
4671                 /* map fib lookup errors to RTN_ type */
4672                 if (err == -EINVAL)
4673                         return BPF_FIB_LKUP_RET_BLACKHOLE;
4674                 if (err == -EHOSTUNREACH)
4675                         return BPF_FIB_LKUP_RET_UNREACHABLE;
4676                 if (err == -EACCES)
4677                         return BPF_FIB_LKUP_RET_PROHIBIT;
4678 
4679                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4680         }
4681 
4682         if (res.type != RTN_UNICAST)
4683                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4684 
4685         if (fib_info_num_path(res.fi) > 1)
4686                 fib_select_path(net, &res, &fl4, NULL);
4687 
4688         if (check_mtu) {
4689                 mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
4690                 if (params->tot_len > mtu)
4691                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4692         }
4693 
4694         nhc = res.nhc;
4695 
4696         /* do not handle lwt encaps right now */
4697         if (nhc->nhc_lwtstate)
4698                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4699 
4700         dev = nhc->nhc_dev;
4701 
4702         params->rt_metric = res.fi->fib_priority;
4703 
4704         /* xdp and cls_bpf programs are run in RCU-bh so
4705          * rcu_read_lock_bh is not needed here
4706          */
4707         if (likely(nhc->nhc_gw_family != AF_INET6)) {
4708                 if (nhc->nhc_gw_family)
4709                         params->ipv4_dst = nhc->nhc_gw.ipv4;
4710 
4711                 neigh = __ipv4_neigh_lookup_noref(dev,
4712                                                  (__force u32)params->ipv4_dst);
4713         } else {
4714                 struct in6_addr *dst = (struct in6_addr *)params->ipv6_dst;
4715 
4716                 params->family = AF_INET6;
4717                 *dst = nhc->nhc_gw.ipv6;
4718                 neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4719         }
4720 
4721         if (!neigh)
4722                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4723 
4724         return bpf_fib_set_fwd_params(params, neigh, dev);
4725 }
4726 #endif
4727 
4728 #if IS_ENABLED(CONFIG_IPV6)
4729 static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4730                                u32 flags, bool check_mtu)
4731 {
4732         struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
4733         struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
4734         struct fib6_result res = {};
4735         struct neighbour *neigh;
4736         struct net_device *dev;
4737         struct inet6_dev *idev;
4738         struct flowi6 fl6;
4739         int strict = 0;
4740         int oif, err;
4741         u32 mtu;
4742 
4743         /* link local addresses are never forwarded */
4744         if (rt6_need_strict(dst) || rt6_need_strict(src))
4745                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4746 
4747         dev = dev_get_by_index_rcu(net, params->ifindex);
4748         if (unlikely(!dev))
4749                 return -ENODEV;
4750 
4751         idev = __in6_dev_get_safely(dev);
4752         if (unlikely(!idev || !idev->cnf.forwarding))
4753                 return BPF_FIB_LKUP_RET_FWD_DISABLED;
4754 
4755         if (flags & BPF_FIB_LOOKUP_OUTPUT) {
4756                 fl6.flowi6_iif = 1;
4757                 oif = fl6.flowi6_oif = params->ifindex;
4758         } else {
4759                 oif = fl6.flowi6_iif = params->ifindex;
4760                 fl6.flowi6_oif = 0;
4761                 strict = RT6_LOOKUP_F_HAS_SADDR;
4762         }
4763         fl6.flowlabel = params->flowinfo;
4764         fl6.flowi6_scope = 0;
4765         fl6.flowi6_flags = 0;
4766         fl6.mp_hash = 0;
4767 
4768         fl6.flowi6_proto = params->l4_protocol;
4769         fl6.daddr = *dst;
4770         fl6.saddr = *src;
4771         fl6.fl6_sport = params->sport;
4772         fl6.fl6_dport = params->dport;
4773 
4774         if (flags & BPF_FIB_LOOKUP_DIRECT) {
4775                 u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
4776                 struct fib6_table *tb;
4777 
4778                 tb = ipv6_stub->fib6_get_table(net, tbid);
4779                 if (unlikely(!tb))
4780                         return BPF_FIB_LKUP_RET_NOT_FWDED;
4781 
4782                 err = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, &res,
4783                                                    strict);
4784         } else {
4785                 fl6.flowi6_mark = 0;
4786                 fl6.flowi6_secid = 0;
4787                 fl6.flowi6_tun_key.tun_id = 0;
4788                 fl6.flowi6_uid = sock_net_uid(net, NULL);
4789 
4790                 err = ipv6_stub->fib6_lookup(net, oif, &fl6, &res, strict);
4791         }
4792 
4793         if (unlikely(err || IS_ERR_OR_NULL(res.f6i) ||
4794                      res.f6i == net->ipv6.fib6_null_entry))
4795                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4796 
4797         switch (res.fib6_type) {
4798         /* only unicast is forwarded */
4799         case RTN_UNICAST:
4800                 break;
4801         case RTN_BLACKHOLE:
4802                 return BPF_FIB_LKUP_RET_BLACKHOLE;
4803         case RTN_UNREACHABLE:
4804                 return BPF_FIB_LKUP_RET_UNREACHABLE;
4805         case RTN_PROHIBIT:
4806                 return BPF_FIB_LKUP_RET_PROHIBIT;
4807         default:
4808                 return BPF_FIB_LKUP_RET_NOT_FWDED;
4809         }
4810 
4811         ipv6_stub->fib6_select_path(net, &res, &fl6, fl6.flowi6_oif,
4812                                     fl6.flowi6_oif != 0, NULL, strict);
4813 
4814         if (check_mtu) {
4815                 mtu = ipv6_stub->ip6_mtu_from_fib6(&res, dst, src);
4816                 if (params->tot_len > mtu)
4817                         return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4818         }
4819 
4820         if (res.nh->fib_nh_lws)
4821                 return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4822 
4823         if (res.nh->fib_nh_gw_family)
4824                 *dst = res.nh->fib_nh_gw6;
4825 
4826         dev = res.nh->fib_nh_dev;
4827         params->rt_metric = res.f6i->fib6_metric;
4828 
4829         /* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
4830          * not needed here.
4831          */
4832         neigh = __ipv6_neigh_lookup_noref_stub(dev, dst);
4833         if (!neigh)
4834                 return BPF_FIB_LKUP_RET_NO_NEIGH;
4835 
4836         return bpf_fib_set_fwd_params(params, neigh, dev);
4837 }
4838 #endif
4839 
4840 BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
4841            struct bpf_fib_lookup *, params, int, plen, u32, flags)
4842 {
4843         if (plen < sizeof(*params))
4844                 return -EINVAL;
4845 
4846         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4847                 return -EINVAL;
4848 
4849         switch (params->family) {
4850 #if IS_ENABLED(CONFIG_INET)
4851         case AF_INET:
4852                 return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4853                                            flags, true);
4854 #endif
4855 #if IS_ENABLED(CONFIG_IPV6)
4856         case AF_INET6:
4857                 return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4858                                            flags, true);
4859 #endif
4860         }
4861         return -EAFNOSUPPORT;
4862 }
4863 
4864 static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
4865         .func           = bpf_xdp_fib_lookup,
4866         .gpl_only       = true,
4867         .ret_type       = RET_INTEGER,
4868         .arg1_type      = ARG_PTR_TO_CTX,
4869         .arg2_type      = ARG_PTR_TO_MEM,
4870         .arg3_type      = ARG_CONST_SIZE,
4871         .arg4_type      = ARG_ANYTHING,
4872 };
4873 
4874 BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
4875            struct bpf_fib_lookup *, params, int, plen, u32, flags)
4876 {
4877         struct net *net = dev_net(skb->dev);
4878         int rc = -EAFNOSUPPORT;
4879 
4880         if (plen < sizeof(*params))
4881                 return -EINVAL;
4882 
4883         if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
4884                 return -EINVAL;
4885 
4886         switch (params->family) {
4887 #if IS_ENABLED(CONFIG_INET)
4888         case AF_INET:
4889                 rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4890                 break;
4891 #endif
4892 #if IS_ENABLED(CONFIG_IPV6)
4893         case AF_INET6:
4894                 rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4895                 break;
4896 #endif
4897         }
4898 
4899         if (!rc) {
4900                 struct net_device *dev;
4901 
4902                 dev = dev_get_by_index_rcu(net, params->ifindex);
4903                 if (!is_skb_forwardable(dev, skb))
4904                         rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4905         }
4906 
4907         return rc;
4908 }
4909 
4910 static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
4911         .func           = bpf_skb_fib_lookup,
4912         .gpl_only       = true,
4913         .ret_type       = RET_INTEGER,
4914         .arg1_type      = ARG_PTR_TO_CTX,
4915         .arg2_type      = ARG_PTR_TO_MEM,
4916         .arg3_type      = ARG_CONST_SIZE,
4917         .arg4_type      = ARG_ANYTHING,
4918 };
4919 
4920 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4921 static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
4922 {
4923         int err;
4924         struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;
4925 
4926         if (!seg6_validate_srh(srh, len))
4927                 return -EINVAL;
4928 
4929         switch (type) {
4930         case BPF_LWT_ENCAP_SEG6_INLINE:
4931                 if (skb->protocol != htons(ETH_P_IPV6))
4932                         return -EBADMSG;
4933 
4934                 err = seg6_do_srh_inline(skb, srh);
4935                 break;
4936         case BPF_LWT_ENCAP_SEG6:
4937                 skb_reset_inner_headers(skb);
4938                 skb->encapsulation = 1;
4939                 err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
4940                 break;
4941         default:
4942                 return -EINVAL;
4943         }
4944 
4945         bpf_compute_data_pointers(skb);
4946         if (err)
4947                 return err;
4948 
4949         ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
4950         skb_set_transport_header(skb, sizeof(struct ipv6hdr));
4951 
4952         return seg6_lookup_nexthop(skb, NULL, 0);
4953 }
4954 #endif /* CONFIG_IPV6_SEG6_BPF */
4955 
4956 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4957 static int bpf_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len,
4958                              bool ingress)
4959 {
4960         return bpf_lwt_push_ip_encap(skb, hdr, len, ingress);
4961 }
4962 #endif
4963 
4964 BPF_CALL_4(bpf_lwt_in_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
4965            u32, len)
4966 {
4967         switch (type) {
4968 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4969         case BPF_LWT_ENCAP_SEG6:
4970         case BPF_LWT_ENCAP_SEG6_INLINE:
4971                 return bpf_push_seg6_encap(skb, type, hdr, len);
4972 #endif
4973 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4974         case BPF_LWT_ENCAP_IP:
4975                 return bpf_push_ip_encap(skb, hdr, len, true /* ingress */);
4976 #endif
4977         default:
4978                 return -EINVAL;
4979         }
4980 }
4981 
4982 BPF_CALL_4(bpf_lwt_xmit_push_encap, struct sk_buff *, skb, u32, type,
4983            void *, hdr, u32, len)
4984 {
4985         switch (type) {
4986 #if IS_ENABLED(CONFIG_LWTUNNEL_BPF)
4987         case BPF_LWT_ENCAP_IP:
4988                 return bpf_push_ip_encap(skb, hdr, len, false /* egress */);
4989 #endif
4990         default:
4991                 return -EINVAL;
4992         }
4993 }
4994 
4995 static const struct bpf_func_proto bpf_lwt_in_push_encap_proto = {
4996         .func           = bpf_lwt_in_push_encap,
4997         .gpl_only       = false,
4998         .ret_type       = RET_INTEGER,
4999         .arg1_type      = ARG_PTR_TO_CTX,
5000         .arg2_type      = ARG_ANYTHING,
5001         .arg3_type      = ARG_PTR_TO_MEM,
5002         .arg4_type      = ARG_CONST_SIZE
5003 };
5004 
5005 static const struct bpf_func_proto bpf_lwt_xmit_push_encap_proto = {
5006         .func           = bpf_lwt_xmit_push_encap,
5007         .gpl_only       = false,
5008         .ret_type       = RET_INTEGER,
5009         .arg1_type      = ARG_PTR_TO_CTX,
5010         .arg2_type      = ARG_ANYTHING,
5011         .arg3_type      = ARG_PTR_TO_MEM,
5012         .arg4_type      = ARG_CONST_SIZE
5013 };
5014 
5015 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5016 BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
5017            const void *, from, u32, len)
5018 {
5019         struct seg6_bpf_srh_state *srh_state =
5020                 this_cpu_ptr(&seg6_bpf_srh_states);
5021         struct ipv6_sr_hdr *srh = srh_state->srh;
5022         void *srh_tlvs, *srh_end, *ptr;
5023         int srhoff = 0;
5024 
5025         if (srh == NULL)
5026                 return -EINVAL;
5027 
5028         srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
5029         srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
5030 
5031         ptr = skb->data + offset;
5032         if (ptr >= srh_tlvs && ptr + len <= srh_end)
5033                 srh_state->valid = false;
5034         else if (ptr < (void *)&srh->flags ||
5035                  ptr + len > (void *)&srh->segments)
5036                 return -EFAULT;
5037 
5038         if (unlikely(bpf_try_make_writable(skb, offset + len)))
5039                 return -EFAULT;
5040         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5041                 return -EINVAL;
5042         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5043 
5044         memcpy(skb->data + offset, from, len);
5045         return 0;
5046 }
5047 
5048 static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
5049         .func           = bpf_lwt_seg6_store_bytes,
5050         .gpl_only       = false,
5051         .ret_type       = RET_INTEGER,
5052         .arg1_type      = ARG_PTR_TO_CTX,
5053         .arg2_type      = ARG_ANYTHING,
5054         .arg3_type      = ARG_PTR_TO_MEM,
5055         .arg4_type      = ARG_CONST_SIZE
5056 };
5057 
5058 static void bpf_update_srh_state(struct sk_buff *skb)
5059 {
5060         struct seg6_bpf_srh_state *srh_state =
5061                 this_cpu_ptr(&seg6_bpf_srh_states);
5062         int srhoff = 0;
5063 
5064         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
5065                 srh_state->srh = NULL;
5066         } else {
5067                 srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5068                 srh_state->hdrlen = srh_state->srh->hdrlen << 3;
5069                 srh_state->valid = true;
5070         }
5071 }
5072 
5073 BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
5074            u32, action, void *, param, u32, param_len)
5075 {
5076         struct seg6_bpf_srh_state *srh_state =
5077                 this_cpu_ptr(&seg6_bpf_srh_states);
5078         int hdroff = 0;
5079         int err;
5080 
5081         switch (action) {
5082         case SEG6_LOCAL_ACTION_END_X:
5083                 if (!seg6_bpf_has_valid_srh(skb))
5084                         return -EBADMSG;
5085                 if (param_len != sizeof(struct in6_addr))
5086                         return -EINVAL;
5087                 return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
5088         case SEG6_LOCAL_ACTION_END_T:
5089                 if (!seg6_bpf_has_valid_srh(skb))
5090                         return -EBADMSG;
5091                 if (param_len != sizeof(int))
5092                         return -EINVAL;
5093                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5094         case SEG6_LOCAL_ACTION_END_DT6:
5095                 if (!seg6_bpf_has_valid_srh(skb))
5096                         return -EBADMSG;
5097                 if (param_len != sizeof(int))
5098                         return -EINVAL;
5099 
5100                 if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
5101                         return -EBADMSG;
5102                 if (!pskb_pull(skb, hdroff))
5103                         return -EBADMSG;
5104 
5105                 skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
5106                 skb_reset_network_header(skb);
5107                 skb_reset_transport_header(skb);
5108                 skb->encapsulation = 0;
5109 
5110                 bpf_compute_data_pointers(skb);
5111                 bpf_update_srh_state(skb);
5112                 return seg6_lookup_nexthop(skb, NULL, *(int *)param);
5113         case SEG6_LOCAL_ACTION_END_B6:
5114                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5115                         return -EBADMSG;
5116                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
5117                                           param, param_len);
5118                 if (!err)
5119                         bpf_update_srh_state(skb);
5120 
5121                 return err;
5122         case SEG6_LOCAL_ACTION_END_B6_ENCAP:
5123                 if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
5124                         return -EBADMSG;
5125                 err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
5126                                           param, param_len);
5127                 if (!err)
5128                         bpf_update_srh_state(skb);
5129 
5130                 return err;
5131         default:
5132                 return -EINVAL;
5133         }
5134 }
5135 
5136 static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
5137         .func           = bpf_lwt_seg6_action,
5138         .gpl_only       = false,
5139         .ret_type       = RET_INTEGER,
5140         .arg1_type      = ARG_PTR_TO_CTX,
5141         .arg2_type      = ARG_ANYTHING,
5142         .arg3_type      = ARG_PTR_TO_MEM,
5143         .arg4_type      = ARG_CONST_SIZE
5144 };
5145 
5146 BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
5147            s32, len)
5148 {
5149         struct seg6_bpf_srh_state *srh_state =
5150                 this_cpu_ptr(&seg6_bpf_srh_states);
5151         struct ipv6_sr_hdr *srh = srh_state->srh;
5152         void *srh_end, *srh_tlvs, *ptr;
5153         struct ipv6hdr *hdr;
5154         int srhoff = 0;
5155         int ret;
5156 
5157         if (unlikely(srh == NULL))
5158                 return -EINVAL;
5159 
5160         srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
5161                         ((srh->first_segment + 1) << 4));
5162         srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
5163                         srh_state->hdrlen);
5164         ptr = skb->data + offset;
5165 
5166         if (unlikely(ptr < srh_tlvs || ptr > srh_end))
5167                 return -EFAULT;
5168         if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
5169                 return -EFAULT;
5170 
5171         if (len > 0) {
5172                 ret = skb_cow_head(skb, len);
5173                 if (unlikely(ret < 0))
5174                         return ret;
5175 
5176                 ret = bpf_skb_net_hdr_push(skb, offset, len);
5177         } else {
5178                 ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
5179         }
5180 
5181         bpf_compute_data_pointers(skb);
5182         if (unlikely(ret < 0))
5183                 return ret;
5184 
5185         hdr = (struct ipv6hdr *)skb->data;
5186         hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
5187 
5188         if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
5189                 return -EINVAL;
5190         srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
5191         srh_state->hdrlen += len;
5192         srh_state->valid = false;
5193         return 0;
5194 }
5195 
5196 static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
5197         .func           = bpf_lwt_seg6_adjust_srh,
5198         .gpl_only       = false,
5199         .ret_type       = RET_INTEGER,
5200         .arg1_type      = ARG_PTR_TO_CTX,
5201         .arg2_type      = ARG_ANYTHING,
5202         .arg3_type      = ARG_ANYTHING,
5203 };
5204 #endif /* CONFIG_IPV6_SEG6_BPF */
5205 
5206 #ifdef CONFIG_INET
5207 static struct sock *sk_lookup(struct net *net, struct bpf_sock_tuple *tuple,
5208                               int dif, int sdif, u8 family, u8 proto)
5209 {
5210         bool refcounted = false;
5211         struct sock *sk = NULL;
5212 
5213         if (family == AF_INET) {
5214                 __be32 src4 = tuple->ipv4.saddr;
5215                 __be32 dst4 = tuple->ipv4.daddr;
5216 
5217                 if (proto == IPPROTO_TCP)
5218                         sk = __inet_lookup(net, &tcp_hashinfo, NULL, 0,
5219                                            src4, tuple->ipv4.sport,
5220                                            dst4, tuple->ipv4.dport,
5221                                            dif, sdif, &refcounted);
5222                 else
5223                         sk = __udp4_lib_lookup(net, src4, tuple->ipv4.sport,
5224                                                dst4, tuple->ipv4.dport,
5225                                                dif, sdif, &udp_table, NULL);
5226 #if IS_ENABLED(CONFIG_IPV6)
5227         } else {
5228                 struct in6_addr *src6 = (struct in6_addr *)&tuple->ipv6.saddr;
5229                 struct in6_addr *dst6 = (struct in6_addr *)&tuple->ipv6.daddr;
5230 
5231                 if (proto == IPPROTO_TCP)
5232                         sk = __inet6_lookup(net, &tcp_hashinfo, NULL, 0,
5233                                             src6, tuple->ipv6.sport,
5234                                             dst6, ntohs(tuple->ipv6.dport),
5235                                             dif, sdif, &refcounted);
5236                 else if (likely(ipv6_bpf_stub))
5237                         sk = ipv6_bpf_stub->udp6_lib_lookup(net,
5238                                                             src6, tuple->ipv6.sport,
5239                                                             dst6, tuple->ipv6.dport,
5240                                                             dif, sdif,
5241                                                             &udp_table, NULL);
5242 #endif
5243         }
5244 
5245         if (unlikely(sk && !refcounted && !sock_flag(sk, SOCK_RCU_FREE))) {
5246                 WARN_ONCE(1, "Found non-RCU, unreferenced socket!");
5247                 sk = NULL;
5248         }
5249         return sk;
5250 }
5251 
5252 /* bpf_skc_lookup performs the core lookup for different types of sockets,
5253  * taking a reference on the socket if it doesn't have the flag SOCK_RCU_FREE.
5254  * Returns the socket as an 'unsigned long' to simplify the casting in the
5255  * callers to satisfy BPF_CALL declarations.
5256  */
5257 static struct sock *
5258 __bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5259                  struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5260                  u64 flags)
5261 {
5262         struct sock *sk = NULL;
5263         u8 family = AF_UNSPEC;
5264         struct net *net;
5265         int sdif;
5266 
5267         if (len == sizeof(tuple->ipv4))
5268                 family = AF_INET;
5269         else if (len == sizeof(tuple->ipv6))
5270                 family = AF_INET6;
5271         else
5272                 return NULL;
5273 
5274         if (unlikely(family == AF_UNSPEC || flags ||
5275                      !((s32)netns_id < 0 || netns_id <= S32_MAX)))
5276                 goto out;
5277 
5278         if (family == AF_INET)
5279                 sdif = inet_sdif(skb);
5280         else
5281                 sdif = inet6_sdif(skb);
5282 
5283         if ((s32)netns_id < 0) {
5284                 net = caller_net;
5285                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5286         } else {
5287                 net = get_net_ns_by_id(caller_net, netns_id);
5288                 if (unlikely(!net))
5289                         goto out;
5290                 sk = sk_lookup(net, tuple, ifindex, sdif, family, proto);
5291                 put_net(net);
5292         }
5293 
5294 out:
5295         return sk;
5296 }
5297 
5298 static struct sock *
5299 __bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5300                 struct net *caller_net, u32 ifindex, u8 proto, u64 netns_id,
5301                 u64 flags)
5302 {
5303         struct sock *sk = __bpf_skc_lookup(skb, tuple, len, caller_net,
5304                                            ifindex, proto, netns_id, flags);
5305 
5306         if (sk) {
5307                 sk = sk_to_full_sk(sk);
5308                 if (!sk_fullsock(sk)) {
5309                         sock_gen_put(sk);
5310                         return NULL;
5311                 }
5312         }
5313 
5314         return sk;
5315 }
5316 
5317 static struct sock *
5318 bpf_skc_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5319                u8 proto, u64 netns_id, u64 flags)
5320 {
5321         struct net *caller_net;
5322         int ifindex;
5323 
5324         if (skb->dev) {
5325                 caller_net = dev_net(skb->dev);
5326                 ifindex = skb->dev->ifindex;
5327         } else {
5328                 caller_net = sock_net(skb->sk);
5329                 ifindex = 0;
5330         }
5331 
5332         return __bpf_skc_lookup(skb, tuple, len, caller_net, ifindex, proto,
5333                                 netns_id, flags);
5334 }
5335 
5336 static struct sock *
5337 bpf_sk_lookup(struct sk_buff *skb, struct bpf_sock_tuple *tuple, u32 len,
5338               u8 proto, u64 netns_id, u64 flags)
5339 {
5340         struct sock *sk = bpf_skc_lookup(skb, tuple, len, proto, netns_id,
5341                                          flags);
5342 
5343         if (sk) {
5344                 sk = sk_to_full_sk(sk);
5345                 if (!sk_fullsock(sk)) {
5346                         sock_gen_put(sk);
5347                         return NULL;
5348                 }
5349         }
5350 
5351         return sk;
5352 }
5353 
5354 BPF_CALL_5(bpf_skc_lookup_tcp, struct sk_buff *, skb,
5355            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5356 {
5357         return (unsigned long)bpf_skc_lookup(skb, tuple, len, IPPROTO_TCP,
5358                                              netns_id, flags);
5359 }
5360 
5361 static const struct bpf_func_proto bpf_skc_lookup_tcp_proto = {
5362         .func           = bpf_skc_lookup_tcp,
5363         .gpl_only       = false,
5364         .pkt_access     = true,
5365         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5366         .arg1_type      = ARG_PTR_TO_CTX,
5367         .arg2_type      = ARG_PTR_TO_MEM,
5368         .arg3_type      = ARG_CONST_SIZE,
5369         .arg4_type      = ARG_ANYTHING,
5370         .arg5_type      = ARG_ANYTHING,
5371 };
5372 
5373 BPF_CALL_5(bpf_sk_lookup_tcp, struct sk_buff *, skb,
5374            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5375 {
5376         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_TCP,
5377                                             netns_id, flags);
5378 }
5379 
5380 static const struct bpf_func_proto bpf_sk_lookup_tcp_proto = {
5381         .func           = bpf_sk_lookup_tcp,
5382         .gpl_only       = false,
5383         .pkt_access     = true,
5384         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5385         .arg1_type      = ARG_PTR_TO_CTX,
5386         .arg2_type      = ARG_PTR_TO_MEM,
5387         .arg3_type      = ARG_CONST_SIZE,
5388         .arg4_type      = ARG_ANYTHING,
5389         .arg5_type      = ARG_ANYTHING,
5390 };
5391 
5392 BPF_CALL_5(bpf_sk_lookup_udp, struct sk_buff *, skb,
5393            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5394 {
5395         return (unsigned long)bpf_sk_lookup(skb, tuple, len, IPPROTO_UDP,
5396                                             netns_id, flags);
5397 }
5398 
5399 static const struct bpf_func_proto bpf_sk_lookup_udp_proto = {
5400         .func           = bpf_sk_lookup_udp,
5401         .gpl_only       = false,
5402         .pkt_access     = true,
5403         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5404         .arg1_type      = ARG_PTR_TO_CTX,
5405         .arg2_type      = ARG_PTR_TO_MEM,
5406         .arg3_type      = ARG_CONST_SIZE,
5407         .arg4_type      = ARG_ANYTHING,
5408         .arg5_type      = ARG_ANYTHING,
5409 };
5410 
5411 BPF_CALL_1(bpf_sk_release, struct sock *, sk)
5412 {
5413         /* Only full sockets have sk->sk_flags. */
5414         if (!sk_fullsock(sk) || !sock_flag(sk, SOCK_RCU_FREE))
5415                 sock_gen_put(sk);
5416         return 0;
5417 }
5418 
5419 static const struct bpf_func_proto bpf_sk_release_proto = {
5420         .func           = bpf_sk_release,
5421         .gpl_only       = false,
5422         .ret_type       = RET_INTEGER,
5423         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5424 };
5425 
5426 BPF_CALL_5(bpf_xdp_sk_lookup_udp, struct xdp_buff *, ctx,
5427            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5428 {
5429         struct net *caller_net = dev_net(ctx->rxq->dev);
5430         int ifindex = ctx->rxq->dev->ifindex;
5431 
5432         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5433                                               ifindex, IPPROTO_UDP, netns_id,
5434                                               flags);
5435 }
5436 
5437 static const struct bpf_func_proto bpf_xdp_sk_lookup_udp_proto = {
5438         .func           = bpf_xdp_sk_lookup_udp,
5439         .gpl_only       = false,
5440         .pkt_access     = true,
5441         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5442         .arg1_type      = ARG_PTR_TO_CTX,
5443         .arg2_type      = ARG_PTR_TO_MEM,
5444         .arg3_type      = ARG_CONST_SIZE,
5445         .arg4_type      = ARG_ANYTHING,
5446         .arg5_type      = ARG_ANYTHING,
5447 };
5448 
5449 BPF_CALL_5(bpf_xdp_skc_lookup_tcp, struct xdp_buff *, ctx,
5450            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5451 {
5452         struct net *caller_net = dev_net(ctx->rxq->dev);
5453         int ifindex = ctx->rxq->dev->ifindex;
5454 
5455         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len, caller_net,
5456                                                ifindex, IPPROTO_TCP, netns_id,
5457                                                flags);
5458 }
5459 
5460 static const struct bpf_func_proto bpf_xdp_skc_lookup_tcp_proto = {
5461         .func           = bpf_xdp_skc_lookup_tcp,
5462         .gpl_only       = false,
5463         .pkt_access     = true,
5464         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5465         .arg1_type      = ARG_PTR_TO_CTX,
5466         .arg2_type      = ARG_PTR_TO_MEM,
5467         .arg3_type      = ARG_CONST_SIZE,
5468         .arg4_type      = ARG_ANYTHING,
5469         .arg5_type      = ARG_ANYTHING,
5470 };
5471 
5472 BPF_CALL_5(bpf_xdp_sk_lookup_tcp, struct xdp_buff *, ctx,
5473            struct bpf_sock_tuple *, tuple, u32, len, u32, netns_id, u64, flags)
5474 {
5475         struct net *caller_net = dev_net(ctx->rxq->dev);
5476         int ifindex = ctx->rxq->dev->ifindex;
5477 
5478         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len, caller_net,
5479                                               ifindex, IPPROTO_TCP, netns_id,
5480                                               flags);
5481 }
5482 
5483 static const struct bpf_func_proto bpf_xdp_sk_lookup_tcp_proto = {
5484         .func           = bpf_xdp_sk_lookup_tcp,
5485         .gpl_only       = false,
5486         .pkt_access     = true,
5487         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5488         .arg1_type      = ARG_PTR_TO_CTX,
5489         .arg2_type      = ARG_PTR_TO_MEM,
5490         .arg3_type      = ARG_CONST_SIZE,
5491         .arg4_type      = ARG_ANYTHING,
5492         .arg5_type      = ARG_ANYTHING,
5493 };
5494 
5495 BPF_CALL_5(bpf_sock_addr_skc_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5496            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5497 {
5498         return (unsigned long)__bpf_skc_lookup(NULL, tuple, len,
5499                                                sock_net(ctx->sk), 0,
5500                                                IPPROTO_TCP, netns_id, flags);
5501 }
5502 
5503 static const struct bpf_func_proto bpf_sock_addr_skc_lookup_tcp_proto = {
5504         .func           = bpf_sock_addr_skc_lookup_tcp,
5505         .gpl_only       = false,
5506         .ret_type       = RET_PTR_TO_SOCK_COMMON_OR_NULL,
5507         .arg1_type      = ARG_PTR_TO_CTX,
5508         .arg2_type      = ARG_PTR_TO_MEM,
5509         .arg3_type      = ARG_CONST_SIZE,
5510         .arg4_type      = ARG_ANYTHING,
5511         .arg5_type      = ARG_ANYTHING,
5512 };
5513 
5514 BPF_CALL_5(bpf_sock_addr_sk_lookup_tcp, struct bpf_sock_addr_kern *, ctx,
5515            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5516 {
5517         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5518                                               sock_net(ctx->sk), 0, IPPROTO_TCP,
5519                                               netns_id, flags);
5520 }
5521 
5522 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_tcp_proto = {
5523         .func           = bpf_sock_addr_sk_lookup_tcp,
5524         .gpl_only       = false,
5525         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5526         .arg1_type      = ARG_PTR_TO_CTX,
5527         .arg2_type      = ARG_PTR_TO_MEM,
5528         .arg3_type      = ARG_CONST_SIZE,
5529         .arg4_type      = ARG_ANYTHING,
5530         .arg5_type      = ARG_ANYTHING,
5531 };
5532 
5533 BPF_CALL_5(bpf_sock_addr_sk_lookup_udp, struct bpf_sock_addr_kern *, ctx,
5534            struct bpf_sock_tuple *, tuple, u32, len, u64, netns_id, u64, flags)
5535 {
5536         return (unsigned long)__bpf_sk_lookup(NULL, tuple, len,
5537                                               sock_net(ctx->sk), 0, IPPROTO_UDP,
5538                                               netns_id, flags);
5539 }
5540 
5541 static const struct bpf_func_proto bpf_sock_addr_sk_lookup_udp_proto = {
5542         .func           = bpf_sock_addr_sk_lookup_udp,
5543         .gpl_only       = false,
5544         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5545         .arg1_type      = ARG_PTR_TO_CTX,
5546         .arg2_type      = ARG_PTR_TO_MEM,
5547         .arg3_type      = ARG_CONST_SIZE,
5548         .arg4_type      = ARG_ANYTHING,
5549         .arg5_type      = ARG_ANYTHING,
5550 };
5551 
5552 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5553                                   struct bpf_insn_access_aux *info)
5554 {
5555         if (off < 0 || off >= offsetofend(struct bpf_tcp_sock,
5556                                           icsk_retransmits))
5557                 return false;
5558 
5559         if (off % size != 0)
5560                 return false;
5561 
5562         switch (off) {
5563         case offsetof(struct bpf_tcp_sock, bytes_received):
5564         case offsetof(struct bpf_tcp_sock, bytes_acked):
5565                 return size == sizeof(__u64);
5566         default:
5567                 return size == sizeof(__u32);
5568         }
5569 }
5570 
5571 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
5572                                     const struct bpf_insn *si,
5573                                     struct bpf_insn *insn_buf,
5574                                     struct bpf_prog *prog, u32 *target_size)
5575 {
5576         struct bpf_insn *insn = insn_buf;
5577 
5578 #define BPF_TCP_SOCK_GET_COMMON(FIELD)                                  \
5579         do {                                                            \
5580                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, FIELD) >     \
5581                              FIELD_SIZEOF(struct bpf_tcp_sock, FIELD)); \
5582                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct tcp_sock, FIELD),\
5583                                       si->dst_reg, si->src_reg,         \
5584                                       offsetof(struct tcp_sock, FIELD)); \
5585         } while (0)
5586 
5587 #define BPF_INET_SOCK_GET_COMMON(FIELD)                                 \
5588         do {                                                            \
5589                 BUILD_BUG_ON(FIELD_SIZEOF(struct inet_connection_sock,  \
5590                                           FIELD) >                      \
5591                              FIELD_SIZEOF(struct bpf_tcp_sock, FIELD)); \
5592                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                 \
5593                                         struct inet_connection_sock,    \
5594                                         FIELD),                         \
5595                                       si->dst_reg, si->src_reg,         \
5596                                       offsetof(                         \
5597                                         struct inet_connection_sock,    \
5598                                         FIELD));                        \
5599         } while (0)
5600 
5601         if (insn > insn_buf)
5602                 return insn - insn_buf;
5603 
5604         switch (si->off) {
5605         case offsetof(struct bpf_tcp_sock, rtt_min):
5606                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
5607                              sizeof(struct minmax));
5608                 BUILD_BUG_ON(sizeof(struct minmax) <
5609                              sizeof(struct minmax_sample));
5610 
5611                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5612                                       offsetof(struct tcp_sock, rtt_min) +
5613                                       offsetof(struct minmax_sample, v));
5614                 break;
5615         case offsetof(struct bpf_tcp_sock, snd_cwnd):
5616                 BPF_TCP_SOCK_GET_COMMON(snd_cwnd);
5617                 break;
5618         case offsetof(struct bpf_tcp_sock, srtt_us):
5619                 BPF_TCP_SOCK_GET_COMMON(srtt_us);
5620                 break;
5621         case offsetof(struct bpf_tcp_sock, snd_ssthresh):
5622                 BPF_TCP_SOCK_GET_COMMON(snd_ssthresh);
5623                 break;
5624         case offsetof(struct bpf_tcp_sock, rcv_nxt):
5625                 BPF_TCP_SOCK_GET_COMMON(rcv_nxt);
5626                 break;
5627         case offsetof(struct bpf_tcp_sock, snd_nxt):
5628                 BPF_TCP_SOCK_GET_COMMON(snd_nxt);
5629                 break;
5630         case offsetof(struct bpf_tcp_sock, snd_una):
5631                 BPF_TCP_SOCK_GET_COMMON(snd_una);
5632                 break;
5633         case offsetof(struct bpf_tcp_sock, mss_cache):
5634                 BPF_TCP_SOCK_GET_COMMON(mss_cache);
5635                 break;
5636         case offsetof(struct bpf_tcp_sock, ecn_flags):
5637                 BPF_TCP_SOCK_GET_COMMON(ecn_flags);
5638                 break;
5639         case offsetof(struct bpf_tcp_sock, rate_delivered):
5640                 BPF_TCP_SOCK_GET_COMMON(rate_delivered);
5641                 break;
5642         case offsetof(struct bpf_tcp_sock, rate_interval_us):
5643                 BPF_TCP_SOCK_GET_COMMON(rate_interval_us);
5644                 break;
5645         case offsetof(struct bpf_tcp_sock, packets_out):
5646                 BPF_TCP_SOCK_GET_COMMON(packets_out);
5647                 break;
5648         case offsetof(struct bpf_tcp_sock, retrans_out):
5649                 BPF_TCP_SOCK_GET_COMMON(retrans_out);
5650                 break;
5651         case offsetof(struct bpf_tcp_sock, total_retrans):
5652                 BPF_TCP_SOCK_GET_COMMON(total_retrans);
5653                 break;
5654         case offsetof(struct bpf_tcp_sock, segs_in):
5655                 BPF_TCP_SOCK_GET_COMMON(segs_in);
5656                 break;
5657         case offsetof(struct bpf_tcp_sock, data_segs_in):
5658                 BPF_TCP_SOCK_GET_COMMON(data_segs_in);
5659                 break;
5660         case offsetof(struct bpf_tcp_sock, segs_out):
5661                 BPF_TCP_SOCK_GET_COMMON(segs_out);
5662                 break;
5663         case offsetof(struct bpf_tcp_sock, data_segs_out):
5664                 BPF_TCP_SOCK_GET_COMMON(data_segs_out);
5665                 break;
5666         case offsetof(struct bpf_tcp_sock, lost_out):
5667                 BPF_TCP_SOCK_GET_COMMON(lost_out);
5668                 break;
5669         case offsetof(struct bpf_tcp_sock, sacked_out):
5670                 BPF_TCP_SOCK_GET_COMMON(sacked_out);
5671                 break;
5672         case offsetof(struct bpf_tcp_sock, bytes_received):
5673                 BPF_TCP_SOCK_GET_COMMON(bytes_received);
5674                 break;
5675         case offsetof(struct bpf_tcp_sock, bytes_acked):
5676                 BPF_TCP_SOCK_GET_COMMON(bytes_acked);
5677                 break;
5678         case offsetof(struct bpf_tcp_sock, dsack_dups):
5679                 BPF_TCP_SOCK_GET_COMMON(dsack_dups);
5680                 break;
5681         case offsetof(struct bpf_tcp_sock, delivered):
5682                 BPF_TCP_SOCK_GET_COMMON(delivered);
5683                 break;
5684         case offsetof(struct bpf_tcp_sock, delivered_ce):
5685                 BPF_TCP_SOCK_GET_COMMON(delivered_ce);
5686                 break;
5687         case offsetof(struct bpf_tcp_sock, icsk_retransmits):
5688                 BPF_INET_SOCK_GET_COMMON(icsk_retransmits);
5689                 break;
5690         }
5691 
5692         return insn - insn_buf;
5693 }
5694 
5695 BPF_CALL_1(bpf_tcp_sock, struct sock *, sk)
5696 {
5697         if (sk_fullsock(sk) && sk->sk_protocol == IPPROTO_TCP)
5698                 return (unsigned long)sk;
5699 
5700         return (unsigned long)NULL;
5701 }
5702 
5703 const struct bpf_func_proto bpf_tcp_sock_proto = {
5704         .func           = bpf_tcp_sock,
5705         .gpl_only       = false,
5706         .ret_type       = RET_PTR_TO_TCP_SOCK_OR_NULL,
5707         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5708 };
5709 
5710 BPF_CALL_1(bpf_get_listener_sock, struct sock *, sk)
5711 {
5712         sk = sk_to_full_sk(sk);
5713 
5714         if (sk->sk_state == TCP_LISTEN && sock_flag(sk, SOCK_RCU_FREE))
5715                 return (unsigned long)sk;
5716 
5717         return (unsigned long)NULL;
5718 }
5719 
5720 static const struct bpf_func_proto bpf_get_listener_sock_proto = {
5721         .func           = bpf_get_listener_sock,
5722         .gpl_only       = false,
5723         .ret_type       = RET_PTR_TO_SOCKET_OR_NULL,
5724         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5725 };
5726 
5727 BPF_CALL_1(bpf_skb_ecn_set_ce, struct sk_buff *, skb)
5728 {
5729         unsigned int iphdr_len;
5730 
5731         if (skb->protocol == cpu_to_be16(ETH_P_IP))
5732                 iphdr_len = sizeof(struct iphdr);
5733         else if (skb->protocol == cpu_to_be16(ETH_P_IPV6))
5734                 iphdr_len = sizeof(struct ipv6hdr);
5735         else
5736                 return 0;
5737 
5738         if (skb_headlen(skb) < iphdr_len)
5739                 return 0;
5740 
5741         if (skb_cloned(skb) && !skb_clone_writable(skb, iphdr_len))
5742                 return 0;
5743 
5744         return INET_ECN_set_ce(skb);
5745 }
5746 
5747 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
5748                                   struct bpf_insn_access_aux *info)
5749 {
5750         if (off < 0 || off >= offsetofend(struct bpf_xdp_sock, queue_id))
5751                 return false;
5752 
5753         if (off % size != 0)
5754                 return false;
5755 
5756         switch (off) {
5757         default:
5758                 return size == sizeof(__u32);
5759         }
5760 }
5761 
5762 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
5763                                     const struct bpf_insn *si,
5764                                     struct bpf_insn *insn_buf,
5765                                     struct bpf_prog *prog, u32 *target_size)
5766 {
5767         struct bpf_insn *insn = insn_buf;
5768 
5769 #define BPF_XDP_SOCK_GET(FIELD)                                         \
5770         do {                                                            \
5771                 BUILD_BUG_ON(FIELD_SIZEOF(struct xdp_sock, FIELD) >     \
5772                              FIELD_SIZEOF(struct bpf_xdp_sock, FIELD)); \
5773                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_sock, FIELD),\
5774                                       si->dst_reg, si->src_reg,         \
5775                                       offsetof(struct xdp_sock, FIELD)); \
5776         } while (0)
5777 
5778         switch (si->off) {
5779         case offsetof(struct bpf_xdp_sock, queue_id):
5780                 BPF_XDP_SOCK_GET(queue_id);
5781                 break;
5782         }
5783 
5784         return insn - insn_buf;
5785 }
5786 
5787 static const struct bpf_func_proto bpf_skb_ecn_set_ce_proto = {
5788         .func           = bpf_skb_ecn_set_ce,
5789         .gpl_only       = false,
5790         .ret_type       = RET_INTEGER,
5791         .arg1_type      = ARG_PTR_TO_CTX,
5792 };
5793 
5794 BPF_CALL_5(bpf_tcp_check_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5795            struct tcphdr *, th, u32, th_len)
5796 {
5797 #ifdef CONFIG_SYN_COOKIES
5798         u32 cookie;
5799         int ret;
5800 
5801         if (unlikely(th_len < sizeof(*th)))
5802                 return -EINVAL;
5803 
5804         /* sk_listener() allows TCP_NEW_SYN_RECV, which makes no sense here. */
5805         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5806                 return -EINVAL;
5807 
5808         if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
5809                 return -EINVAL;
5810 
5811         if (!th->ack || th->rst || th->syn)
5812                 return -ENOENT;
5813 
5814         if (tcp_synq_no_recent_overflow(sk))
5815                 return -ENOENT;
5816 
5817         cookie = ntohl(th->ack_seq) - 1;
5818 
5819         switch (sk->sk_family) {
5820         case AF_INET:
5821                 if (unlikely(iph_len < sizeof(struct iphdr)))
5822                         return -EINVAL;
5823 
5824                 ret = __cookie_v4_check((struct iphdr *)iph, th, cookie);
5825                 break;
5826 
5827 #if IS_BUILTIN(CONFIG_IPV6)
5828         case AF_INET6:
5829                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5830                         return -EINVAL;
5831 
5832                 ret = __cookie_v6_check((struct ipv6hdr *)iph, th, cookie);
5833                 break;
5834 #endif /* CONFIG_IPV6 */
5835 
5836         default:
5837                 return -EPROTONOSUPPORT;
5838         }
5839 
5840         if (ret > 0)
5841                 return 0;
5842 
5843         return -ENOENT;
5844 #else
5845         return -ENOTSUPP;
5846 #endif
5847 }
5848 
5849 static const struct bpf_func_proto bpf_tcp_check_syncookie_proto = {
5850         .func           = bpf_tcp_check_syncookie,
5851         .gpl_only       = true,
5852         .pkt_access     = true,
5853         .ret_type       = RET_INTEGER,
5854         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5855         .arg2_type      = ARG_PTR_TO_MEM,
5856         .arg3_type      = ARG_CONST_SIZE,
5857         .arg4_type      = ARG_PTR_TO_MEM,
5858         .arg5_type      = ARG_CONST_SIZE,
5859 };
5860 
5861 BPF_CALL_5(bpf_tcp_gen_syncookie, struct sock *, sk, void *, iph, u32, iph_len,
5862            struct tcphdr *, th, u32, th_len)
5863 {
5864 #ifdef CONFIG_SYN_COOKIES
5865         u32 cookie;
5866         u16 mss;
5867 
5868         if (unlikely(th_len < sizeof(*th) || th_len != th->doff * 4))
5869                 return -EINVAL;
5870 
5871         if (sk->sk_protocol != IPPROTO_TCP || sk->sk_state != TCP_LISTEN)
5872                 return -EINVAL;
5873 
5874         if (!sock_net(sk)->ipv4.sysctl_tcp_syncookies)
5875                 return -ENOENT;
5876 
5877         if (!th->syn || th->ack || th->fin || th->rst)
5878                 return -EINVAL;
5879 
5880         if (unlikely(iph_len < sizeof(struct iphdr)))
5881                 return -EINVAL;
5882 
5883         /* Both struct iphdr and struct ipv6hdr have the version field at the
5884          * same offset so we can cast to the shorter header (struct iphdr).
5885          */
5886         switch (((struct iphdr *)iph)->version) {
5887         case 4:
5888                 if (sk->sk_family == AF_INET6 && sk->sk_ipv6only)
5889                         return -EINVAL;
5890 
5891                 mss = tcp_v4_get_syncookie(sk, iph, th, &cookie);
5892                 break;
5893 
5894 #if IS_BUILTIN(CONFIG_IPV6)
5895         case 6:
5896                 if (unlikely(iph_len < sizeof(struct ipv6hdr)))
5897                         return -EINVAL;
5898 
5899                 if (sk->sk_family != AF_INET6)
5900                         return -EINVAL;
5901 
5902                 mss = tcp_v6_get_syncookie(sk, iph, th, &cookie);
5903                 break;
5904 #endif /* CONFIG_IPV6 */
5905 
5906         default:
5907                 return -EPROTONOSUPPORT;
5908         }
5909         if (mss == 0)
5910                 return -ENOENT;
5911 
5912         return cookie | ((u64)mss << 32);
5913 #else
5914         return -EOPNOTSUPP;
5915 #endif /* CONFIG_SYN_COOKIES */
5916 }
5917 
5918 static const struct bpf_func_proto bpf_tcp_gen_syncookie_proto = {
5919         .func           = bpf_tcp_gen_syncookie,
5920         .gpl_only       = true, /* __cookie_v*_init_sequence() is GPL */
5921         .pkt_access     = true,
5922         .ret_type       = RET_INTEGER,
5923         .arg1_type      = ARG_PTR_TO_SOCK_COMMON,
5924         .arg2_type      = ARG_PTR_TO_MEM,
5925         .arg3_type      = ARG_CONST_SIZE,
5926         .arg4_type      = ARG_PTR_TO_MEM,
5927         .arg5_type      = ARG_CONST_SIZE,
5928 };
5929 
5930 #endif /* CONFIG_INET */
5931 
5932 bool bpf_helper_changes_pkt_data(void *func)
5933 {
5934         if (func == bpf_skb_vlan_push ||
5935             func == bpf_skb_vlan_pop ||
5936             func == bpf_skb_store_bytes ||
5937             func == bpf_skb_change_proto ||
5938             func == bpf_skb_change_head ||
5939             func == sk_skb_change_head ||
5940             func == bpf_skb_change_tail ||
5941             func == sk_skb_change_tail ||
5942             func == bpf_skb_adjust_room ||
5943             func == bpf_skb_pull_data ||
5944             func == sk_skb_pull_data ||
5945             func == bpf_clone_redirect ||
5946             func == bpf_l3_csum_replace ||
5947             func == bpf_l4_csum_replace ||
5948             func == bpf_xdp_adjust_head ||
5949             func == bpf_xdp_adjust_meta ||
5950             func == bpf_msg_pull_data ||
5951             func == bpf_msg_push_data ||
5952             func == bpf_msg_pop_data ||
5953             func == bpf_xdp_adjust_tail ||
5954 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5955             func == bpf_lwt_seg6_store_bytes ||
5956             func == bpf_lwt_seg6_adjust_srh ||
5957             func == bpf_lwt_seg6_action ||
5958 #endif
5959             func == bpf_lwt_in_push_encap ||
5960             func == bpf_lwt_xmit_push_encap)
5961                 return true;
5962 
5963         return false;
5964 }
5965 
5966 static const struct bpf_func_proto *
5967 bpf_base_func_proto(enum bpf_func_id func_id)
5968 {
5969         switch (func_id) {
5970         case BPF_FUNC_map_lookup_elem:
5971                 return &bpf_map_lookup_elem_proto;
5972         case BPF_FUNC_map_update_elem:
5973                 return &bpf_map_update_elem_proto;
5974         case BPF_FUNC_map_delete_elem:
5975                 return &bpf_map_delete_elem_proto;
5976         case BPF_FUNC_map_push_elem:
5977                 return &bpf_map_push_elem_proto;
5978         case BPF_FUNC_map_pop_elem:
5979                 return &bpf_map_pop_elem_proto;
5980         case BPF_FUNC_map_peek_elem:
5981                 return &bpf_map_peek_elem_proto;
5982         case BPF_FUNC_get_prandom_u32:
5983                 return &bpf_get_prandom_u32_proto;
5984         case BPF_FUNC_get_smp_processor_id:
5985                 return &bpf_get_raw_smp_processor_id_proto;
5986         case BPF_FUNC_get_numa_node_id:
5987                 return &bpf_get_numa_node_id_proto;
5988         case BPF_FUNC_tail_call:
5989                 return &bpf_tail_call_proto;
5990         case BPF_FUNC_ktime_get_ns:
5991                 return &bpf_ktime_get_ns_proto;
5992         default:
5993                 break;
5994         }
5995 
5996         if (!capable(CAP_SYS_ADMIN))
5997                 return NULL;
5998 
5999         switch (func_id) {
6000         case BPF_FUNC_spin_lock:
6001                 return &bpf_spin_lock_proto;
6002         case BPF_FUNC_spin_unlock:
6003                 return &bpf_spin_unlock_proto;
6004         case BPF_FUNC_trace_printk:
6005                 return bpf_get_trace_printk_proto();
6006         default:
6007                 return NULL;
6008         }
6009 }
6010 
6011 static const struct bpf_func_proto *
6012 sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6013 {
6014         switch (func_id) {
6015         /* inet and inet6 sockets are created in a process
6016          * context so there is always a valid uid/gid
6017          */
6018         case BPF_FUNC_get_current_uid_gid:
6019                 return &bpf_get_current_uid_gid_proto;
6020         case BPF_FUNC_get_local_storage:
6021                 return &bpf_get_local_storage_proto;
6022         default:
6023                 return bpf_base_func_proto(func_id);
6024         }
6025 }
6026 
6027 static const struct bpf_func_proto *
6028 sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6029 {
6030         switch (func_id) {
6031         /* inet and inet6 sockets are created in a process
6032          * context so there is always a valid uid/gid
6033          */
6034         case BPF_FUNC_get_current_uid_gid:
6035                 return &bpf_get_current_uid_gid_proto;
6036         case BPF_FUNC_bind:
6037                 switch (prog->expected_attach_type) {
6038                 case BPF_CGROUP_INET4_CONNECT:
6039                 case BPF_CGROUP_INET6_CONNECT:
6040                         return &bpf_bind_proto;
6041                 default:
6042                         return NULL;
6043                 }
6044         case BPF_FUNC_get_socket_cookie:
6045                 return &bpf_get_socket_cookie_sock_addr_proto;
6046         case BPF_FUNC_get_local_storage:
6047                 return &bpf_get_local_storage_proto;
6048 #ifdef CONFIG_INET
6049         case BPF_FUNC_sk_lookup_tcp:
6050                 return &bpf_sock_addr_sk_lookup_tcp_proto;
6051         case BPF_FUNC_sk_lookup_udp:
6052                 return &bpf_sock_addr_sk_lookup_udp_proto;
6053         case BPF_FUNC_sk_release:
6054                 return &bpf_sk_release_proto;
6055         case BPF_FUNC_skc_lookup_tcp:
6056                 return &bpf_sock_addr_skc_lookup_tcp_proto;
6057 #endif /* CONFIG_INET */
6058         case BPF_FUNC_sk_storage_get:
6059                 return &bpf_sk_storage_get_proto;
6060         case BPF_FUNC_sk_storage_delete:
6061                 return &bpf_sk_storage_delete_proto;
6062         default:
6063                 return bpf_base_func_proto(func_id);
6064         }
6065 }
6066 
6067 static const struct bpf_func_proto *
6068 sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6069 {
6070         switch (func_id) {
6071         case BPF_FUNC_skb_load_bytes:
6072                 return &bpf_skb_load_bytes_proto;
6073         case BPF_FUNC_skb_load_bytes_relative:
6074                 return &bpf_skb_load_bytes_relative_proto;
6075         case BPF_FUNC_get_socket_cookie:
6076                 return &bpf_get_socket_cookie_proto;
6077         case BPF_FUNC_get_socket_uid:
6078                 return &bpf_get_socket_uid_proto;
6079         case BPF_FUNC_perf_event_output:
6080                 return &bpf_skb_event_output_proto;
6081         default:
6082                 return bpf_base_func_proto(func_id);
6083         }
6084 }
6085 
6086 const struct bpf_func_proto bpf_sk_storage_get_proto __weak;
6087 const struct bpf_func_proto bpf_sk_storage_delete_proto __weak;
6088 
6089 static const struct bpf_func_proto *
6090 cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6091 {
6092         switch (func_id) {
6093         case BPF_FUNC_get_local_storage:
6094                 return &bpf_get_local_storage_proto;
6095         case BPF_FUNC_sk_fullsock:
6096                 return &bpf_sk_fullsock_proto;
6097         case BPF_FUNC_sk_storage_get:
6098                 return &bpf_sk_storage_get_proto;
6099         case BPF_FUNC_sk_storage_delete:
6100                 return &bpf_sk_storage_delete_proto;
6101         case BPF_FUNC_perf_event_output:
6102                 return &bpf_skb_event_output_proto;
6103 #ifdef CONFIG_SOCK_CGROUP_DATA
6104         case BPF_FUNC_skb_cgroup_id:
6105                 return &bpf_skb_cgroup_id_proto;
6106 #endif
6107 #ifdef CONFIG_INET
6108         case BPF_FUNC_tcp_sock:
6109                 return &bpf_tcp_sock_proto;
6110         case BPF_FUNC_get_listener_sock:
6111                 return &bpf_get_listener_sock_proto;
6112         case BPF_FUNC_skb_ecn_set_ce:
6113                 return &bpf_skb_ecn_set_ce_proto;
6114 #endif
6115         default:
6116                 return sk_filter_func_proto(func_id, prog);
6117         }
6118 }
6119 
6120 static const struct bpf_func_proto *
6121 tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6122 {
6123         switch (func_id) {
6124         case BPF_FUNC_skb_store_bytes:
6125                 return &bpf_skb_store_bytes_proto;
6126         case BPF_FUNC_skb_load_bytes:
6127                 return &bpf_skb_load_bytes_proto;
6128         case BPF_FUNC_skb_load_bytes_relative:
6129                 return &bpf_skb_load_bytes_relative_proto;
6130         case BPF_FUNC_skb_pull_data:
6131                 return &bpf_skb_pull_data_proto;
6132         case BPF_FUNC_csum_diff:
6133                 return &bpf_csum_diff_proto;
6134         case BPF_FUNC_csum_update:
6135                 return &bpf_csum_update_proto;
6136         case BPF_FUNC_l3_csum_replace:
6137                 return &bpf_l3_csum_replace_proto;
6138         case BPF_FUNC_l4_csum_replace:
6139                 return &bpf_l4_csum_replace_proto;
6140         case BPF_FUNC_clone_redirect:
6141                 return &bpf_clone_redirect_proto;
6142         case BPF_FUNC_get_cgroup_classid:
6143                 return &bpf_get_cgroup_classid_proto;
6144         case BPF_FUNC_skb_vlan_push:
6145                 return &bpf_skb_vlan_push_proto;
6146         case BPF_FUNC_skb_vlan_pop:
6147                 return &bpf_skb_vlan_pop_proto;
6148         case BPF_FUNC_skb_change_proto:
6149                 return &bpf_skb_change_proto_proto;
6150         case BPF_FUNC_skb_change_type:
6151                 return &bpf_skb_change_type_proto;
6152         case BPF_FUNC_skb_adjust_room:
6153                 return &bpf_skb_adjust_room_proto;
6154         case BPF_FUNC_skb_change_tail:
6155                 return &bpf_skb_change_tail_proto;
6156         case BPF_FUNC_skb_get_tunnel_key:
6157                 return &bpf_skb_get_tunnel_key_proto;
6158         case BPF_FUNC_skb_set_tunnel_key:
6159                 return bpf_get_skb_set_tunnel_proto(func_id);
6160         case BPF_FUNC_skb_get_tunnel_opt:
6161                 return &bpf_skb_get_tunnel_opt_proto;
6162         case BPF_FUNC_skb_set_tunnel_opt:
6163                 return bpf_get_skb_set_tunnel_proto(func_id);
6164         case BPF_FUNC_redirect:
6165                 return &bpf_redirect_proto;
6166         case BPF_FUNC_get_route_realm:
6167                 return &bpf_get_route_realm_proto;
6168         case BPF_FUNC_get_hash_recalc:
6169                 return &bpf_get_hash_recalc_proto;
6170         case BPF_FUNC_set_hash_invalid:
6171                 return &bpf_set_hash_invalid_proto;
6172         case BPF_FUNC_set_hash:
6173                 return &bpf_set_hash_proto;
6174         case BPF_FUNC_perf_event_output:
6175                 return &bpf_skb_event_output_proto;
6176         case BPF_FUNC_get_smp_processor_id:
6177                 return &bpf_get_smp_processor_id_proto;
6178         case BPF_FUNC_skb_under_cgroup:
6179                 return &bpf_skb_under_cgroup_proto;
6180         case BPF_FUNC_get_socket_cookie:
6181                 return &bpf_get_socket_cookie_proto;
6182         case BPF_FUNC_get_socket_uid:
6183                 return &bpf_get_socket_uid_proto;
6184         case BPF_FUNC_fib_lookup:
6185                 return &bpf_skb_fib_lookup_proto;
6186         case BPF_FUNC_sk_fullsock:
6187                 return &bpf_sk_fullsock_proto;
6188         case BPF_FUNC_sk_storage_get:
6189                 return &bpf_sk_storage_get_proto;
6190         case BPF_FUNC_sk_storage_delete:
6191                 return &bpf_sk_storage_delete_proto;
6192 #ifdef CONFIG_XFRM
6193         case BPF_FUNC_skb_get_xfrm_state:
6194                 return &bpf_skb_get_xfrm_state_proto;
6195 #endif
6196 #ifdef CONFIG_SOCK_CGROUP_DATA
6197         case BPF_FUNC_skb_cgroup_id:
6198                 return &bpf_skb_cgroup_id_proto;
6199         case BPF_FUNC_skb_ancestor_cgroup_id:
6200                 return &bpf_skb_ancestor_cgroup_id_proto;
6201 #endif
6202 #ifdef CONFIG_INET
6203         case BPF_FUNC_sk_lookup_tcp:
6204                 return &bpf_sk_lookup_tcp_proto;
6205         case BPF_FUNC_sk_lookup_udp:
6206                 return &bpf_sk_lookup_udp_proto;
6207         case BPF_FUNC_sk_release:
6208                 return &bpf_sk_release_proto;
6209         case BPF_FUNC_tcp_sock:
6210                 return &bpf_tcp_sock_proto;
6211         case BPF_FUNC_get_listener_sock:
6212                 return &bpf_get_listener_sock_proto;
6213         case BPF_FUNC_skc_lookup_tcp:
6214                 return &bpf_skc_lookup_tcp_proto;
6215         case BPF_FUNC_tcp_check_syncookie:
6216                 return &bpf_tcp_check_syncookie_proto;
6217         case BPF_FUNC_skb_ecn_set_ce:
6218                 return &bpf_skb_ecn_set_ce_proto;
6219         case BPF_FUNC_tcp_gen_syncookie:
6220                 return &bpf_tcp_gen_syncookie_proto;
6221 #endif
6222         default:
6223                 return bpf_base_func_proto(func_id);
6224         }
6225 }
6226 
6227 static const struct bpf_func_proto *
6228 xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6229 {
6230         switch (func_id) {
6231         case BPF_FUNC_perf_event_output:
6232                 return &bpf_xdp_event_output_proto;
6233         case BPF_FUNC_get_smp_processor_id:
6234                 return &bpf_get_smp_processor_id_proto;
6235         case BPF_FUNC_csum_diff:
6236                 return &bpf_csum_diff_proto;
6237         case BPF_FUNC_xdp_adjust_head:
6238                 return &bpf_xdp_adjust_head_proto;
6239         case BPF_FUNC_xdp_adjust_meta:
6240                 return &bpf_xdp_adjust_meta_proto;
6241         case BPF_FUNC_redirect:
6242                 return &bpf_xdp_redirect_proto;
6243         case BPF_FUNC_redirect_map:
6244                 return &bpf_xdp_redirect_map_proto;
6245         case BPF_FUNC_xdp_adjust_tail:
6246                 return &bpf_xdp_adjust_tail_proto;
6247         case BPF_FUNC_fib_lookup:
6248                 return &bpf_xdp_fib_lookup_proto;
6249 #ifdef CONFIG_INET
6250         case BPF_FUNC_sk_lookup_udp:
6251                 return &bpf_xdp_sk_lookup_udp_proto;
6252         case BPF_FUNC_sk_lookup_tcp:
6253                 return &bpf_xdp_sk_lookup_tcp_proto;
6254         case BPF_FUNC_sk_release:
6255                 return &bpf_sk_release_proto;
6256         case BPF_FUNC_skc_lookup_tcp:
6257                 return &bpf_xdp_skc_lookup_tcp_proto;
6258         case BPF_FUNC_tcp_check_syncookie:
6259                 return &bpf_tcp_check_syncookie_proto;
6260         case BPF_FUNC_tcp_gen_syncookie:
6261                 return &bpf_tcp_gen_syncookie_proto;
6262 #endif
6263         default:
6264                 return bpf_base_func_proto(func_id);
6265         }
6266 }
6267 
6268 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
6269 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
6270 
6271 static const struct bpf_func_proto *
6272 sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6273 {
6274         switch (func_id) {
6275         case BPF_FUNC_setsockopt:
6276                 return &bpf_setsockopt_proto;
6277         case BPF_FUNC_getsockopt:
6278                 return &bpf_getsockopt_proto;
6279         case BPF_FUNC_sock_ops_cb_flags_set:
6280                 return &bpf_sock_ops_cb_flags_set_proto;
6281         case BPF_FUNC_sock_map_update:
6282                 return &bpf_sock_map_update_proto;
6283         case BPF_FUNC_sock_hash_update:
6284                 return &bpf_sock_hash_update_proto;
6285         case BPF_FUNC_get_socket_cookie:
6286                 return &bpf_get_socket_cookie_sock_ops_proto;
6287         case BPF_FUNC_get_local_storage:
6288                 return &bpf_get_local_storage_proto;
6289         case BPF_FUNC_perf_event_output:
6290                 return &bpf_sockopt_event_output_proto;
6291         case BPF_FUNC_sk_storage_get:
6292                 return &bpf_sk_storage_get_proto;
6293         case BPF_FUNC_sk_storage_delete:
6294                 return &bpf_sk_storage_delete_proto;
6295 #ifdef CONFIG_INET
6296         case BPF_FUNC_tcp_sock:
6297                 return &bpf_tcp_sock_proto;
6298 #endif /* CONFIG_INET */
6299         default:
6300                 return bpf_base_func_proto(func_id);
6301         }
6302 }
6303 
6304 const struct bpf_func_proto bpf_msg_redirect_map_proto __weak;
6305 const struct bpf_func_proto bpf_msg_redirect_hash_proto __weak;
6306 
6307 static const struct bpf_func_proto *
6308 sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6309 {
6310         switch (func_id) {
6311         case BPF_FUNC_msg_redirect_map:
6312                 return &bpf_msg_redirect_map_proto;
6313         case BPF_FUNC_msg_redirect_hash:
6314                 return &bpf_msg_redirect_hash_proto;
6315         case BPF_FUNC_msg_apply_bytes:
6316                 return &bpf_msg_apply_bytes_proto;
6317         case BPF_FUNC_msg_cork_bytes:
6318                 return &bpf_msg_cork_bytes_proto;
6319         case BPF_FUNC_msg_pull_data:
6320                 return &bpf_msg_pull_data_proto;
6321         case BPF_FUNC_msg_push_data:
6322                 return &bpf_msg_push_data_proto;
6323         case BPF_FUNC_msg_pop_data:
6324                 return &bpf_msg_pop_data_proto;
6325         default:
6326                 return bpf_base_func_proto(func_id);
6327         }
6328 }
6329 
6330 const struct bpf_func_proto bpf_sk_redirect_map_proto __weak;
6331 const struct bpf_func_proto bpf_sk_redirect_hash_proto __weak;
6332 
6333 static const struct bpf_func_proto *
6334 sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6335 {
6336         switch (func_id) {
6337         case BPF_FUNC_skb_store_bytes:
6338                 return &bpf_skb_store_bytes_proto;
6339         case BPF_FUNC_skb_load_bytes:
6340                 return &bpf_skb_load_bytes_proto;
6341         case BPF_FUNC_skb_pull_data:
6342                 return &sk_skb_pull_data_proto;
6343         case BPF_FUNC_skb_change_tail:
6344                 return &sk_skb_change_tail_proto;
6345         case BPF_FUNC_skb_change_head:
6346                 return &sk_skb_change_head_proto;
6347         case BPF_FUNC_get_socket_cookie:
6348                 return &bpf_get_socket_cookie_proto;
6349         case BPF_FUNC_get_socket_uid:
6350                 return &bpf_get_socket_uid_proto;
6351         case BPF_FUNC_sk_redirect_map:
6352                 return &bpf_sk_redirect_map_proto;
6353         case BPF_FUNC_sk_redirect_hash:
6354                 return &bpf_sk_redirect_hash_proto;
6355         case BPF_FUNC_perf_event_output:
6356                 return &bpf_skb_event_output_proto;
6357 #ifdef CONFIG_INET
6358         case BPF_FUNC_sk_lookup_tcp:
6359                 return &bpf_sk_lookup_tcp_proto;
6360         case BPF_FUNC_sk_lookup_udp:
6361                 return &bpf_sk_lookup_udp_proto;
6362         case BPF_FUNC_sk_release:
6363                 return &bpf_sk_release_proto;
6364         case BPF_FUNC_skc_lookup_tcp:
6365                 return &bpf_skc_lookup_tcp_proto;
6366 #endif
6367         default:
6368                 return bpf_base_func_proto(func_id);
6369         }
6370 }
6371 
6372 static const struct bpf_func_proto *
6373 flow_dissector_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6374 {
6375         switch (func_id) {
6376         case BPF_FUNC_skb_load_bytes:
6377                 return &bpf_flow_dissector_load_bytes_proto;
6378         default:
6379                 return bpf_base_func_proto(func_id);
6380         }
6381 }
6382 
6383 static const struct bpf_func_proto *
6384 lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6385 {
6386         switch (func_id) {
6387         case BPF_FUNC_skb_load_bytes:
6388                 return &bpf_skb_load_bytes_proto;
6389         case BPF_FUNC_skb_pull_data:
6390                 return &bpf_skb_pull_data_proto;
6391         case BPF_FUNC_csum_diff:
6392                 return &bpf_csum_diff_proto;
6393         case BPF_FUNC_get_cgroup_classid:
6394                 return &bpf_get_cgroup_classid_proto;
6395         case BPF_FUNC_get_route_realm:
6396                 return &bpf_get_route_realm_proto;
6397         case BPF_FUNC_get_hash_recalc:
6398                 return &bpf_get_hash_recalc_proto;
6399         case BPF_FUNC_perf_event_output:
6400                 return &bpf_skb_event_output_proto;
6401         case BPF_FUNC_get_smp_processor_id:
6402                 return &bpf_get_smp_processor_id_proto;
6403         case BPF_FUNC_skb_under_cgroup:
6404                 return &bpf_skb_under_cgroup_proto;
6405         default:
6406                 return bpf_base_func_proto(func_id);
6407         }
6408 }
6409 
6410 static const struct bpf_func_proto *
6411 lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6412 {
6413         switch (func_id) {
6414         case BPF_FUNC_lwt_push_encap:
6415                 return &bpf_lwt_in_push_encap_proto;
6416         default:
6417                 return lwt_out_func_proto(func_id, prog);
6418         }
6419 }
6420 
6421 static const struct bpf_func_proto *
6422 lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6423 {
6424         switch (func_id) {
6425         case BPF_FUNC_skb_get_tunnel_key:
6426                 return &bpf_skb_get_tunnel_key_proto;
6427         case BPF_FUNC_skb_set_tunnel_key:
6428                 return bpf_get_skb_set_tunnel_proto(func_id);
6429         case BPF_FUNC_skb_get_tunnel_opt:
6430                 return &bpf_skb_get_tunnel_opt_proto;
6431         case BPF_FUNC_skb_set_tunnel_opt:
6432                 return bpf_get_skb_set_tunnel_proto(func_id);
6433         case BPF_FUNC_redirect:
6434                 return &bpf_redirect_proto;
6435         case BPF_FUNC_clone_redirect:
6436                 return &bpf_clone_redirect_proto;
6437         case BPF_FUNC_skb_change_tail:
6438                 return &bpf_skb_change_tail_proto;
6439         case BPF_FUNC_skb_change_head:
6440                 return &bpf_skb_change_head_proto;
6441         case BPF_FUNC_skb_store_bytes:
6442                 return &bpf_skb_store_bytes_proto;
6443         case BPF_FUNC_csum_update:
6444                 return &bpf_csum_update_proto;
6445         case BPF_FUNC_l3_csum_replace:
6446                 return &bpf_l3_csum_replace_proto;
6447         case BPF_FUNC_l4_csum_replace:
6448                 return &bpf_l4_csum_replace_proto;
6449         case BPF_FUNC_set_hash_invalid:
6450                 return &bpf_set_hash_invalid_proto;
6451         case BPF_FUNC_lwt_push_encap:
6452                 return &bpf_lwt_xmit_push_encap_proto;
6453         default:
6454                 return lwt_out_func_proto(func_id, prog);
6455         }
6456 }
6457 
6458 static const struct bpf_func_proto *
6459 lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
6460 {
6461         switch (func_id) {
6462 #if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
6463         case BPF_FUNC_lwt_seg6_store_bytes:
6464                 return &bpf_lwt_seg6_store_bytes_proto;
6465         case BPF_FUNC_lwt_seg6_action:
6466                 return &bpf_lwt_seg6_action_proto;
6467         case BPF_FUNC_lwt_seg6_adjust_srh:
6468                 return &bpf_lwt_seg6_adjust_srh_proto;
6469 #endif
6470         default:
6471                 return lwt_out_func_proto(func_id, prog);
6472         }
6473 }
6474 
6475 static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
6476                                     const struct bpf_prog *prog,
6477                                     struct bpf_insn_access_aux *info)
6478 {
6479         const int size_default = sizeof(__u32);
6480 
6481         if (off < 0 || off >= sizeof(struct __sk_buff))
6482                 return false;
6483 
6484         /* The verifier guarantees that size > 0. */
6485         if (off % size != 0)
6486                 return false;
6487 
6488         switch (off) {
6489         case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6490                 if (off + size > offsetofend(struct __sk_buff, cb[4]))
6491                         return false;
6492                 break;
6493         case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
6494         case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
6495         case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
6496         case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
6497         case bpf_ctx_range(struct __sk_buff, data):
6498         case bpf_ctx_range(struct __sk_buff, data_meta):
6499         case bpf_ctx_range(struct __sk_buff, data_end):
6500                 if (size != size_default)
6501                         return false;
6502                 break;
6503         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
6504                 return false;
6505         case bpf_ctx_range(struct __sk_buff, tstamp):
6506                 if (size != sizeof(__u64))
6507                         return false;
6508                 break;
6509         case offsetof(struct __sk_buff, sk):
6510                 if (type == BPF_WRITE || size != sizeof(__u64))
6511                         return false;
6512                 info->reg_type = PTR_TO_SOCK_COMMON_OR_NULL;
6513                 break;
6514         default:
6515                 /* Only narrow read access allowed for now. */
6516                 if (type == BPF_WRITE) {
6517                         if (size != size_default)
6518                                 return false;
6519                 } else {
6520                         bpf_ctx_record_field_size(info, size_default);
6521                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6522                                 return false;
6523                 }
6524         }
6525 
6526         return true;
6527 }
6528 
6529 static bool sk_filter_is_valid_access(int off, int size,
6530                                       enum bpf_access_type type,
6531                                       const struct bpf_prog *prog,
6532                                       struct bpf_insn_access_aux *info)
6533 {
6534         switch (off) {
6535         case bpf_ctx_range(struct __sk_buff, tc_classid):
6536         case bpf_ctx_range(struct __sk_buff, data):
6537         case bpf_ctx_range(struct __sk_buff, data_meta):
6538         case bpf_ctx_range(struct __sk_buff, data_end):
6539         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6540         case bpf_ctx_range(struct __sk_buff, tstamp):
6541         case bpf_ctx_range(struct __sk_buff, wire_len):
6542                 return false;
6543         }
6544 
6545         if (type == BPF_WRITE) {
6546                 switch (off) {
6547                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6548                         break;
6549                 default:
6550                         return false;
6551                 }
6552         }
6553 
6554         return bpf_skb_is_valid_access(off, size, type, prog, info);
6555 }
6556 
6557 static bool cg_skb_is_valid_access(int off, int size,
6558                                    enum bpf_access_type type,
6559                                    const struct bpf_prog *prog,
6560                                    struct bpf_insn_access_aux *info)
6561 {
6562         switch (off) {
6563         case bpf_ctx_range(struct __sk_buff, tc_classid):
6564         case bpf_ctx_range(struct __sk_buff, data_meta):
6565         case bpf_ctx_range(struct __sk_buff, wire_len):
6566                 return false;
6567         case bpf_ctx_range(struct __sk_buff, data):
6568         case bpf_ctx_range(struct __sk_buff, data_end):
6569                 if (!capable(CAP_SYS_ADMIN))
6570                         return false;
6571                 break;
6572         }
6573 
6574         if (type == BPF_WRITE) {
6575                 switch (off) {
6576                 case bpf_ctx_range(struct __sk_buff, mark):
6577                 case bpf_ctx_range(struct __sk_buff, priority):
6578                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6579                         break;
6580                 case bpf_ctx_range(struct __sk_buff, tstamp):
6581                         if (!capable(CAP_SYS_ADMIN))
6582                                 return false;
6583                         break;
6584                 default:
6585                         return false;
6586                 }
6587         }
6588 
6589         switch (off) {
6590         case bpf_ctx_range(struct __sk_buff, data):
6591                 info->reg_type = PTR_TO_PACKET;
6592                 break;
6593         case bpf_ctx_range(struct __sk_buff, data_end):
6594                 info->reg_type = PTR_TO_PACKET_END;
6595                 break;
6596         }
6597 
6598         return bpf_skb_is_valid_access(off, size, type, prog, info);
6599 }
6600 
6601 static bool lwt_is_valid_access(int off, int size,
6602                                 enum bpf_access_type type,
6603                                 const struct bpf_prog *prog,
6604                                 struct bpf_insn_access_aux *info)
6605 {
6606         switch (off) {
6607         case bpf_ctx_range(struct __sk_buff, tc_classid):
6608         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6609         case bpf_ctx_range(struct __sk_buff, data_meta):
6610         case bpf_ctx_range(struct __sk_buff, tstamp):
6611         case bpf_ctx_range(struct __sk_buff, wire_len):
6612                 return false;
6613         }
6614 
6615         if (type == BPF_WRITE) {
6616                 switch (off) {
6617                 case bpf_ctx_range(struct __sk_buff, mark):
6618                 case bpf_ctx_range(struct __sk_buff, priority):
6619                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6620                         break;
6621                 default:
6622                         return false;
6623                 }
6624         }
6625 
6626         switch (off) {
6627         case bpf_ctx_range(struct __sk_buff, data):
6628                 info->reg_type = PTR_TO_PACKET;
6629                 break;
6630         case bpf_ctx_range(struct __sk_buff, data_end):
6631                 info->reg_type = PTR_TO_PACKET_END;
6632                 break;
6633         }
6634 
6635         return bpf_skb_is_valid_access(off, size, type, prog, info);
6636 }
6637 
6638 /* Attach type specific accesses */
6639 static bool __sock_filter_check_attach_type(int off,
6640                                             enum bpf_access_type access_type,
6641                                             enum bpf_attach_type attach_type)
6642 {
6643         switch (off) {
6644         case offsetof(struct bpf_sock, bound_dev_if):
6645         case offsetof(struct bpf_sock, mark):
6646         case offsetof(struct bpf_sock, priority):
6647                 switch (attach_type) {
6648                 case BPF_CGROUP_INET_SOCK_CREATE:
6649                         goto full_access;
6650                 default:
6651                         return false;
6652                 }
6653         case bpf_ctx_range(struct bpf_sock, src_ip4):
6654                 switch (attach_type) {
6655                 case BPF_CGROUP_INET4_POST_BIND:
6656                         goto read_only;
6657                 default:
6658                         return false;
6659                 }
6660         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6661                 switch (attach_type) {
6662                 case BPF_CGROUP_INET6_POST_BIND:
6663                         goto read_only;
6664                 default:
6665                         return false;
6666                 }
6667         case bpf_ctx_range(struct bpf_sock, src_port):
6668                 switch (attach_type) {
6669                 case BPF_CGROUP_INET4_POST_BIND:
6670                 case BPF_CGROUP_INET6_POST_BIND:
6671                         goto read_only;
6672                 default:
6673                         return false;
6674                 }
6675         }
6676 read_only:
6677         return access_type == BPF_READ;
6678 full_access:
6679         return true;
6680 }
6681 
6682 bool bpf_sock_common_is_valid_access(int off, int size,
6683                                      enum bpf_access_type type,
6684                                      struct bpf_insn_access_aux *info)
6685 {
6686         switch (off) {
6687         case bpf_ctx_range_till(struct bpf_sock, type, priority):
6688                 return false;
6689         default:
6690                 return bpf_sock_is_valid_access(off, size, type, info);
6691         }
6692 }
6693 
6694 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
6695                               struct bpf_insn_access_aux *info)
6696 {
6697         const int size_default = sizeof(__u32);
6698 
6699         if (off < 0 || off >= sizeof(struct bpf_sock))
6700                 return false;
6701         if (off % size != 0)
6702                 return false;
6703 
6704         switch (off) {
6705         case offsetof(struct bpf_sock, state):
6706         case offsetof(struct bpf_sock, family):
6707         case offsetof(struct bpf_sock, type):
6708         case offsetof(struct bpf_sock, protocol):
6709         case offsetof(struct bpf_sock, dst_port):
6710         case offsetof(struct bpf_sock, src_port):
6711         case bpf_ctx_range(struct bpf_sock, src_ip4):
6712         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
6713         case bpf_ctx_range(struct bpf_sock, dst_ip4):
6714         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
6715                 bpf_ctx_record_field_size(info, size_default);
6716                 return bpf_ctx_narrow_access_ok(off, size, size_default);
6717         }
6718 
6719         return size == size_default;
6720 }
6721 
6722 static bool sock_filter_is_valid_access(int off, int size,
6723                                         enum bpf_access_type type,
6724                                         const struct bpf_prog *prog,
6725                                         struct bpf_insn_access_aux *info)
6726 {
6727         if (!bpf_sock_is_valid_access(off, size, type, info))
6728                 return false;
6729         return __sock_filter_check_attach_type(off, type,
6730                                                prog->expected_attach_type);
6731 }
6732 
6733 static int bpf_noop_prologue(struct bpf_insn *insn_buf, bool direct_write,
6734                              const struct bpf_prog *prog)
6735 {
6736         /* Neither direct read nor direct write requires any preliminary
6737          * action.
6738          */
6739         return 0;
6740 }
6741 
6742 static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
6743                                 const struct bpf_prog *prog, int drop_verdict)
6744 {
6745         struct bpf_insn *insn = insn_buf;
6746 
6747         if (!direct_write)
6748                 return 0;
6749 
6750         /* if (!skb->cloned)
6751          *       goto start;
6752          *
6753          * (Fast-path, otherwise approximation that we might be
6754          *  a clone, do the rest in helper.)
6755          */
6756         *insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
6757         *insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
6758         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);
6759 
6760         /* ret = bpf_skb_pull_data(skb, 0); */
6761         *insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
6762         *insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
6763         *insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
6764                                BPF_FUNC_skb_pull_data);
6765         /* if (!ret)
6766          *      goto restore;
6767          * return TC_ACT_SHOT;
6768          */
6769         *insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
6770         *insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
6771         *insn++ = BPF_EXIT_INSN();
6772 
6773         /* restore: */
6774         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
6775         /* start: */
6776         *insn++ = prog->insnsi[0];
6777 
6778         return insn - insn_buf;
6779 }
6780 
6781 static int bpf_gen_ld_abs(const struct bpf_insn *orig,
6782                           struct bpf_insn *insn_buf)
6783 {
6784         bool indirect = BPF_MODE(orig->code) == BPF_IND;
6785         struct bpf_insn *insn = insn_buf;
6786 
6787         /* We're guaranteed here that CTX is in R6. */
6788         *insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
6789         if (!indirect) {
6790                 *insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
6791         } else {
6792                 *insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
6793                 if (orig->imm)
6794                         *insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
6795         }
6796 
6797         switch (BPF_SIZE(orig->code)) {
6798         case BPF_B:
6799                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
6800                 break;
6801         case BPF_H:
6802                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
6803                 break;
6804         case BPF_W:
6805                 *insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
6806                 break;
6807         }
6808 
6809         *insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
6810         *insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
6811         *insn++ = BPF_EXIT_INSN();
6812 
6813         return insn - insn_buf;
6814 }
6815 
6816 static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
6817                                const struct bpf_prog *prog)
6818 {
6819         return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
6820 }
6821 
6822 static bool tc_cls_act_is_valid_access(int off, int size,
6823                                        enum bpf_access_type type,
6824                                        const struct bpf_prog *prog,
6825                                        struct bpf_insn_access_aux *info)
6826 {
6827         if (type == BPF_WRITE) {
6828                 switch (off) {
6829                 case bpf_ctx_range(struct __sk_buff, mark):
6830                 case bpf_ctx_range(struct __sk_buff, tc_index):
6831                 case bpf_ctx_range(struct __sk_buff, priority):
6832                 case bpf_ctx_range(struct __sk_buff, tc_classid):
6833                 case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
6834                 case bpf_ctx_range(struct __sk_buff, tstamp):
6835                 case bpf_ctx_range(struct __sk_buff, queue_mapping):
6836                         break;
6837                 default:
6838                         return false;
6839                 }
6840         }
6841 
6842         switch (off) {
6843         case bpf_ctx_range(struct __sk_buff, data):
6844                 info->reg_type = PTR_TO_PACKET;
6845                 break;
6846         case bpf_ctx_range(struct __sk_buff, data_meta):
6847                 info->reg_type = PTR_TO_PACKET_META;
6848                 break;
6849         case bpf_ctx_range(struct __sk_buff, data_end):
6850                 info->reg_type = PTR_TO_PACKET_END;
6851                 break;
6852         case bpf_ctx_range_till(struct __sk_buff, family, local_port):
6853                 return false;
6854         }
6855 
6856         return bpf_skb_is_valid_access(off, size, type, prog, info);
6857 }
6858 
6859 static bool __is_valid_xdp_access(int off, int size)
6860 {
6861         if (off < 0 || off >= sizeof(struct xdp_md))
6862                 return false;
6863         if (off % size != 0)
6864                 return false;
6865         if (size != sizeof(__u32))
6866                 return false;
6867 
6868         return true;
6869 }
6870 
6871 static bool xdp_is_valid_access(int off, int size,
6872                                 enum bpf_access_type type,
6873                                 const struct bpf_prog *prog,
6874                                 struct bpf_insn_access_aux *info)
6875 {
6876         if (type == BPF_WRITE) {
6877                 if (bpf_prog_is_dev_bound(prog->aux)) {
6878                         switch (off) {
6879                         case offsetof(struct xdp_md, rx_queue_index):
6880                                 return __is_valid_xdp_access(off, size);
6881                         }
6882                 }
6883                 return false;
6884         }
6885 
6886         switch (off) {
6887         case offsetof(struct xdp_md, data):
6888                 info->reg_type = PTR_TO_PACKET;
6889                 break;
6890         case offsetof(struct xdp_md, data_meta):
6891                 info->reg_type = PTR_TO_PACKET_META;
6892                 break;
6893         case offsetof(struct xdp_md, data_end):
6894                 info->reg_type = PTR_TO_PACKET_END;
6895                 break;
6896         }
6897 
6898         return __is_valid_xdp_access(off, size);
6899 }
6900 
6901 void bpf_warn_invalid_xdp_action(u32 act)
6902 {
6903         const u32 act_max = XDP_REDIRECT;
6904 
6905         WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
6906                   act > act_max ? "Illegal" : "Driver unsupported",
6907                   act);
6908 }
6909 EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);
6910 
6911 static bool sock_addr_is_valid_access(int off, int size,
6912                                       enum bpf_access_type type,
6913                                       const struct bpf_prog *prog,
6914                                       struct bpf_insn_access_aux *info)
6915 {
6916         const int size_default = sizeof(__u32);
6917 
6918         if (off < 0 || off >= sizeof(struct bpf_sock_addr))
6919                 return false;
6920         if (off % size != 0)
6921                 return false;
6922 
6923         /* Disallow access to IPv6 fields from IPv4 contex and vise
6924          * versa.
6925          */
6926         switch (off) {
6927         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6928                 switch (prog->expected_attach_type) {
6929                 case BPF_CGROUP_INET4_BIND:
6930                 case BPF_CGROUP_INET4_CONNECT:
6931                 case BPF_CGROUP_UDP4_SENDMSG:
6932                 case BPF_CGROUP_UDP4_RECVMSG:
6933                         break;
6934                 default:
6935                         return false;
6936                 }
6937                 break;
6938         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6939                 switch (prog->expected_attach_type) {
6940                 case BPF_CGROUP_INET6_BIND:
6941                 case BPF_CGROUP_INET6_CONNECT:
6942                 case BPF_CGROUP_UDP6_SENDMSG:
6943                 case BPF_CGROUP_UDP6_RECVMSG:
6944                         break;
6945                 default:
6946                         return false;
6947                 }
6948                 break;
6949         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6950                 switch (prog->expected_attach_type) {
6951                 case BPF_CGROUP_UDP4_SENDMSG:
6952                         break;
6953                 default:
6954                         return false;
6955                 }
6956                 break;
6957         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6958                                 msg_src_ip6[3]):
6959                 switch (prog->expected_attach_type) {
6960                 case BPF_CGROUP_UDP6_SENDMSG:
6961                         break;
6962                 default:
6963                         return false;
6964                 }
6965                 break;
6966         }
6967 
6968         switch (off) {
6969         case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
6970         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
6971         case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
6972         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
6973                                 msg_src_ip6[3]):
6974                 if (type == BPF_READ) {
6975                         bpf_ctx_record_field_size(info, size_default);
6976 
6977                         if (bpf_ctx_wide_access_ok(off, size,
6978                                                    struct bpf_sock_addr,
6979                                                    user_ip6))
6980                                 return true;
6981 
6982                         if (bpf_ctx_wide_access_ok(off, size,
6983                                                    struct bpf_sock_addr,
6984                                                    msg_src_ip6))
6985                                 return true;
6986 
6987                         if (!bpf_ctx_narrow_access_ok(off, size, size_default))
6988                                 return false;
6989                 } else {
6990                         if (bpf_ctx_wide_access_ok(off, size,
6991                                                    struct bpf_sock_addr,
6992                                                    user_ip6))
6993                                 return true;
6994 
6995                         if (bpf_ctx_wide_access_ok(off, size,
6996                                                    struct bpf_sock_addr,
6997                                                    msg_src_ip6))
6998                                 return true;
6999 
7000                         if (size != size_default)
7001                                 return false;
7002                 }
7003                 break;
7004         case bpf_ctx_range(struct bpf_sock_addr, user_port):
7005                 if (size != size_default)
7006                         return false;
7007                 break;
7008         case offsetof(struct bpf_sock_addr, sk):
7009                 if (type != BPF_READ)
7010                         return false;
7011                 if (size != sizeof(__u64))
7012                         return false;
7013                 info->reg_type = PTR_TO_SOCKET;
7014                 break;
7015         default:
7016                 if (type == BPF_READ) {
7017                         if (size != size_default)
7018                                 return false;
7019                 } else {
7020                         return false;
7021                 }
7022         }
7023 
7024         return true;
7025 }
7026 
7027 static bool sock_ops_is_valid_access(int off, int size,
7028                                      enum bpf_access_type type,
7029                                      const struct bpf_prog *prog,
7030                                      struct bpf_insn_access_aux *info)
7031 {
7032         const int size_default = sizeof(__u32);
7033 
7034         if (off < 0 || off >= sizeof(struct bpf_sock_ops))
7035                 return false;
7036 
7037         /* The verifier guarantees that size > 0. */
7038         if (off % size != 0)
7039                 return false;
7040 
7041         if (type == BPF_WRITE) {
7042                 switch (off) {
7043                 case offsetof(struct bpf_sock_ops, reply):
7044                 case offsetof(struct bpf_sock_ops, sk_txhash):
7045                         if (size != size_default)
7046                                 return false;
7047                         break;
7048                 default:
7049                         return false;
7050                 }
7051         } else {
7052                 switch (off) {
7053                 case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
7054                                         bytes_acked):
7055                         if (size != sizeof(__u64))
7056                                 return false;
7057                         break;
7058                 case offsetof(struct bpf_sock_ops, sk):
7059                         if (size != sizeof(__u64))
7060                                 return false;
7061                         info->reg_type = PTR_TO_SOCKET_OR_NULL;
7062                         break;
7063                 default:
7064                         if (size != size_default)
7065                                 return false;
7066                         break;
7067                 }
7068         }
7069 
7070         return true;
7071 }
7072 
7073 static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
7074                            const struct bpf_prog *prog)
7075 {
7076         return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
7077 }
7078 
7079 static bool sk_skb_is_valid_access(int off, int size,
7080                                    enum bpf_access_type type,
7081                                    const struct bpf_prog *prog,
7082                                    struct bpf_insn_access_aux *info)
7083 {
7084         switch (off) {
7085         case bpf_ctx_range(struct __sk_buff, tc_classid):
7086         case bpf_ctx_range(struct __sk_buff, data_meta):
7087         case bpf_ctx_range(struct __sk_buff, tstamp):
7088         case bpf_ctx_range(struct __sk_buff, wire_len):
7089                 return false;
7090         }
7091 
7092         if (type == BPF_WRITE) {
7093                 switch (off) {
7094                 case bpf_ctx_range(struct __sk_buff, tc_index):
7095                 case bpf_ctx_range(struct __sk_buff, priority):
7096                         break;
7097                 default:
7098                         return false;
7099                 }
7100         }
7101 
7102         switch (off) {
7103         case bpf_ctx_range(struct __sk_buff, mark):
7104                 return false;
7105         case bpf_ctx_range(struct __sk_buff, data):
7106                 info->reg_type = PTR_TO_PACKET;
7107                 break;
7108         case bpf_ctx_range(struct __sk_buff, data_end):
7109                 info->reg_type = PTR_TO_PACKET_END;
7110                 break;
7111         }
7112 
7113         return bpf_skb_is_valid_access(off, size, type, prog, info);
7114 }
7115 
7116 static bool sk_msg_is_valid_access(int off, int size,
7117                                    enum bpf_access_type type,
7118                                    const struct bpf_prog *prog,
7119                                    struct bpf_insn_access_aux *info)
7120 {
7121         if (type == BPF_WRITE)
7122                 return false;
7123 
7124         if (off % size != 0)
7125                 return false;
7126 
7127         switch (off) {
7128         case offsetof(struct sk_msg_md, data):
7129                 info->reg_type = PTR_TO_PACKET;
7130                 if (size != sizeof(__u64))
7131                         return false;
7132                 break;
7133         case offsetof(struct sk_msg_md, data_end):
7134                 info->reg_type = PTR_TO_PACKET_END;
7135                 if (size != sizeof(__u64))
7136                         return false;
7137                 break;
7138         case bpf_ctx_range(struct sk_msg_md, family):
7139         case bpf_ctx_range(struct sk_msg_md, remote_ip4):
7140         case bpf_ctx_range(struct sk_msg_md, local_ip4):
7141         case bpf_ctx_range_till(struct sk_msg_md, remote_ip6[0], remote_ip6[3]):
7142         case bpf_ctx_range_till(struct sk_msg_md, local_ip6[0], local_ip6[3]):
7143         case bpf_ctx_range(struct sk_msg_md, remote_port):
7144         case bpf_ctx_range(struct sk_msg_md, local_port):
7145         case bpf_ctx_range(struct sk_msg_md, size):
7146                 if (size != sizeof(__u32))
7147                         return false;
7148                 break;
7149         default:
7150                 return false;
7151         }
7152         return true;
7153 }
7154 
7155 static bool flow_dissector_is_valid_access(int off, int size,
7156                                            enum bpf_access_type type,
7157                                            const struct bpf_prog *prog,
7158                                            struct bpf_insn_access_aux *info)
7159 {
7160         const int size_default = sizeof(__u32);
7161 
7162         if (off < 0 || off >= sizeof(struct __sk_buff))
7163                 return false;
7164 
7165         if (type == BPF_WRITE)
7166                 return false;
7167 
7168         switch (off) {
7169         case bpf_ctx_range(struct __sk_buff, data):
7170                 if (size != size_default)
7171                         return false;
7172                 info->reg_type = PTR_TO_PACKET;
7173                 return true;
7174         case bpf_ctx_range(struct __sk_buff, data_end):
7175                 if (size != size_default)
7176                         return false;
7177                 info->reg_type = PTR_TO_PACKET_END;
7178                 return true;
7179         case bpf_ctx_range_ptr(struct __sk_buff, flow_keys):
7180                 if (size != sizeof(__u64))
7181                         return false;
7182                 info->reg_type = PTR_TO_FLOW_KEYS;
7183                 return true;
7184         default:
7185                 return false;
7186         }
7187 }
7188 
7189 static u32 flow_dissector_convert_ctx_access(enum bpf_access_type type,
7190                                              const struct bpf_insn *si,
7191                                              struct bpf_insn *insn_buf,
7192                                              struct bpf_prog *prog,
7193                                              u32 *target_size)
7194 
7195 {
7196         struct bpf_insn *insn = insn_buf;
7197 
7198         switch (si->off) {
7199         case offsetof(struct __sk_buff, data):
7200                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data),
7201                                       si->dst_reg, si->src_reg,
7202                                       offsetof(struct bpf_flow_dissector, data));
7203                 break;
7204 
7205         case offsetof(struct __sk_buff, data_end):
7206                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, data_end),
7207                                       si->dst_reg, si->src_reg,
7208                                       offsetof(struct bpf_flow_dissector, data_end));
7209                 break;
7210 
7211         case offsetof(struct __sk_buff, flow_keys):
7212                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_flow_dissector, flow_keys),
7213                                       si->dst_reg, si->src_reg,
7214                                       offsetof(struct bpf_flow_dissector, flow_keys));
7215                 break;
7216         }
7217 
7218         return insn - insn_buf;
7219 }
7220 
7221 static u32 bpf_convert_ctx_access(enum bpf_access_type type,
7222                                   const struct bpf_insn *si,
7223                                   struct bpf_insn *insn_buf,
7224                                   struct bpf_prog *prog, u32 *target_size)
7225 {
7226         struct bpf_insn *insn = insn_buf;
7227         int off;
7228 
7229         switch (si->off) {
7230         case offsetof(struct __sk_buff, len):
7231                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7232                                       bpf_target_off(struct sk_buff, len, 4,
7233                                                      target_size));
7234                 break;
7235 
7236         case offsetof(struct __sk_buff, protocol):
7237                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7238                                       bpf_target_off(struct sk_buff, protocol, 2,
7239                                                      target_size));
7240                 break;
7241 
7242         case offsetof(struct __sk_buff, vlan_proto):
7243                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7244                                       bpf_target_off(struct sk_buff, vlan_proto, 2,
7245                                                      target_size));
7246                 break;
7247 
7248         case offsetof(struct __sk_buff, priority):
7249                 if (type == BPF_WRITE)
7250                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7251                                               bpf_target_off(struct sk_buff, priority, 4,
7252                                                              target_size));
7253                 else
7254                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7255                                               bpf_target_off(struct sk_buff, priority, 4,
7256                                                              target_size));
7257                 break;
7258 
7259         case offsetof(struct __sk_buff, ingress_ifindex):
7260                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7261                                       bpf_target_off(struct sk_buff, skb_iif, 4,
7262                                                      target_size));
7263                 break;
7264 
7265         case offsetof(struct __sk_buff, ifindex):
7266                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7267                                       si->dst_reg, si->src_reg,
7268                                       offsetof(struct sk_buff, dev));
7269                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
7270                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7271                                       bpf_target_off(struct net_device, ifindex, 4,
7272                                                      target_size));
7273                 break;
7274 
7275         case offsetof(struct __sk_buff, hash):
7276                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7277                                       bpf_target_off(struct sk_buff, hash, 4,
7278                                                      target_size));
7279                 break;
7280 
7281         case offsetof(struct __sk_buff, mark):
7282                 if (type == BPF_WRITE)
7283                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7284                                               bpf_target_off(struct sk_buff, mark, 4,
7285                                                              target_size));
7286                 else
7287                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7288                                               bpf_target_off(struct sk_buff, mark, 4,
7289                                                              target_size));
7290                 break;
7291 
7292         case offsetof(struct __sk_buff, pkt_type):
7293                 *target_size = 1;
7294                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7295                                       PKT_TYPE_OFFSET());
7296                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
7297 #ifdef __BIG_ENDIAN_BITFIELD
7298                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
7299 #endif
7300                 break;
7301 
7302         case offsetof(struct __sk_buff, queue_mapping):
7303                 if (type == BPF_WRITE) {
7304                         *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
7305                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7306                                               bpf_target_off(struct sk_buff,
7307                                                              queue_mapping,
7308                                                              2, target_size));
7309                 } else {
7310                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7311                                               bpf_target_off(struct sk_buff,
7312                                                              queue_mapping,
7313                                                              2, target_size));
7314                 }
7315                 break;
7316 
7317         case offsetof(struct __sk_buff, vlan_present):
7318                 *target_size = 1;
7319                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
7320                                       PKT_VLAN_PRESENT_OFFSET());
7321                 if (PKT_VLAN_PRESENT_BIT)
7322                         *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
7323                 if (PKT_VLAN_PRESENT_BIT < 7)
7324                         *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
7325                 break;
7326 
7327         case offsetof(struct __sk_buff, vlan_tci):
7328                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7329                                       bpf_target_off(struct sk_buff, vlan_tci, 2,
7330                                                      target_size));
7331                 break;
7332 
7333         case offsetof(struct __sk_buff, cb[0]) ...
7334              offsetofend(struct __sk_buff, cb[4]) - 1:
7335                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
7336                 BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
7337                               offsetof(struct qdisc_skb_cb, data)) %
7338                              sizeof(__u64));
7339 
7340                 prog->cb_access = 1;
7341                 off  = si->off;
7342                 off -= offsetof(struct __sk_buff, cb[0]);
7343                 off += offsetof(struct sk_buff, cb);
7344                 off += offsetof(struct qdisc_skb_cb, data);
7345                 if (type == BPF_WRITE)
7346                         *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
7347                                               si->src_reg, off);
7348                 else
7349                         *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
7350                                               si->src_reg, off);
7351                 break;
7352 
7353         case offsetof(struct __sk_buff, tc_classid):
7354                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);
7355 
7356                 off  = si->off;
7357                 off -= offsetof(struct __sk_buff, tc_classid);
7358                 off += offsetof(struct sk_buff, cb);
7359                 off += offsetof(struct qdisc_skb_cb, tc_classid);
7360                 *target_size = 2;
7361                 if (type == BPF_WRITE)
7362                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
7363                                               si->src_reg, off);
7364                 else
7365                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
7366                                               si->src_reg, off);
7367                 break;
7368 
7369         case offsetof(struct __sk_buff, data):
7370                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
7371                                       si->dst_reg, si->src_reg,
7372                                       offsetof(struct sk_buff, data));
7373                 break;
7374 
7375         case offsetof(struct __sk_buff, data_meta):
7376                 off  = si->off;
7377                 off -= offsetof(struct __sk_buff, data_meta);
7378                 off += offsetof(struct sk_buff, cb);
7379                 off += offsetof(struct bpf_skb_data_end, data_meta);
7380                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7381                                       si->src_reg, off);
7382                 break;
7383 
7384         case offsetof(struct __sk_buff, data_end):
7385                 off  = si->off;
7386                 off -= offsetof(struct __sk_buff, data_end);
7387                 off += offsetof(struct sk_buff, cb);
7388                 off += offsetof(struct bpf_skb_data_end, data_end);
7389                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
7390                                       si->src_reg, off);
7391                 break;
7392 
7393         case offsetof(struct __sk_buff, tc_index):
7394 #ifdef CONFIG_NET_SCHED
7395                 if (type == BPF_WRITE)
7396                         *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
7397                                               bpf_target_off(struct sk_buff, tc_index, 2,
7398                                                              target_size));
7399                 else
7400                         *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
7401                                               bpf_target_off(struct sk_buff, tc_index, 2,
7402                                                              target_size));
7403 #else
7404                 *target_size = 2;
7405                 if (type == BPF_WRITE)
7406                         *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
7407                 else
7408                         *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7409 #endif
7410                 break;
7411 
7412         case offsetof(struct __sk_buff, napi_id):
7413 #if defined(CONFIG_NET_RX_BUSY_POLL)
7414                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7415                                       bpf_target_off(struct sk_buff, napi_id, 4,
7416                                                      target_size));
7417                 *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
7418                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7419 #else
7420                 *target_size = 4;
7421                 *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
7422 #endif
7423                 break;
7424         case offsetof(struct __sk_buff, family):
7425                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
7426 
7427                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7428                                       si->dst_reg, si->src_reg,
7429                                       offsetof(struct sk_buff, sk));
7430                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7431                                       bpf_target_off(struct sock_common,
7432                                                      skc_family,
7433                                                      2, target_size));
7434                 break;
7435         case offsetof(struct __sk_buff, remote_ip4):
7436                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
7437 
7438                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7439                                       si->dst_reg, si->src_reg,
7440                                       offsetof(struct sk_buff, sk));
7441                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7442                                       bpf_target_off(struct sock_common,
7443                                                      skc_daddr,
7444                                                      4, target_size));
7445                 break;
7446         case offsetof(struct __sk_buff, local_ip4):
7447                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7448                                           skc_rcv_saddr) != 4);
7449 
7450                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7451                                       si->dst_reg, si->src_reg,
7452                                       offsetof(struct sk_buff, sk));
7453                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7454                                       bpf_target_off(struct sock_common,
7455                                                      skc_rcv_saddr,
7456                                                      4, target_size));
7457                 break;
7458         case offsetof(struct __sk_buff, remote_ip6[0]) ...
7459              offsetof(struct __sk_buff, remote_ip6[3]):
7460 #if IS_ENABLED(CONFIG_IPV6)
7461                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7462                                           skc_v6_daddr.s6_addr32[0]) != 4);
7463 
7464                 off = si->off;
7465                 off -= offsetof(struct __sk_buff, remote_ip6[0]);
7466 
7467                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7468                                       si->dst_reg, si->src_reg,
7469                                       offsetof(struct sk_buff, sk));
7470                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7471                                       offsetof(struct sock_common,
7472                                                skc_v6_daddr.s6_addr32[0]) +
7473                                       off);
7474 #else
7475                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7476 #endif
7477                 break;
7478         case offsetof(struct __sk_buff, local_ip6[0]) ...
7479              offsetof(struct __sk_buff, local_ip6[3]):
7480 #if IS_ENABLED(CONFIG_IPV6)
7481                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
7482                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
7483 
7484                 off = si->off;
7485                 off -= offsetof(struct __sk_buff, local_ip6[0]);
7486 
7487                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7488                                       si->dst_reg, si->src_reg,
7489                                       offsetof(struct sk_buff, sk));
7490                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7491                                       offsetof(struct sock_common,
7492                                                skc_v6_rcv_saddr.s6_addr32[0]) +
7493                                       off);
7494 #else
7495                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7496 #endif
7497                 break;
7498 
7499         case offsetof(struct __sk_buff, remote_port):
7500                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
7501 
7502                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7503                                       si->dst_reg, si->src_reg,
7504                                       offsetof(struct sk_buff, sk));
7505                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7506                                       bpf_target_off(struct sock_common,
7507                                                      skc_dport,
7508                                                      2, target_size));
7509 #ifndef __BIG_ENDIAN_BITFIELD
7510                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
7511 #endif
7512                 break;
7513 
7514         case offsetof(struct __sk_buff, local_port):
7515                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
7516 
7517                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7518                                       si->dst_reg, si->src_reg,
7519                                       offsetof(struct sk_buff, sk));
7520                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
7521                                       bpf_target_off(struct sock_common,
7522                                                      skc_num, 2, target_size));
7523                 break;
7524 
7525         case offsetof(struct __sk_buff, tstamp):
7526                 BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, tstamp) != 8);
7527 
7528                 if (type == BPF_WRITE)
7529                         *insn++ = BPF_STX_MEM(BPF_DW,
7530                                               si->dst_reg, si->src_reg,
7531                                               bpf_target_off(struct sk_buff,
7532                                                              tstamp, 8,
7533                                                              target_size));
7534                 else
7535                         *insn++ = BPF_LDX_MEM(BPF_DW,
7536                                               si->dst_reg, si->src_reg,
7537                                               bpf_target_off(struct sk_buff,
7538                                                              tstamp, 8,
7539                                                              target_size));
7540                 break;
7541 
7542         case offsetof(struct __sk_buff, gso_segs):
7543                 /* si->dst_reg = skb_shinfo(SKB); */
7544 #ifdef NET_SKBUFF_DATA_USES_OFFSET
7545                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7546                                       BPF_REG_AX, si->src_reg,
7547                                       offsetof(struct sk_buff, end));
7548                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, head),
7549                                       si->dst_reg, si->src_reg,
7550                                       offsetof(struct sk_buff, head));
7551                 *insn++ = BPF_ALU64_REG(BPF_ADD, si->dst_reg, BPF_REG_AX);
7552 #else
7553                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, end),
7554                                       si->dst_reg, si->src_reg,
7555                                       offsetof(struct sk_buff, end));
7556 #endif
7557                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
7558                                       si->dst_reg, si->dst_reg,
7559                                       bpf_target_off(struct skb_shared_info,
7560                                                      gso_segs, 2,
7561                                                      target_size));
7562                 break;
7563         case offsetof(struct __sk_buff, wire_len):
7564                 BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, pkt_len) != 4);
7565 
7566                 off = si->off;
7567                 off -= offsetof(struct __sk_buff, wire_len);
7568                 off += offsetof(struct sk_buff, cb);
7569                 off += offsetof(struct qdisc_skb_cb, pkt_len);
7570                 *target_size = 4;
7571                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
7572                 break;
7573 
7574         case offsetof(struct __sk_buff, sk):
7575                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
7576                                       si->dst_reg, si->src_reg,
7577                                       offsetof(struct sk_buff, sk));
7578                 break;
7579         }
7580 
7581         return insn - insn_buf;
7582 }
7583 
7584 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
7585                                 const struct bpf_insn *si,
7586                                 struct bpf_insn *insn_buf,
7587                                 struct bpf_prog *prog, u32 *target_size)
7588 {
7589         struct bpf_insn *insn = insn_buf;
7590         int off;
7591 
7592         switch (si->off) {
7593         case offsetof(struct bpf_sock, bound_dev_if):
7594                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);
7595 
7596                 if (type == BPF_WRITE)
7597                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7598                                         offsetof(struct sock, sk_bound_dev_if));
7599                 else
7600                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7601                                       offsetof(struct sock, sk_bound_dev_if));
7602                 break;
7603 
7604         case offsetof(struct bpf_sock, mark):
7605                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);
7606 
7607                 if (type == BPF_WRITE)
7608                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7609                                         offsetof(struct sock, sk_mark));
7610                 else
7611                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7612                                       offsetof(struct sock, sk_mark));
7613                 break;
7614 
7615         case offsetof(struct bpf_sock, priority):
7616                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);
7617 
7618                 if (type == BPF_WRITE)
7619                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
7620                                         offsetof(struct sock, sk_priority));
7621                 else
7622                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7623                                       offsetof(struct sock, sk_priority));
7624                 break;
7625 
7626         case offsetof(struct bpf_sock, family):
7627                 *insn++ = BPF_LDX_MEM(
7628                         BPF_FIELD_SIZEOF(struct sock_common, skc_family),
7629                         si->dst_reg, si->src_reg,
7630                         bpf_target_off(struct sock_common,
7631                                        skc_family,
7632                                        FIELD_SIZEOF(struct sock_common,
7633                                                     skc_family),
7634                                        target_size));
7635                 break;
7636 
7637         case offsetof(struct bpf_sock, type):
7638                 BUILD_BUG_ON(HWEIGHT32(SK_FL_TYPE_MASK) != BITS_PER_BYTE * 2);
7639                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7640                                       offsetof(struct sock, __sk_flags_offset));
7641                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7642                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7643                 *target_size = 2;
7644                 break;
7645 
7646         case offsetof(struct bpf_sock, protocol):
7647                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7648                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
7649                                       offsetof(struct sock, __sk_flags_offset));
7650                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7651                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
7652                 *target_size = 1;
7653                 break;
7654 
7655         case offsetof(struct bpf_sock, src_ip4):
7656                 *insn++ = BPF_LDX_MEM(
7657                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7658                         bpf_target_off(struct sock_common, skc_rcv_saddr,
7659                                        FIELD_SIZEOF(struct sock_common,
7660                                                     skc_rcv_saddr),
7661                                        target_size));
7662                 break;
7663 
7664         case offsetof(struct bpf_sock, dst_ip4):
7665                 *insn++ = BPF_LDX_MEM(
7666                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7667                         bpf_target_off(struct sock_common, skc_daddr,
7668                                        FIELD_SIZEOF(struct sock_common,
7669                                                     skc_daddr),
7670                                        target_size));
7671                 break;
7672 
7673         case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
7674 #if IS_ENABLED(CONFIG_IPV6)
7675                 off = si->off;
7676                 off -= offsetof(struct bpf_sock, src_ip6[0]);
7677                 *insn++ = BPF_LDX_MEM(
7678                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7679                         bpf_target_off(
7680                                 struct sock_common,
7681                                 skc_v6_rcv_saddr.s6_addr32[0],
7682                                 FIELD_SIZEOF(struct sock_common,
7683                                              skc_v6_rcv_saddr.s6_addr32[0]),
7684                                 target_size) + off);
7685 #else
7686                 (void)off;
7687                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7688 #endif
7689                 break;
7690 
7691         case bpf_ctx_range_till(struct bpf_sock, dst_ip6[0], dst_ip6[3]):
7692 #if IS_ENABLED(CONFIG_IPV6)
7693                 off = si->off;
7694                 off -= offsetof(struct bpf_sock, dst_ip6[0]);
7695                 *insn++ = BPF_LDX_MEM(
7696                         BPF_SIZE(si->code), si->dst_reg, si->src_reg,
7697                         bpf_target_off(struct sock_common,
7698                                        skc_v6_daddr.s6_addr32[0],
7699                                        FIELD_SIZEOF(struct sock_common,
7700                                                     skc_v6_daddr.s6_addr32[0]),
7701                                        target_size) + off);
7702 #else
7703                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
7704                 *target_size = 4;
7705 #endif
7706                 break;
7707 
7708         case offsetof(struct bpf_sock, src_port):
7709                 *insn++ = BPF_LDX_MEM(
7710                         BPF_FIELD_SIZEOF(struct sock_common, skc_num),
7711                         si->dst_reg, si->src_reg,
7712                         bpf_target_off(struct sock_common, skc_num,
7713                                        FIELD_SIZEOF(struct sock_common,
7714                                                     skc_num),
7715                                        target_size));
7716                 break;
7717 
7718         case offsetof(struct bpf_sock, dst_port):
7719                 *insn++ = BPF_LDX_MEM(
7720                         BPF_FIELD_SIZEOF(struct sock_common, skc_dport),
7721                         si->dst_reg, si->src_reg,
7722                         bpf_target_off(struct sock_common, skc_dport,
7723                                        FIELD_SIZEOF(struct sock_common,
7724                                                     skc_dport),
7725                                        target_size));
7726                 break;
7727 
7728         case offsetof(struct bpf_sock, state):
7729                 *insn++ = BPF_LDX_MEM(
7730                         BPF_FIELD_SIZEOF(struct sock_common, skc_state),
7731                         si->dst_reg, si->src_reg,
7732                         bpf_target_off(struct sock_common, skc_state,
7733                                        FIELD_SIZEOF(struct sock_common,
7734                                                     skc_state),
7735                                        target_size));
7736                 break;
7737         }
7738 
7739         return insn - insn_buf;
7740 }
7741 
7742 static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
7743                                          const struct bpf_insn *si,
7744                                          struct bpf_insn *insn_buf,
7745                                          struct bpf_prog *prog, u32 *target_size)
7746 {
7747         struct bpf_insn *insn = insn_buf;
7748 
7749         switch (si->off) {
7750         case offsetof(struct __sk_buff, ifindex):
7751                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
7752                                       si->dst_reg, si->src_reg,
7753                                       offsetof(struct sk_buff, dev));
7754                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7755                                       bpf_target_off(struct net_device, ifindex, 4,
7756                                                      target_size));
7757                 break;
7758         default:
7759                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
7760                                               target_size);
7761         }
7762 
7763         return insn - insn_buf;
7764 }
7765 
7766 static u32 xdp_convert_ctx_access(enum bpf_access_type type,
7767                                   const struct bpf_insn *si,
7768                                   struct bpf_insn *insn_buf,
7769                                   struct bpf_prog *prog, u32 *target_size)
7770 {
7771         struct bpf_insn *insn = insn_buf;
7772 
7773         switch (si->off) {
7774         case offsetof(struct xdp_md, data):
7775                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
7776                                       si->dst_reg, si->src_reg,
7777                                       offsetof(struct xdp_buff, data));
7778                 break;
7779         case offsetof(struct xdp_md, data_meta):
7780                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
7781                                       si->dst_reg, si->src_reg,
7782                                       offsetof(struct xdp_buff, data_meta));
7783                 break;
7784         case offsetof(struct xdp_md, data_end):
7785                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
7786                                       si->dst_reg, si->src_reg,
7787                                       offsetof(struct xdp_buff, data_end));
7788                 break;
7789         case offsetof(struct xdp_md, ingress_ifindex):
7790                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7791                                       si->dst_reg, si->src_reg,
7792                                       offsetof(struct xdp_buff, rxq));
7793                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
7794                                       si->dst_reg, si->dst_reg,
7795                                       offsetof(struct xdp_rxq_info, dev));
7796                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7797                                       offsetof(struct net_device, ifindex));
7798                 break;
7799         case offsetof(struct xdp_md, rx_queue_index):
7800                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
7801                                       si->dst_reg, si->src_reg,
7802                                       offsetof(struct xdp_buff, rxq));
7803                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
7804                                       offsetof(struct xdp_rxq_info,
7805                                                queue_index));
7806                 break;
7807         }
7808 
7809         return insn - insn_buf;
7810 }
7811 
7812 /* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
7813  * context Structure, F is Field in context structure that contains a pointer
7814  * to Nested Structure of type NS that has the field NF.
7815  *
7816  * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
7817  * sure that SIZE is not greater than actual size of S.F.NF.
7818  *
7819  * If offset OFF is provided, the load happens from that offset relative to
7820  * offset of NF.
7821  */
7822 #define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)          \
7823         do {                                                                   \
7824                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
7825                                       si->src_reg, offsetof(S, F));            \
7826                 *insn++ = BPF_LDX_MEM(                                         \
7827                         SIZE, si->dst_reg, si->dst_reg,                        \
7828                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7829                                        target_size)                            \
7830                                 + OFF);                                        \
7831         } while (0)
7832 
7833 #define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)                              \
7834         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,                     \
7835                                              BPF_FIELD_SIZEOF(NS, NF), 0)
7836 
7837 /* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
7838  * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
7839  *
7840  * In addition it uses Temporary Field TF (member of struct S) as the 3rd
7841  * "register" since two registers available in convert_ctx_access are not
7842  * enough: we can't override neither SRC, since it contains value to store, nor
7843  * DST since it contains pointer to context that may be used by later
7844  * instructions. But we need a temporary place to save pointer to nested
7845  * structure whose field we want to store to.
7846  */
7847 #define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE, OFF, TF)          \
7848         do {                                                                   \
7849                 int tmp_reg = BPF_REG_9;                                       \
7850                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7851                         --tmp_reg;                                             \
7852                 if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)          \
7853                         --tmp_reg;                                             \
7854                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,            \
7855                                       offsetof(S, TF));                        \
7856                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,         \
7857                                       si->dst_reg, offsetof(S, F));            \
7858                 *insn++ = BPF_STX_MEM(SIZE, tmp_reg, si->src_reg,              \
7859                         bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),           \
7860                                        target_size)                            \
7861                                 + OFF);                                        \
7862                 *insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,            \
7863                                       offsetof(S, TF));                        \
7864         } while (0)
7865 
7866 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
7867                                                       TF)                      \
7868         do {                                                                   \
7869                 if (type == BPF_WRITE) {                                       \
7870                         SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, SIZE,   \
7871                                                          OFF, TF);             \
7872                 } else {                                                       \
7873                         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(                  \
7874                                 S, NS, F, NF, SIZE, OFF);  \
7875                 }                                                              \
7876         } while (0)
7877 
7878 #define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)                 \
7879         SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(                         \
7880                 S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)
7881 
7882 static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
7883                                         const struct bpf_insn *si,
7884                                         struct bpf_insn *insn_buf,
7885                                         struct bpf_prog *prog, u32 *target_size)
7886 {
7887         struct bpf_insn *insn = insn_buf;
7888         int off;
7889 
7890         switch (si->off) {
7891         case offsetof(struct bpf_sock_addr, user_family):
7892                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7893                                             struct sockaddr, uaddr, sa_family);
7894                 break;
7895 
7896         case offsetof(struct bpf_sock_addr, user_ip4):
7897                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7898                         struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
7899                         sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
7900                 break;
7901 
7902         case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
7903                 off = si->off;
7904                 off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
7905                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7906                         struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
7907                         sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
7908                         tmp_reg);
7909                 break;
7910 
7911         case offsetof(struct bpf_sock_addr, user_port):
7912                 /* To get port we need to know sa_family first and then treat
7913                  * sockaddr as either sockaddr_in or sockaddr_in6.
7914                  * Though we can simplify since port field has same offset and
7915                  * size in both structures.
7916                  * Here we check this invariant and use just one of the
7917                  * structures if it's true.
7918                  */
7919                 BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
7920                              offsetof(struct sockaddr_in6, sin6_port));
7921                 BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
7922                              FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
7923                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
7924                                                      struct sockaddr_in6, uaddr,
7925                                                      sin6_port, tmp_reg);
7926                 break;
7927 
7928         case offsetof(struct bpf_sock_addr, family):
7929                 SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
7930                                             struct sock, sk, sk_family);
7931                 break;
7932 
7933         case offsetof(struct bpf_sock_addr, type):
7934                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7935                         struct bpf_sock_addr_kern, struct sock, sk,
7936                         __sk_flags_offset, BPF_W, 0);
7937                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
7938                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
7939                 break;
7940 
7941         case offsetof(struct bpf_sock_addr, protocol):
7942                 SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
7943                         struct bpf_sock_addr_kern, struct sock, sk,
7944                         __sk_flags_offset, BPF_W, 0);
7945                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
7946                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
7947                                         SK_FL_PROTO_SHIFT);
7948                 break;
7949 
7950         case offsetof(struct bpf_sock_addr, msg_src_ip4):
7951                 /* Treat t_ctx as struct in_addr for msg_src_ip4. */
7952                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7953                         struct bpf_sock_addr_kern, struct in_addr, t_ctx,
7954                         s_addr, BPF_SIZE(si->code), 0, tmp_reg);
7955                 break;
7956 
7957         case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
7958                                 msg_src_ip6[3]):
7959                 off = si->off;
7960                 off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
7961                 /* Treat t_ctx as struct in6_addr for msg_src_ip6. */
7962                 SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
7963                         struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
7964                         s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
7965                 break;
7966         case offsetof(struct bpf_sock_addr, sk):
7967                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sock_addr_kern, sk),
7968                                       si->dst_reg, si->src_reg,
7969                                       offsetof(struct bpf_sock_addr_kern, sk));
7970                 break;
7971         }
7972 
7973         return insn - insn_buf;
7974 }
7975 
7976 static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
7977                                        const struct bpf_insn *si,
7978                                        struct bpf_insn *insn_buf,
7979                                        struct bpf_prog *prog,
7980                                        u32 *target_size)
7981 {
7982         struct bpf_insn *insn = insn_buf;
7983         int off;
7984 
7985 /* Helper macro for adding read access to tcp_sock or sock fields. */
7986 #define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
7987         do {                                                                  \
7988                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
7989                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
7990                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7991                                                 struct bpf_sock_ops_kern,     \
7992                                                 is_fullsock),                 \
7993                                       si->dst_reg, si->src_reg,               \
7994                                       offsetof(struct bpf_sock_ops_kern,      \
7995                                                is_fullsock));                 \
7996                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);            \
7997                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
7998                                                 struct bpf_sock_ops_kern, sk),\
7999                                       si->dst_reg, si->src_reg,               \
8000                                       offsetof(struct bpf_sock_ops_kern, sk));\
8001                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,                   \
8002                                                        OBJ_FIELD),            \
8003                                       si->dst_reg, si->dst_reg,               \
8004                                       offsetof(OBJ, OBJ_FIELD));              \
8005         } while (0)
8006 
8007 #define SOCK_OPS_GET_TCP_SOCK_FIELD(FIELD) \
8008                 SOCK_OPS_GET_FIELD(FIELD, FIELD, struct tcp_sock)
8009 
8010 /* Helper macro for adding write access to tcp_sock or sock fields.
8011  * The macro is called with two registers, dst_reg which contains a pointer
8012  * to ctx (context) and src_reg which contains the value that should be
8013  * stored. However, we need an additional register since we cannot overwrite
8014  * dst_reg because it may be used later in the program.
8015  * Instead we "borrow" one of the other register. We first save its value
8016  * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
8017  * it at the end of the macro.
8018  */
8019 #define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)                         \
8020         do {                                                                  \
8021                 int reg = BPF_REG_9;                                          \
8022                 BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >                   \
8023                              FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
8024                 if (si->dst_reg == reg || si->src_reg == reg)                 \
8025                         reg--;                                                \
8026                 if (si->dst_reg == reg || si->src_reg == reg)                 \
8027                         reg--;                                                \
8028                 *insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,               \
8029                                       offsetof(struct bpf_sock_ops_kern,      \
8030                                                temp));                        \
8031                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8032                                                 struct bpf_sock_ops_kern,     \
8033                                                 is_fullsock),                 \
8034                                       reg, si->dst_reg,                       \
8035                                       offsetof(struct bpf_sock_ops_kern,      \
8036                                                is_fullsock));                 \
8037                 *insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);                    \
8038                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(                       \
8039                                                 struct bpf_sock_ops_kern, sk),\
8040                                       reg, si->dst_reg,                       \
8041                                       offsetof(struct bpf_sock_ops_kern, sk));\
8042                 *insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),       \
8043                                       reg, si->src_reg,                       \
8044                                       offsetof(OBJ, OBJ_FIELD));              \
8045                 *insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,               \
8046                                       offsetof(struct bpf_sock_ops_kern,      \
8047                                                temp));                        \
8048         } while (0)
8049 
8050 #define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)            \
8051         do {                                                                  \
8052                 if (TYPE == BPF_WRITE)                                        \
8053                         SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
8054                 else                                                          \
8055                         SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);        \
8056         } while (0)
8057 
8058         if (insn > insn_buf)
8059                 return insn - insn_buf;
8060 
8061         switch (si->off) {
8062         case offsetof(struct bpf_sock_ops, op) ...
8063              offsetof(struct bpf_sock_ops, replylong[3]):
8064                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
8065                              FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
8066                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
8067                              FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
8068                 BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
8069                              FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
8070                 off = si->off;
8071                 off -= offsetof(struct bpf_sock_ops, op);
8072                 off += offsetof(struct bpf_sock_ops_kern, op);
8073                 if (type == BPF_WRITE)
8074                         *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
8075                                               off);
8076                 else
8077                         *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
8078                                               off);
8079                 break;
8080 
8081         case offsetof(struct bpf_sock_ops, family):
8082                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
8083 
8084                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8085                                               struct bpf_sock_ops_kern, sk),
8086                                       si->dst_reg, si->src_reg,
8087                                       offsetof(struct bpf_sock_ops_kern, sk));
8088                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8089                                       offsetof(struct sock_common, skc_family));
8090                 break;
8091 
8092         case offsetof(struct bpf_sock_ops, remote_ip4):
8093                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
8094 
8095                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8096                                                 struct bpf_sock_ops_kern, sk),
8097                                       si->dst_reg, si->src_reg,
8098                                       offsetof(struct bpf_sock_ops_kern, sk));
8099                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8100                                       offsetof(struct sock_common, skc_daddr));
8101                 break;
8102 
8103         case offsetof(struct bpf_sock_ops, local_ip4):
8104                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8105                                           skc_rcv_saddr) != 4);
8106 
8107                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8108                                               struct bpf_sock_ops_kern, sk),
8109                                       si->dst_reg, si->src_reg,
8110                                       offsetof(struct bpf_sock_ops_kern, sk));
8111                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8112                                       offsetof(struct sock_common,
8113                                                skc_rcv_saddr));
8114                 break;
8115 
8116         case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
8117              offsetof(struct bpf_sock_ops, remote_ip6[3]):
8118 #if IS_ENABLED(CONFIG_IPV6)
8119                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8120                                           skc_v6_daddr.s6_addr32[0]) != 4);
8121 
8122                 off = si->off;
8123                 off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
8124                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8125                                                 struct bpf_sock_ops_kern, sk),
8126                                       si->dst_reg, si->src_reg,
8127                                       offsetof(struct bpf_sock_ops_kern, sk));
8128                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8129                                       offsetof(struct sock_common,
8130                                                skc_v6_daddr.s6_addr32[0]) +
8131                                       off);
8132 #else
8133                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8134 #endif
8135                 break;
8136 
8137         case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
8138              offsetof(struct bpf_sock_ops, local_ip6[3]):
8139 #if IS_ENABLED(CONFIG_IPV6)
8140                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8141                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8142 
8143                 off = si->off;
8144                 off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
8145                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8146                                                 struct bpf_sock_ops_kern, sk),
8147                                       si->dst_reg, si->src_reg,
8148                                       offsetof(struct bpf_sock_ops_kern, sk));
8149                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8150                                       offsetof(struct sock_common,
8151                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8152                                       off);
8153 #else
8154                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8155 #endif
8156                 break;
8157 
8158         case offsetof(struct bpf_sock_ops, remote_port):
8159                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8160 
8161                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8162                                                 struct bpf_sock_ops_kern, sk),
8163                                       si->dst_reg, si->src_reg,
8164                                       offsetof(struct bpf_sock_ops_kern, sk));
8165                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8166                                       offsetof(struct sock_common, skc_dport));
8167 #ifndef __BIG_ENDIAN_BITFIELD
8168                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8169 #endif
8170                 break;
8171 
8172         case offsetof(struct bpf_sock_ops, local_port):
8173                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8174 
8175                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8176                                                 struct bpf_sock_ops_kern, sk),
8177                                       si->dst_reg, si->src_reg,
8178                                       offsetof(struct bpf_sock_ops_kern, sk));
8179                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8180                                       offsetof(struct sock_common, skc_num));
8181                 break;
8182 
8183         case offsetof(struct bpf_sock_ops, is_fullsock):
8184                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8185                                                 struct bpf_sock_ops_kern,
8186                                                 is_fullsock),
8187                                       si->dst_reg, si->src_reg,
8188                                       offsetof(struct bpf_sock_ops_kern,
8189                                                is_fullsock));
8190                 break;
8191 
8192         case offsetof(struct bpf_sock_ops, state):
8193                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);
8194 
8195                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8196                                                 struct bpf_sock_ops_kern, sk),
8197                                       si->dst_reg, si->src_reg,
8198                                       offsetof(struct bpf_sock_ops_kern, sk));
8199                 *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
8200                                       offsetof(struct sock_common, skc_state));
8201                 break;
8202 
8203         case offsetof(struct bpf_sock_ops, rtt_min):
8204                 BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
8205                              sizeof(struct minmax));
8206                 BUILD_BUG_ON(sizeof(struct minmax) <
8207                              sizeof(struct minmax_sample));
8208 
8209                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8210                                                 struct bpf_sock_ops_kern, sk),
8211                                       si->dst_reg, si->src_reg,
8212                                       offsetof(struct bpf_sock_ops_kern, sk));
8213                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8214                                       offsetof(struct tcp_sock, rtt_min) +
8215                                       FIELD_SIZEOF(struct minmax_sample, t));
8216                 break;
8217 
8218         case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
8219                 SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
8220                                    struct tcp_sock);
8221                 break;
8222 
8223         case offsetof(struct bpf_sock_ops, sk_txhash):
8224                 SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
8225                                           struct sock, type);
8226                 break;
8227         case offsetof(struct bpf_sock_ops, snd_cwnd):
8228                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_cwnd);
8229                 break;
8230         case offsetof(struct bpf_sock_ops, srtt_us):
8231                 SOCK_OPS_GET_TCP_SOCK_FIELD(srtt_us);
8232                 break;
8233         case offsetof(struct bpf_sock_ops, snd_ssthresh):
8234                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_ssthresh);
8235                 break;
8236         case offsetof(struct bpf_sock_ops, rcv_nxt):
8237                 SOCK_OPS_GET_TCP_SOCK_FIELD(rcv_nxt);
8238                 break;
8239         case offsetof(struct bpf_sock_ops, snd_nxt):
8240                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_nxt);
8241                 break;
8242         case offsetof(struct bpf_sock_ops, snd_una):
8243                 SOCK_OPS_GET_TCP_SOCK_FIELD(snd_una);
8244                 break;
8245         case offsetof(struct bpf_sock_ops, mss_cache):
8246                 SOCK_OPS_GET_TCP_SOCK_FIELD(mss_cache);
8247                 break;
8248         case offsetof(struct bpf_sock_ops, ecn_flags):
8249                 SOCK_OPS_GET_TCP_SOCK_FIELD(ecn_flags);
8250                 break;
8251         case offsetof(struct bpf_sock_ops, rate_delivered):
8252                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_delivered);
8253                 break;
8254         case offsetof(struct bpf_sock_ops, rate_interval_us):
8255                 SOCK_OPS_GET_TCP_SOCK_FIELD(rate_interval_us);
8256                 break;
8257         case offsetof(struct bpf_sock_ops, packets_out):
8258                 SOCK_OPS_GET_TCP_SOCK_FIELD(packets_out);
8259                 break;
8260         case offsetof(struct bpf_sock_ops, retrans_out):
8261                 SOCK_OPS_GET_TCP_SOCK_FIELD(retrans_out);
8262                 break;
8263         case offsetof(struct bpf_sock_ops, total_retrans):
8264                 SOCK_OPS_GET_TCP_SOCK_FIELD(total_retrans);
8265                 break;
8266         case offsetof(struct bpf_sock_ops, segs_in):
8267                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_in);
8268                 break;
8269         case offsetof(struct bpf_sock_ops, data_segs_in):
8270                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_in);
8271                 break;
8272         case offsetof(struct bpf_sock_ops, segs_out):
8273                 SOCK_OPS_GET_TCP_SOCK_FIELD(segs_out);
8274                 break;
8275         case offsetof(struct bpf_sock_ops, data_segs_out):
8276                 SOCK_OPS_GET_TCP_SOCK_FIELD(data_segs_out);
8277                 break;
8278         case offsetof(struct bpf_sock_ops, lost_out):
8279                 SOCK_OPS_GET_TCP_SOCK_FIELD(lost_out);
8280                 break;
8281         case offsetof(struct bpf_sock_ops, sacked_out):
8282                 SOCK_OPS_GET_TCP_SOCK_FIELD(sacked_out);
8283                 break;
8284         case offsetof(struct bpf_sock_ops, bytes_received):
8285                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_received);
8286                 break;
8287         case offsetof(struct bpf_sock_ops, bytes_acked):
8288                 SOCK_OPS_GET_TCP_SOCK_FIELD(bytes_acked);
8289                 break;
8290         case offsetof(struct bpf_sock_ops, sk):
8291                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8292                                                 struct bpf_sock_ops_kern,
8293                                                 is_fullsock),
8294                                       si->dst_reg, si->src_reg,
8295                                       offsetof(struct bpf_sock_ops_kern,
8296                                                is_fullsock));
8297                 *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
8298                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8299                                                 struct bpf_sock_ops_kern, sk),
8300                                       si->dst_reg, si->src_reg,
8301                                       offsetof(struct bpf_sock_ops_kern, sk));
8302                 break;
8303         }
8304         return insn - insn_buf;
8305 }
8306 
8307 static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
8308                                      const struct bpf_insn *si,
8309                                      struct bpf_insn *insn_buf,
8310                                      struct bpf_prog *prog, u32 *target_size)
8311 {
8312         struct bpf_insn *insn = insn_buf;
8313         int off;
8314 
8315         switch (si->off) {
8316         case offsetof(struct __sk_buff, data_end):
8317                 off  = si->off;
8318                 off -= offsetof(struct __sk_buff, data_end);
8319                 off += offsetof(struct sk_buff, cb);
8320                 off += offsetof(struct tcp_skb_cb, bpf.data_end);
8321                 *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
8322                                       si->src_reg, off);
8323                 break;
8324         default:
8325                 return bpf_convert_ctx_access(type, si, insn_buf, prog,
8326                                               target_size);
8327         }
8328 
8329         return insn - insn_buf;
8330 }
8331 
8332 static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
8333                                      const struct bpf_insn *si,
8334                                      struct bpf_insn *insn_buf,
8335                                      struct bpf_prog *prog, u32 *target_size)
8336 {
8337         struct bpf_insn *insn = insn_buf;
8338 #if IS_ENABLED(CONFIG_IPV6)
8339         int off;
8340 #endif
8341 
8342         /* convert ctx uses the fact sg element is first in struct */
8343         BUILD_BUG_ON(offsetof(struct sk_msg, sg) != 0);
8344 
8345         switch (si->off) {
8346         case offsetof(struct sk_msg_md, data):
8347                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data),
8348                                       si->dst_reg, si->src_reg,
8349                                       offsetof(struct sk_msg, data));
8350                 break;
8351         case offsetof(struct sk_msg_md, data_end):
8352                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg, data_end),
8353                                       si->dst_reg, si->src_reg,
8354                                       offsetof(struct sk_msg, data_end));
8355                 break;
8356         case offsetof(struct sk_msg_md, family):
8357                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);
8358 
8359                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8360                                               struct sk_msg, sk),
8361                                       si->dst_reg, si->src_reg,
8362                                       offsetof(struct sk_msg, sk));
8363                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8364                                       offsetof(struct sock_common, skc_family));
8365                 break;
8366 
8367         case offsetof(struct sk_msg_md, remote_ip4):
8368                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);
8369 
8370                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8371                                                 struct sk_msg, sk),
8372                                       si->dst_reg, si->src_reg,
8373                                       offsetof(struct sk_msg, sk));
8374                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8375                                       offsetof(struct sock_common, skc_daddr));
8376                 break;
8377 
8378         case offsetof(struct sk_msg_md, local_ip4):
8379                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8380                                           skc_rcv_saddr) != 4);
8381 
8382                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8383                                               struct sk_msg, sk),
8384                                       si->dst_reg, si->src_reg,
8385                                       offsetof(struct sk_msg, sk));
8386                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8387                                       offsetof(struct sock_common,
8388                                                skc_rcv_saddr));
8389                 break;
8390 
8391         case offsetof(struct sk_msg_md, remote_ip6[0]) ...
8392              offsetof(struct sk_msg_md, remote_ip6[3]):
8393 #if IS_ENABLED(CONFIG_IPV6)
8394                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8395                                           skc_v6_daddr.s6_addr32[0]) != 4);
8396 
8397                 off = si->off;
8398                 off -= offsetof(struct sk_msg_md, remote_ip6[0]);
8399                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8400                                                 struct sk_msg, sk),
8401                                       si->dst_reg, si->src_reg,
8402                                       offsetof(struct sk_msg, sk));
8403                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8404                                       offsetof(struct sock_common,
8405                                                skc_v6_daddr.s6_addr32[0]) +
8406                                       off);
8407 #else
8408                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8409 #endif
8410                 break;
8411 
8412         case offsetof(struct sk_msg_md, local_ip6[0]) ...
8413              offsetof(struct sk_msg_md, local_ip6[3]):
8414 #if IS_ENABLED(CONFIG_IPV6)
8415                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
8416                                           skc_v6_rcv_saddr.s6_addr32[0]) != 4);
8417 
8418                 off = si->off;
8419                 off -= offsetof(struct sk_msg_md, local_ip6[0]);
8420                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8421                                                 struct sk_msg, sk),
8422                                       si->dst_reg, si->src_reg,
8423                                       offsetof(struct sk_msg, sk));
8424                 *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
8425                                       offsetof(struct sock_common,
8426                                                skc_v6_rcv_saddr.s6_addr32[0]) +
8427                                       off);
8428 #else
8429                 *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
8430 #endif
8431                 break;
8432 
8433         case offsetof(struct sk_msg_md, remote_port):
8434                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);
8435 
8436                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8437                                                 struct sk_msg, sk),
8438                                       si->dst_reg, si->src_reg,
8439                                       offsetof(struct sk_msg, sk));
8440                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8441                                       offsetof(struct sock_common, skc_dport));
8442 #ifndef __BIG_ENDIAN_BITFIELD
8443                 *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
8444 #endif
8445                 break;
8446 
8447         case offsetof(struct sk_msg_md, local_port):
8448                 BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);
8449 
8450                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
8451                                                 struct sk_msg, sk),
8452                                       si->dst_reg, si->src_reg,
8453                                       offsetof(struct sk_msg, sk));
8454                 *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
8455                                       offsetof(struct sock_common, skc_num));
8456                 break;
8457 
8458         case offsetof(struct sk_msg_md, size):
8459                 *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_sg, size),
8460                                       si->dst_reg, si->src_reg,
8461                                       offsetof(struct sk_msg_sg, size));
8462                 break;
8463         }
8464 
8465         return insn - insn_buf;
8466 }
8467 
8468 const struct bpf_verifier_ops sk_filter_verifier_ops = {
8469         .get_func_proto         = sk_filter_func_proto,
8470         .is_valid_access        = sk_filter_is_valid_access,
8471         .convert_ctx_access     = bpf_convert_ctx_access,
8472         .gen_ld_abs             = bpf_gen_ld_abs,
8473 };
8474 
8475 const struct bpf_prog_ops sk_filter_prog_ops = {
8476         .test_run               = bpf_prog_test_run_skb,
8477 };
8478 
8479 const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
8480         .get_func_proto         = tc_cls_act_func_proto,
8481         .is_valid_access        = tc_cls_act_is_valid_access,
8482         .convert_ctx_access     = tc_cls_act_convert_ctx_access,
8483         .gen_prologue           = tc_cls_act_prologue,
8484         .gen_ld_abs             = bpf_gen_ld_abs,
8485 };
8486 
8487 const struct bpf_prog_ops tc_cls_act_prog_ops = {
8488         .test_run               = bpf_prog_test_run_skb,
8489 };
8490 
8491 const struct bpf_verifier_ops xdp_verifier_ops = {
8492         .get_func_proto         = xdp_func_proto,
8493         .is_valid_access        = xdp_is_valid_access,
8494         .convert_ctx_access     = xdp_convert_ctx_access,
8495         .gen_prologue           = bpf_noop_prologue,
8496 };
8497 
8498 const struct bpf_prog_ops xdp_prog_ops = {
8499         .test_run               = bpf_prog_test_run_xdp,
8500 };
8501 
8502 const struct bpf_verifier_ops cg_skb_verifier_ops = {
8503         .get_func_proto         = cg_skb_func_proto,
8504         .is_valid_access        = cg_skb_is_valid_access,
8505         .convert_ctx_access     = bpf_convert_ctx_access,
8506 };
8507 
8508 const struct bpf_prog_ops cg_skb_prog_ops = {
8509         .test_run               = bpf_prog_test_run_skb,
8510 };
8511 
8512 const struct bpf_verifier_ops lwt_in_verifier_ops = {
8513         .get_func_proto         = lwt_in_func_proto,
8514         .is_valid_access        = lwt_is_valid_access,
8515         .convert_ctx_access     = bpf_convert_ctx_access,
8516 };
8517 
8518 const struct bpf_prog_ops lwt_in_prog_ops = {
8519         .test_run               = bpf_prog_test_run_skb,
8520 };
8521 
8522 const struct bpf_verifier_ops lwt_out_verifier_ops = {
8523         .get_func_proto         = lwt_out_func_proto,
8524         .is_valid_access        = lwt_is_valid_access,
8525         .convert_ctx_access     = bpf_convert_ctx_access,
8526 };
8527 
8528 const struct bpf_prog_ops lwt_out_prog_ops = {
8529         .test_run               = bpf_prog_test_run_skb,
8530 };
8531 
8532 const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
8533         .get_func_proto         = lwt_xmit_func_proto,
8534         .is_valid_access        = lwt_is_valid_access,
8535         .convert_ctx_access     = bpf_convert_ctx_access,
8536         .gen_prologue           = tc_cls_act_prologue,
8537 };
8538 
8539 const struct bpf_prog_ops lwt_xmit_prog_ops = {
8540         .test_run               = bpf_prog_test_run_skb,
8541 };
8542 
8543 const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
8544         .get_func_proto         = lwt_seg6local_func_proto,
8545         .is_valid_access        = lwt_is_valid_access,
8546         .convert_ctx_access     = bpf_convert_ctx_access,
8547 };
8548 
8549 const struct bpf_prog_ops lwt_seg6local_prog_ops = {
8550         .test_run               = bpf_prog_test_run_skb,
8551 };
8552 
8553 const struct bpf_verifier_ops cg_sock_verifier_ops = {
8554         .get_func_proto         = sock_filter_func_proto,
8555         .is_valid_access        = sock_filter_is_valid_access,
8556         .convert_ctx_access     = bpf_sock_convert_ctx_access,
8557 };
8558 
8559 const struct bpf_prog_ops cg_sock_prog_ops = {
8560 };
8561 
8562 const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
8563         .get_func_proto         = sock_addr_func_proto,
8564         .is_valid_access        = sock_addr_is_valid_access,
8565         .convert_ctx_access     = sock_addr_convert_ctx_access,
8566 };
8567 
8568 const struct bpf_prog_ops cg_sock_addr_prog_ops = {
8569 };
8570 
8571 const struct bpf_verifier_ops sock_ops_verifier_ops = {
8572         .get_func_proto         = sock_ops_func_proto,
8573         .is_valid_access        = sock_ops_is_valid_access,
8574         .convert_ctx_access     = sock_ops_convert_ctx_access,
8575 };
8576 
8577 const struct bpf_prog_ops sock_ops_prog_ops = {
8578 };
8579 
8580 const struct bpf_verifier_ops sk_skb_verifier_ops = {
8581         .get_func_proto         = sk_skb_func_proto,
8582         .is_valid_access        = sk_skb_is_valid_access,
8583         .convert_ctx_access     = sk_skb_convert_ctx_access,
8584         .gen_prologue           = sk_skb_prologue,
8585 };
8586 
8587 const struct bpf_prog_ops sk_skb_prog_ops = {
8588 };
8589 
8590 const struct bpf_verifier_ops sk_msg_verifier_ops = {
8591         .get_func_proto         = sk_msg_func_proto,
8592         .is_valid_access        = sk_msg_is_valid_access,
8593         .convert_ctx_access     = sk_msg_convert_ctx_access,
8594         .gen_prologue           = bpf_noop_prologue,
8595 };
8596 
8597 const struct bpf_prog_ops sk_msg_prog_ops = {
8598 };
8599 
8600 const struct bpf_verifier_ops flow_dissector_verifier_ops = {
8601         .get_func_proto         = flow_dissector_func_proto,
8602         .is_valid_access        = flow_dissector_is_valid_access,
8603         .convert_ctx_access     = flow_dissector_convert_ctx_access,
8604 };
8605 
8606 const struct bpf_prog_ops flow_dissector_prog_ops = {
8607         .test_run               = bpf_prog_test_run_flow_dissector,
8608 };
8609 
8610 int sk_detach_filter(struct sock *sk)
8611 {
8612         int ret = -ENOENT;
8613         struct sk_filter *filter;
8614 
8615         if (sock_flag(sk, SOCK_FILTER_LOCKED))
8616                 return -EPERM;
8617 
8618         filter = rcu_dereference_protected(sk->sk_filter,
8619                                            lockdep_sock_is_held(sk));
8620         if (filter) {
8621                 RCU_INIT_POINTER(sk->sk_filter, NULL);
8622                 sk_filter_uncharge(sk, filter);
8623                 ret = 0;
8624         }
8625 
8626         return ret;
8627 }
8628 EXPORT_SYMBOL_GPL(sk_detach_filter);
8629 
8630 int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
8631                   unsigned int len)
8632 {
8633         struct sock_fprog_kern *fprog;
8634         struct sk_filter *filter;
8635         int ret = 0;
8636 
8637         lock_sock(sk);
8638         filter = rcu_dereference_protected(sk->sk_filter,
8639                                            lockdep_sock_is_held(sk));
8640         if (!filter)
8641                 goto out;
8642 
8643         /* We're copying the filter that has been originally attached,
8644          * so no conversion/decode needed anymore. eBPF programs that
8645          * have no original program cannot be dumped through this.
8646          */
8647         ret = -EACCES;
8648         fprog = filter->prog->orig_prog;
8649         if (!fprog)
8650                 goto out;
8651 
8652         ret = fprog->len;
8653         if (!len)
8654                 /* User space only enquires number of filter blocks. */
8655                 goto out;
8656 
8657         ret = -EINVAL;
8658         if (len < fprog->len)
8659                 goto out;
8660 
8661         ret = -EFAULT;
8662         if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
8663                 goto out;
8664 
8665         /* Instead of bytes, the API requests to return the number
8666          * of filter blocks.
8667          */
8668         ret = fprog->len;
8669 out:
8670         release_sock(sk);
8671         return ret;
8672 }
8673 
8674 #ifdef CONFIG_INET
8675 struct sk_reuseport_kern {
8676         struct sk_buff *skb;
8677         struct sock *sk;
8678         struct sock *selected_sk;
8679         void *data_end;
8680         u32 hash;
8681         u32 reuseport_id;
8682         bool bind_inany;
8683 };
8684 
8685 static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
8686                                     struct sock_reuseport *reuse,
8687                                     struct sock *sk, struct sk_buff *skb,
8688                                     u32 hash)
8689 {
8690         reuse_kern->skb = skb;
8691         reuse_kern->sk = sk;
8692         reuse_kern->selected_sk = NULL;
8693         reuse_kern->data_end = skb->data + skb_headlen(skb);
8694         reuse_kern->hash = hash;
8695         reuse_kern->reuseport_id = reuse->reuseport_id;
8696         reuse_kern->bind_inany = reuse->bind_inany;
8697 }
8698 
8699 struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
8700                                   struct bpf_prog *prog, struct sk_buff *skb,
8701                                   u32 hash)
8702 {
8703         struct sk_reuseport_kern reuse_kern;
8704         enum sk_action action;
8705 
8706         bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
8707         action = BPF_PROG_RUN(prog, &reuse_kern);
8708 
8709         if (action == SK_PASS)
8710                 return reuse_kern.selected_sk;
8711         else
8712                 return ERR_PTR(-ECONNREFUSED);
8713 }
8714 
8715 BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
8716            struct bpf_map *, map, void *, key, u32, flags)
8717 {
8718         struct sock_reuseport *reuse;
8719         struct sock *selected_sk;
8720 
8721         selected_sk = map->ops->map_lookup_elem(map, key);
8722         if (!selected_sk)
8723                 return -ENOENT;
8724 
8725         reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
8726         if (!reuse)
8727                 /* selected_sk is unhashed (e.g. by close()) after the
8728                  * above map_lookup_elem().  Treat selected_sk has already
8729                  * been removed from the map.
8730                  */
8731                 return -ENOENT;
8732 
8733         if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
8734                 struct sock *sk;
8735 
8736                 if (unlikely(!reuse_kern->reuseport_id))
8737                         /* There is a small race between adding the
8738                          * sk to the map and setting the
8739                          * reuse_kern->reuseport_id.
8740                          * Treat it as the sk has not been added to
8741                          * the bpf map yet.
8742                          */
8743                         return -ENOENT;
8744 
8745                 sk = reuse_kern->sk;
8746                 if (sk->sk_protocol != selected_sk->sk_protocol)
8747                         return -EPROTOTYPE;
8748                 else if (sk->sk_family != selected_sk->sk_family)
8749                         return -EAFNOSUPPORT;
8750 
8751                 /* Catch all. Likely bound to a different sockaddr. */
8752                 return -EBADFD;
8753         }
8754 
8755         reuse_kern->selected_sk = selected_sk;
8756 
8757         return 0;
8758 }
8759 
8760 static const struct bpf_func_proto sk_select_reuseport_proto = {
8761         .func           = sk_select_reuseport,
8762         .gpl_only       = false,
8763         .ret_type       = RET_INTEGER,
8764         .arg1_type      = ARG_PTR_TO_CTX,
8765         .arg2_type      = ARG_CONST_MAP_PTR,
8766         .arg3_type      = ARG_PTR_TO_MAP_KEY,
8767         .arg4_type      = ARG_ANYTHING,
8768 };
8769 
8770 BPF_CALL_4(sk_reuseport_load_bytes,
8771            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8772            void *, to, u32, len)
8773 {
8774         return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
8775 }
8776 
8777 static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
8778         .func           = sk_reuseport_load_bytes,
8779         .gpl_only       = false,
8780         .ret_type       = RET_INTEGER,
8781         .arg1_type      = ARG_PTR_TO_CTX,
8782         .arg2_type      = ARG_ANYTHING,
8783         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8784         .arg4_type      = ARG_CONST_SIZE,
8785 };
8786 
8787 BPF_CALL_5(sk_reuseport_load_bytes_relative,
8788            const struct sk_reuseport_kern *, reuse_kern, u32, offset,
8789            void *, to, u32, len, u32, start_header)
8790 {
8791         return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
8792                                                len, start_header);
8793 }
8794 
8795 static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
8796         .func           = sk_reuseport_load_bytes_relative,
8797         .gpl_only       = false,
8798         .ret_type       = RET_INTEGER,
8799         .arg1_type      = ARG_PTR_TO_CTX,
8800         .arg2_type      = ARG_ANYTHING,
8801         .arg3_type      = ARG_PTR_TO_UNINIT_MEM,
8802         .arg4_type      = ARG_CONST_SIZE,
8803         .arg5_type      = ARG_ANYTHING,
8804 };
8805 
8806 static const struct bpf_func_proto *
8807 sk_reuseport_func_proto(enum bpf_func_id func_id,
8808                         const struct bpf_prog *prog)
8809 {
8810         switch (func_id) {
8811         case BPF_FUNC_sk_select_reuseport:
8812                 return &sk_select_reuseport_proto;
8813         case BPF_FUNC_skb_load_bytes:
8814                 return &sk_reuseport_load_bytes_proto;
8815         case BPF_FUNC_skb_load_bytes_relative:
8816                 return &sk_reuseport_load_bytes_relative_proto;
8817         default:
8818                 return bpf_base_func_proto(func_id);
8819         }
8820 }
8821 
8822 static bool
8823 sk_reuseport_is_valid_access(int off, int size,
8824                              enum bpf_access_type type,
8825                              const struct bpf_prog *prog,
8826                              struct bpf_insn_access_aux *info)
8827 {
8828         const u32 size_default = sizeof(__u32);
8829 
8830         if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
8831             off % size || type != BPF_READ)
8832                 return false;
8833 
8834         switch (off) {
8835         case offsetof(struct sk_reuseport_md, data):
8836                 info->reg_type = PTR_TO_PACKET;
8837                 return size == sizeof(__u64);
8838 
8839         case offsetof(struct sk_reuseport_md, data_end):
8840                 info->reg_type = PTR_TO_PACKET_END;
8841                 return size == sizeof(__u64);
8842 
8843         case offsetof(struct sk_reuseport_md, hash):
8844                 return size == size_default;
8845 
8846         /* Fields that allow narrowing */
8847         case bpf_ctx_range(struct sk_reuseport_md, eth_protocol):
8848                 if (size < FIELD_SIZEOF(struct sk_buff, protocol))
8849                         return false;
8850                 /* fall through */
8851         case bpf_ctx_range(struct sk_reuseport_md, ip_protocol):
8852         case bpf_ctx_range(struct sk_reuseport_md, bind_inany):
8853         case bpf_ctx_range(struct sk_reuseport_md, len):
8854                 bpf_ctx_record_field_size(info, size_default);
8855                 return bpf_ctx_narrow_access_ok(off, size, size_default);
8856 
8857         default:
8858                 return false;
8859         }
8860 }
8861 
8862 #define SK_REUSEPORT_LOAD_FIELD(F) ({                                   \
8863         *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8864                               si->dst_reg, si->src_reg,                 \
8865                               bpf_target_off(struct sk_reuseport_kern, F, \
8866                                              FIELD_SIZEOF(struct sk_reuseport_kern, F), \
8867                                              target_size));             \
8868         })
8869 
8870 #define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)                          \
8871         SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,           \
8872                                     struct sk_buff,                     \
8873                                     skb,                                \
8874                                     SKB_FIELD)
8875 
8876 #define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
8877         SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,  \
8878                                              struct sock,               \
8879                                              sk,                        \
8880                                              SK_FIELD, BPF_SIZE, EXTRA_OFF)
8881 
8882 static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
8883                                            const struct bpf_insn *si,
8884                                            struct bpf_insn *insn_buf,
8885                                            struct bpf_prog *prog,
8886                                            u32 *target_size)
8887 {
8888         struct bpf_insn *insn = insn_buf;
8889 
8890         switch (si->off) {
8891         case offsetof(struct sk_reuseport_md, data):
8892                 SK_REUSEPORT_LOAD_SKB_FIELD(data);
8893                 break;
8894 
8895         case offsetof(struct sk_reuseport_md, len):
8896                 SK_REUSEPORT_LOAD_SKB_FIELD(len);
8897                 break;
8898 
8899         case offsetof(struct sk_reuseport_md, eth_protocol):
8900                 SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
8901                 break;
8902 
8903         case offsetof(struct sk_reuseport_md, ip_protocol):
8904                 BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
8905                 SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
8906                                                     BPF_W, 0);
8907                 *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
8908                 *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
8909                                         SK_FL_PROTO_SHIFT);
8910                 /* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
8911                  * aware.  No further narrowing or masking is needed.
8912                  */
8913                 *target_size = 1;
8914                 break;
8915 
8916         case offsetof(struct sk_reuseport_md, data_end):
8917                 SK_REUSEPORT_LOAD_FIELD(data_end);
8918                 break;
8919 
8920         case offsetof(struct sk_reuseport_md, hash):
8921                 SK_REUSEPORT_LOAD_FIELD(hash);
8922                 break;
8923 
8924         case offsetof(struct sk_reuseport_md, bind_inany):
8925                 SK_REUSEPORT_LOAD_FIELD(bind_inany);
8926                 break;
8927         }
8928 
8929         return insn - insn_buf;
8930 }
8931 
8932 const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
8933         .get_func_proto         = sk_reuseport_func_proto,
8934         .is_valid_access        = sk_reuseport_is_valid_access,
8935         .convert_ctx_access     = sk_reuseport_convert_ctx_access,
8936 };
8937 
8938 const struct bpf_prog_ops sk_reuseport_prog_ops = {
8939 };
8940 #endif /* CONFIG_INET */

/* [<][>][^][v][top][bottom][index][help] */