filter.c 194.1 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3
/*
 * Linux Socket Filter - Kernel level socket filtering
 *
4 5
 * Based on the design of the Berkeley Packet Filter. The new
 * internal format has been designed by PLUMgrid:
L
Linus Torvalds 已提交
6
 *
7 8 9 10 11 12 13
 *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
 *
 * Authors:
 *
 *	Jay Schulist <jschlst@samba.org>
 *	Alexei Starovoitov <ast@plumgrid.com>
 *	Daniel Borkmann <dborkman@redhat.com>
L
Linus Torvalds 已提交
14 15 16 17 18 19 20
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *
 * Andi Kleen - Fix a few bad bugs and races.
21
 * Kris Katterjohn - Added many additional checks in bpf_check_classic()
L
Linus Torvalds 已提交
22 23 24 25 26 27 28
 */

#include <linux/module.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
29
#include <linux/sock_diag.h>
L
Linus Torvalds 已提交
30 31 32 33
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
34
#include <linux/if_arp.h>
35
#include <linux/gfp.h>
A
Andrey Ignatov 已提交
36
#include <net/inet_common.h>
L
Linus Torvalds 已提交
37 38
#include <net/ip.h>
#include <net/protocol.h>
39
#include <net/netlink.h>
L
Linus Torvalds 已提交
40 41
#include <linux/skbuff.h>
#include <net/sock.h>
42
#include <net/flow_dissector.h>
L
Linus Torvalds 已提交
43 44
#include <linux/errno.h>
#include <linux/timer.h>
45
#include <linux/uaccess.h>
46
#include <asm/unaligned.h>
47
#include <asm/cmpxchg.h>
L
Linus Torvalds 已提交
48
#include <linux/filter.h>
49
#include <linux/ratelimit.h>
50
#include <linux/seccomp.h>
E
Eric Dumazet 已提交
51
#include <linux/if_vlan.h>
52
#include <linux/bpf.h>
53
#include <net/sch_generic.h>
54
#include <net/cls_cgroup.h>
55
#include <net/dst_metadata.h>
56
#include <net/dst.h>
57
#include <net/sock_reuseport.h>
58
#include <net/busy_poll.h>
59
#include <net/tcp.h>
60
#include <net/xfrm.h>
61
#include <linux/bpf_trace.h>
62
#include <net/xdp_sock.h>
63 64 65 66
#include <linux/inetdevice.h>
#include <net/ip_fib.h>
#include <net/flow.h>
#include <net/arp.h>
67 68 69 70
#include <net/ipv6.h>
#include <linux/seg6_local.h>
#include <net/seg6.h>
#include <net/seg6_local.h>
L
Linus Torvalds 已提交
71

S
Stephen Hemminger 已提交
72
/**
73
 *	sk_filter_trim_cap - run a packet through a socket filter
S
Stephen Hemminger 已提交
74 75
 *	@sk: sock associated with &sk_buff
 *	@skb: buffer to filter
76
 *	@cap: limit on how short the eBPF program may trim the packet
S
Stephen Hemminger 已提交
77
 *
78 79
 * Run the eBPF program and then cut skb->data to correct size returned by
 * the program. If pkt_len is 0 we toss packet. If skb->len is smaller
S
Stephen Hemminger 已提交
80
 * than pkt_len we keep whole skb->data. This is the socket level
81
 * wrapper to BPF_PROG_RUN. It returns 0 if the packet should
S
Stephen Hemminger 已提交
82 83 84
 * be accepted or -EPERM if the packet should be tossed.
 *
 */
85
int sk_filter_trim_cap(struct sock *sk, struct sk_buff *skb, unsigned int cap)
S
Stephen Hemminger 已提交
86 87 88 89
{
	int err;
	struct sk_filter *filter;

90 91 92 93 94
	/*
	 * If the skb was allocated from pfmemalloc reserves, only
	 * allow SOCK_MEMALLOC sockets to use it as this socket is
	 * helping free memory
	 */
95 96
	if (skb_pfmemalloc(skb) && !sock_flag(sk, SOCK_MEMALLOC)) {
		NET_INC_STATS(sock_net(sk), LINUX_MIB_PFMEMALLOCDROP);
97
		return -ENOMEM;
98
	}
99 100 101 102
	err = BPF_CGROUP_RUN_PROG_INET_INGRESS(sk, skb);
	if (err)
		return err;

S
Stephen Hemminger 已提交
103 104 105 106
	err = security_sock_rcv_skb(sk, skb);
	if (err)
		return err;

107 108
	rcu_read_lock();
	filter = rcu_dereference(sk->sk_filter);
S
Stephen Hemminger 已提交
109
	if (filter) {
110 111 112 113 114 115
		struct sock *save_sk = skb->sk;
		unsigned int pkt_len;

		skb->sk = sk;
		pkt_len = bpf_prog_run_save_cb(filter->prog, skb);
		skb->sk = save_sk;
116
		err = pkt_len ? pskb_trim(skb, max(cap, pkt_len)) : -EPERM;
S
Stephen Hemminger 已提交
117
	}
118
	rcu_read_unlock();
S
Stephen Hemminger 已提交
119 120 121

	return err;
}
122
EXPORT_SYMBOL(sk_filter_trim_cap);
S
Stephen Hemminger 已提交
123

124
BPF_CALL_1(bpf_skb_get_pay_offset, struct sk_buff *, skb)
125
{
126
	return skb_get_poff(skb);
127 128
}

129
BPF_CALL_3(bpf_skb_get_nlattr, struct sk_buff *, skb, u32, a, u32, x)
130 131 132 133 134 135
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

136 137 138
	if (skb->len < sizeof(struct nlattr))
		return 0;

139
	if (a > skb->len - sizeof(struct nlattr))
140 141
		return 0;

142
	nla = nla_find((struct nlattr *) &skb->data[a], skb->len - a, x);
143 144 145 146 147 148
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

149
BPF_CALL_3(bpf_skb_get_nlattr_nest, struct sk_buff *, skb, u32, a, u32, x)
150 151 152 153 154 155
{
	struct nlattr *nla;

	if (skb_is_nonlinear(skb))
		return 0;

156 157 158
	if (skb->len < sizeof(struct nlattr))
		return 0;

159
	if (a > skb->len - sizeof(struct nlattr))
160 161
		return 0;

162 163
	nla = (struct nlattr *) &skb->data[a];
	if (nla->nla_len > skb->len - a)
164 165
		return 0;

166
	nla = nla_find_nested(nla, x);
167 168 169 170 171 172
	if (nla)
		return (void *) nla - (void *) skb->data;

	return 0;
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
BPF_CALL_4(bpf_skb_load_helper_8, const struct sk_buff *, skb, const void *,
	   data, int, headlen, int, offset)
{
	u8 tmp, *ptr;
	const int len = sizeof(tmp);

	if (offset >= 0) {
		if (headlen - offset >= len)
			return *(u8 *)(data + offset);
		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
			return tmp;
	} else {
		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
		if (likely(ptr))
			return *(u8 *)ptr;
	}

	return -EFAULT;
}

BPF_CALL_2(bpf_skb_load_helper_8_no_cache, const struct sk_buff *, skb,
	   int, offset)
{
	return ____bpf_skb_load_helper_8(skb, skb->data, skb->len - skb->data_len,
					 offset);
}

BPF_CALL_4(bpf_skb_load_helper_16, const struct sk_buff *, skb, const void *,
	   data, int, headlen, int, offset)
{
	u16 tmp, *ptr;
	const int len = sizeof(tmp);

	if (offset >= 0) {
		if (headlen - offset >= len)
			return get_unaligned_be16(data + offset);
		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
			return be16_to_cpu(tmp);
	} else {
		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
		if (likely(ptr))
			return get_unaligned_be16(ptr);
	}

	return -EFAULT;
}

BPF_CALL_2(bpf_skb_load_helper_16_no_cache, const struct sk_buff *, skb,
	   int, offset)
{
	return ____bpf_skb_load_helper_16(skb, skb->data, skb->len - skb->data_len,
					  offset);
}

BPF_CALL_4(bpf_skb_load_helper_32, const struct sk_buff *, skb, const void *,
	   data, int, headlen, int, offset)
{
	u32 tmp, *ptr;
	const int len = sizeof(tmp);

	if (likely(offset >= 0)) {
		if (headlen - offset >= len)
			return get_unaligned_be32(data + offset);
		if (!skb_copy_bits(skb, offset, &tmp, sizeof(tmp)))
			return be32_to_cpu(tmp);
	} else {
		ptr = bpf_internal_load_pointer_neg_helper(skb, offset, len);
		if (likely(ptr))
			return get_unaligned_be32(ptr);
	}

	return -EFAULT;
}

BPF_CALL_2(bpf_skb_load_helper_32_no_cache, const struct sk_buff *, skb,
	   int, offset)
{
	return ____bpf_skb_load_helper_32(skb, skb->data, skb->len - skb->data_len,
					  offset);
}

254
BPF_CALL_0(bpf_get_raw_cpu_id)
255 256 257 258
{
	return raw_smp_processor_id();
}

259
static const struct bpf_func_proto bpf_get_raw_smp_processor_id_proto = {
260
	.func		= bpf_get_raw_cpu_id,
261 262 263 264
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
};

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
static u32 convert_skb_access(int skb_field, int dst_reg, int src_reg,
			      struct bpf_insn *insn_buf)
{
	struct bpf_insn *insn = insn_buf;

	switch (skb_field) {
	case SKF_AD_MARK:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, mark) != 4);

		*insn++ = BPF_LDX_MEM(BPF_W, dst_reg, src_reg,
				      offsetof(struct sk_buff, mark));
		break;

	case SKF_AD_PKTTYPE:
		*insn++ = BPF_LDX_MEM(BPF_B, dst_reg, src_reg, PKT_TYPE_OFFSET());
		*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, PKT_TYPE_MAX);
#ifdef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 5);
#endif
		break;

	case SKF_AD_QUEUE:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, queue_mapping) != 2);

		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, queue_mapping));
		break;
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

	case SKF_AD_VLAN_TAG:
	case SKF_AD_VLAN_TAG_PRESENT:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_tci) != 2);
		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);

		/* dst_reg = *(u16 *) (src_reg + offsetof(vlan_tci)) */
		*insn++ = BPF_LDX_MEM(BPF_H, dst_reg, src_reg,
				      offsetof(struct sk_buff, vlan_tci));
		if (skb_field == SKF_AD_VLAN_TAG) {
			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg,
						~VLAN_TAG_PRESENT);
		} else {
			/* dst_reg >>= 12 */
			*insn++ = BPF_ALU32_IMM(BPF_RSH, dst_reg, 12);
			/* dst_reg &= 1 */
			*insn++ = BPF_ALU32_IMM(BPF_AND, dst_reg, 1);
		}
		break;
311 312 313 314 315
	}

	return insn - insn_buf;
}

316
static bool convert_bpf_extensions(struct sock_filter *fp,
317
				   struct bpf_insn **insnp)
318
{
319
	struct bpf_insn *insn = *insnp;
320
	u32 cnt;
321 322 323

	switch (fp->k) {
	case SKF_AD_OFF + SKF_AD_PROTOCOL:
324 325 326 327 328 329 330
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, protocol) != 2);

		/* A = *(u16 *) (CTX + offsetof(protocol)) */
		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
				      offsetof(struct sk_buff, protocol));
		/* A = ntohs(A) [emitting a nop or swap16] */
		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
331 332 333
		break;

	case SKF_AD_OFF + SKF_AD_PKTTYPE:
334 335
		cnt = convert_skb_access(SKF_AD_PKTTYPE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
336 337 338 339 340 341
		break;

	case SKF_AD_OFF + SKF_AD_IFINDEX:
	case SKF_AD_OFF + SKF_AD_HATYPE:
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, ifindex) != 4);
		BUILD_BUG_ON(FIELD_SIZEOF(struct net_device, type) != 2);
342

343
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
344 345 346 347 348 349 350 351 352 353 354
				      BPF_REG_TMP, BPF_REG_CTX,
				      offsetof(struct sk_buff, dev));
		/* if (tmp != 0) goto pc + 1 */
		*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_TMP, 0, 1);
		*insn++ = BPF_EXIT_INSN();
		if (fp->k == SKF_AD_OFF + SKF_AD_IFINDEX)
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_TMP,
					    offsetof(struct net_device, ifindex));
		else
			*insn = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_TMP,
					    offsetof(struct net_device, type));
355 356 357
		break;

	case SKF_AD_OFF + SKF_AD_MARK:
358 359
		cnt = convert_skb_access(SKF_AD_MARK, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
360 361 362 363 364
		break;

	case SKF_AD_OFF + SKF_AD_RXHASH:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, hash) != 4);

365 366
		*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX,
				    offsetof(struct sk_buff, hash));
367 368 369
		break;

	case SKF_AD_OFF + SKF_AD_QUEUE:
370 371
		cnt = convert_skb_access(SKF_AD_QUEUE, BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
372 373 374
		break;

	case SKF_AD_OFF + SKF_AD_VLAN_TAG:
375 376 377 378
		cnt = convert_skb_access(SKF_AD_VLAN_TAG,
					 BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
		break;
379

380 381 382 383
	case SKF_AD_OFF + SKF_AD_VLAN_TAG_PRESENT:
		cnt = convert_skb_access(SKF_AD_VLAN_TAG_PRESENT,
					 BPF_REG_A, BPF_REG_CTX, insn);
		insn += cnt - 1;
384 385
		break;

386 387 388 389 390 391 392 393 394 395
	case SKF_AD_OFF + SKF_AD_VLAN_TPID:
		BUILD_BUG_ON(FIELD_SIZEOF(struct sk_buff, vlan_proto) != 2);

		/* A = *(u16 *) (CTX + offsetof(vlan_proto)) */
		*insn++ = BPF_LDX_MEM(BPF_H, BPF_REG_A, BPF_REG_CTX,
				      offsetof(struct sk_buff, vlan_proto));
		/* A = ntohs(A) [emitting a nop or swap16] */
		*insn = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, 16);
		break;

396 397 398 399
	case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
	case SKF_AD_OFF + SKF_AD_NLATTR:
	case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
	case SKF_AD_OFF + SKF_AD_CPU:
C
Chema Gonzalez 已提交
400
	case SKF_AD_OFF + SKF_AD_RANDOM:
401
		/* arg1 = CTX */
402
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
403
		/* arg2 = A */
404
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_A);
405
		/* arg3 = X */
406
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_X);
407
		/* Emit call(arg1=CTX, arg2=A, arg3=X) */
408 409
		switch (fp->k) {
		case SKF_AD_OFF + SKF_AD_PAY_OFFSET:
410
			*insn = BPF_EMIT_CALL(bpf_skb_get_pay_offset);
411 412
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR:
413
			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr);
414 415
			break;
		case SKF_AD_OFF + SKF_AD_NLATTR_NEST:
416
			*insn = BPF_EMIT_CALL(bpf_skb_get_nlattr_nest);
417 418
			break;
		case SKF_AD_OFF + SKF_AD_CPU:
419
			*insn = BPF_EMIT_CALL(bpf_get_raw_cpu_id);
420
			break;
C
Chema Gonzalez 已提交
421
		case SKF_AD_OFF + SKF_AD_RANDOM:
422 423
			*insn = BPF_EMIT_CALL(bpf_user_rnd_u32);
			bpf_user_rnd_init_once();
C
Chema Gonzalez 已提交
424
			break;
425 426 427 428
		}
		break;

	case SKF_AD_OFF + SKF_AD_ALU_XOR_X:
429 430
		/* A ^= X */
		*insn = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_X);
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
		break;

	default:
		/* This is just a dummy call to avoid letting the compiler
		 * evict __bpf_call_base() as an optimization. Placed here
		 * where no-one bothers.
		 */
		BUG_ON(__bpf_call_base(0, 0, 0, 0, 0) != 0);
		return false;
	}

	*insnp = insn;
	return true;
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
static bool convert_bpf_ld_abs(struct sock_filter *fp, struct bpf_insn **insnp)
{
	const bool unaligned_ok = IS_BUILTIN(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS);
	int size = bpf_size_to_bytes(BPF_SIZE(fp->code));
	bool endian = BPF_SIZE(fp->code) == BPF_H ||
		      BPF_SIZE(fp->code) == BPF_W;
	bool indirect = BPF_MODE(fp->code) == BPF_IND;
	const int ip_align = NET_IP_ALIGN;
	struct bpf_insn *insn = *insnp;
	int offset = fp->k;

	if (!indirect &&
	    ((unaligned_ok && offset >= 0) ||
	     (!unaligned_ok && offset >= 0 &&
	      offset + ip_align >= 0 &&
	      offset + ip_align % size == 0))) {
462 463
		bool ldx_off_ok = offset <= S16_MAX;

464 465
		*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_H);
		*insn++ = BPF_ALU64_IMM(BPF_SUB, BPF_REG_TMP, offset);
466 467 468 469 470 471 472 473 474 475 476
		*insn++ = BPF_JMP_IMM(BPF_JSLT, BPF_REG_TMP,
				      size, 2 + endian + (!ldx_off_ok * 2));
		if (ldx_off_ok) {
			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
					      BPF_REG_D, offset);
		} else {
			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_D);
			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_TMP, offset);
			*insn++ = BPF_LDX_MEM(BPF_SIZE(fp->code), BPF_REG_A,
					      BPF_REG_TMP, 0);
		}
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
		if (endian)
			*insn++ = BPF_ENDIAN(BPF_FROM_BE, BPF_REG_A, size * 8);
		*insn++ = BPF_JMP_A(8);
	}

	*insn++ = BPF_MOV64_REG(BPF_REG_ARG1, BPF_REG_CTX);
	*insn++ = BPF_MOV64_REG(BPF_REG_ARG2, BPF_REG_D);
	*insn++ = BPF_MOV64_REG(BPF_REG_ARG3, BPF_REG_H);
	if (!indirect) {
		*insn++ = BPF_MOV64_IMM(BPF_REG_ARG4, offset);
	} else {
		*insn++ = BPF_MOV64_REG(BPF_REG_ARG4, BPF_REG_X);
		if (fp->k)
			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_ARG4, offset);
	}

	switch (BPF_SIZE(fp->code)) {
	case BPF_B:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8);
		break;
	case BPF_H:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16);
		break;
	case BPF_W:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32);
		break;
	default:
		return false;
	}

	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_A, 0, 2);
	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
	*insn   = BPF_EXIT_INSN();

	*insnp = insn;
	return true;
}

515
/**
516
 *	bpf_convert_filter - convert filter program
517 518
 *	@prog: the user passed filter program
 *	@len: the length of the user passed filter program
519
 *	@new_prog: allocated 'struct bpf_prog' or NULL
520
 *	@new_len: pointer to store length of converted program
521
 *	@seen_ld_abs: bool whether we've seen ld_abs/ind
522
 *
523 524
 * Remap 'sock_filter' style classic BPF (cBPF) instruction set to 'bpf_insn'
 * style extended BPF (eBPF).
525 526 527
 * Conversion workflow:
 *
 * 1) First pass for calculating the new program length:
528
 *   bpf_convert_filter(old_prog, old_len, NULL, &new_len, &seen_ld_abs)
529 530 531
 *
 * 2) 2nd pass to remap in two passes: 1st pass finds new
 *    jump offsets, 2nd pass remapping:
532
 *   bpf_convert_filter(old_prog, old_len, new_prog, &new_len, &seen_ld_abs)
533
 */
534
static int bpf_convert_filter(struct sock_filter *prog, int len,
535 536
			      struct bpf_prog *new_prog, int *new_len,
			      bool *seen_ld_abs)
537
{
538 539
	int new_flen = 0, pass = 0, target, i, stack_off;
	struct bpf_insn *new_insn, *first_insn = NULL;
540 541 542 543 544
	struct sock_filter *fp;
	int *addrs = NULL;
	u8 bpf_src;

	BUILD_BUG_ON(BPF_MEMWORDS * sizeof(u32) > MAX_BPF_STACK);
545
	BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
546

547
	if (len <= 0 || len > BPF_MAXINSNS)
548 549 550
		return -EINVAL;

	if (new_prog) {
551
		first_insn = new_prog->insnsi;
552 553
		addrs = kcalloc(len, sizeof(*addrs),
				GFP_KERNEL | __GFP_NOWARN);
554 555 556 557 558
		if (!addrs)
			return -ENOMEM;
	}

do_pass:
559
	new_insn = first_insn;
560 561
	fp = prog;

562
	/* Classic BPF related prologue emission. */
563
	if (new_prog) {
564 565 566
		/* Classic BPF expects A and X to be reset first. These need
		 * to be guaranteed to be the first two instructions.
		 */
567 568
		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
		*new_insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_X, BPF_REG_X);
569 570 571 572 573 574

		/* All programs must keep CTX in callee saved BPF_REG_CTX.
		 * In eBPF case it's done by the compiler, here we need to
		 * do this ourself. Initial CTX is present in BPF_REG_ARG1.
		 */
		*new_insn++ = BPF_MOV64_REG(BPF_REG_CTX, BPF_REG_ARG1);
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
		if (*seen_ld_abs) {
			/* For packet access in classic BPF, cache skb->data
			 * in callee-saved BPF R8 and skb->len - skb->data_len
			 * (headlen) in BPF R9. Since classic BPF is read-only
			 * on CTX, we only need to cache it once.
			 */
			*new_insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
						  BPF_REG_D, BPF_REG_CTX,
						  offsetof(struct sk_buff, data));
			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_H, BPF_REG_CTX,
						  offsetof(struct sk_buff, len));
			*new_insn++ = BPF_LDX_MEM(BPF_W, BPF_REG_TMP, BPF_REG_CTX,
						  offsetof(struct sk_buff, data_len));
			*new_insn++ = BPF_ALU32_REG(BPF_SUB, BPF_REG_H, BPF_REG_TMP);
		}
590 591 592
	} else {
		new_insn += 3;
	}
593 594

	for (i = 0; i < len; fp++, i++) {
595
		struct bpf_insn tmp_insns[32] = { };
596
		struct bpf_insn *insn = tmp_insns;
597 598

		if (addrs)
599
			addrs[i] = new_insn - first_insn;
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637

		switch (fp->code) {
		/* All arithmetic insns and skb loads map as-is. */
		case BPF_ALU | BPF_ADD | BPF_X:
		case BPF_ALU | BPF_ADD | BPF_K:
		case BPF_ALU | BPF_SUB | BPF_X:
		case BPF_ALU | BPF_SUB | BPF_K:
		case BPF_ALU | BPF_AND | BPF_X:
		case BPF_ALU | BPF_AND | BPF_K:
		case BPF_ALU | BPF_OR | BPF_X:
		case BPF_ALU | BPF_OR | BPF_K:
		case BPF_ALU | BPF_LSH | BPF_X:
		case BPF_ALU | BPF_LSH | BPF_K:
		case BPF_ALU | BPF_RSH | BPF_X:
		case BPF_ALU | BPF_RSH | BPF_K:
		case BPF_ALU | BPF_XOR | BPF_X:
		case BPF_ALU | BPF_XOR | BPF_K:
		case BPF_ALU | BPF_MUL | BPF_X:
		case BPF_ALU | BPF_MUL | BPF_K:
		case BPF_ALU | BPF_DIV | BPF_X:
		case BPF_ALU | BPF_DIV | BPF_K:
		case BPF_ALU | BPF_MOD | BPF_X:
		case BPF_ALU | BPF_MOD | BPF_K:
		case BPF_ALU | BPF_NEG:
		case BPF_LD | BPF_ABS | BPF_W:
		case BPF_LD | BPF_ABS | BPF_H:
		case BPF_LD | BPF_ABS | BPF_B:
		case BPF_LD | BPF_IND | BPF_W:
		case BPF_LD | BPF_IND | BPF_H:
		case BPF_LD | BPF_IND | BPF_B:
			/* Check for overloaded BPF extension and
			 * directly convert it if found, otherwise
			 * just move on with mapping.
			 */
			if (BPF_CLASS(fp->code) == BPF_LD &&
			    BPF_MODE(fp->code) == BPF_ABS &&
			    convert_bpf_extensions(fp, &insn))
				break;
638 639 640 641 642
			if (BPF_CLASS(fp->code) == BPF_LD &&
			    convert_bpf_ld_abs(fp, &insn)) {
				*seen_ld_abs = true;
				break;
			}
643

644
			if (fp->code == (BPF_ALU | BPF_DIV | BPF_X) ||
645
			    fp->code == (BPF_ALU | BPF_MOD | BPF_X)) {
646
				*insn++ = BPF_MOV32_REG(BPF_REG_X, BPF_REG_X);
647 648 649 650 651 652 653
				/* Error with exception code on div/mod by 0.
				 * For cBPF programs, this was always return 0.
				 */
				*insn++ = BPF_JMP_IMM(BPF_JNE, BPF_REG_X, 0, 2);
				*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_A, BPF_REG_A);
				*insn++ = BPF_EXIT_INSN();
			}
654

655
			*insn = BPF_RAW_INSN(fp->code, BPF_REG_A, BPF_REG_X, 0, fp->k);
656 657
			break;

658 659 660 661 662 663 664
		/* Jump transformation cannot use BPF block macros
		 * everywhere as offset calculation and target updates
		 * require a bit more work than the rest, i.e. jump
		 * opcodes map as-is, but offsets need adjustment.
		 */

#define BPF_EMIT_JMP							\
665
	do {								\
666 667 668
		const s32 off_min = S16_MIN, off_max = S16_MAX;		\
		s32 off;						\
									\
669 670
		if (target >= len || target < 0)			\
			goto err;					\
671
		off = addrs ? addrs[target] - addrs[i] - 1 : 0;		\
672
		/* Adjust pc relative offset for 2nd or 3rd insn. */	\
673 674 675 676 677
		off -= insn - tmp_insns;				\
		/* Reject anything not fitting into insn->off. */	\
		if (off < off_min || off > off_max)			\
			goto err;					\
		insn->off = off;					\
678 679
	} while (0)

680 681 682 683
		case BPF_JMP | BPF_JA:
			target = i + fp->k + 1;
			insn->code = fp->code;
			BPF_EMIT_JMP;
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
			break;

		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
			if (BPF_SRC(fp->code) == BPF_K && (int) fp->k < 0) {
				/* BPF immediates are signed, zero extend
				 * immediate into tmp register and use it
				 * in compare insn.
				 */
699
				*insn++ = BPF_MOV32_IMM(BPF_REG_TMP, fp->k);
700

701 702
				insn->dst_reg = BPF_REG_A;
				insn->src_reg = BPF_REG_TMP;
703 704
				bpf_src = BPF_X;
			} else {
705
				insn->dst_reg = BPF_REG_A;
706 707
				insn->imm = fp->k;
				bpf_src = BPF_SRC(fp->code);
708
				insn->src_reg = bpf_src == BPF_X ? BPF_REG_X : 0;
L
Linus Torvalds 已提交
709
			}
710 711 712 713 714

			/* Common case where 'jump_false' is next insn. */
			if (fp->jf == 0) {
				insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
				target = i + fp->jt + 1;
715
				BPF_EMIT_JMP;
716
				break;
L
Linus Torvalds 已提交
717
			}
718

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
			/* Convert some jumps when 'jump_true' is next insn. */
			if (fp->jt == 0) {
				switch (BPF_OP(fp->code)) {
				case BPF_JEQ:
					insn->code = BPF_JMP | BPF_JNE | bpf_src;
					break;
				case BPF_JGT:
					insn->code = BPF_JMP | BPF_JLE | bpf_src;
					break;
				case BPF_JGE:
					insn->code = BPF_JMP | BPF_JLT | bpf_src;
					break;
				default:
					goto jmp_rest;
				}

735
				target = i + fp->jf + 1;
736
				BPF_EMIT_JMP;
737
				break;
738
			}
739
jmp_rest:
740 741 742
			/* Other jumps are mapped into two insns: Jxx and JA. */
			target = i + fp->jt + 1;
			insn->code = BPF_JMP | BPF_OP(fp->code) | bpf_src;
743
			BPF_EMIT_JMP;
744 745 746 747
			insn++;

			insn->code = BPF_JMP | BPF_JA;
			target = i + fp->jf + 1;
748
			BPF_EMIT_JMP;
749 750 751
			break;

		/* ldxb 4 * ([14] & 0xf) is remaped into 6 insns. */
752 753 754 755 756 757 758 759 760 761
		case BPF_LDX | BPF_MSH | BPF_B: {
			struct sock_filter tmp = {
				.code	= BPF_LD | BPF_ABS | BPF_B,
				.k	= fp->k,
			};

			*seen_ld_abs = true;

			/* X = A */
			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
762
			/* A = BPF_R0 = *(u8 *) (skb->data + K) */
763 764
			convert_bpf_ld_abs(&tmp, &insn);
			insn++;
765
			/* A &= 0xf */
766
			*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_A, 0xf);
767
			/* A <<= 2 */
768
			*insn++ = BPF_ALU32_IMM(BPF_LSH, BPF_REG_A, 2);
769 770
			/* tmp = X */
			*insn++ = BPF_MOV64_REG(BPF_REG_TMP, BPF_REG_X);
771
			/* X = A */
772
			*insn++ = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
773
			/* A = tmp */
774
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_TMP);
775
			break;
776
		}
777 778 779
		/* RET_K is remaped into 2 insns. RET_A case doesn't need an
		 * extra mov as BPF_REG_0 is already mapped into BPF_REG_A.
		 */
780 781
		case BPF_RET | BPF_A:
		case BPF_RET | BPF_K:
782 783 784
			if (BPF_RVAL(fp->code) == BPF_K)
				*insn++ = BPF_MOV32_RAW(BPF_K, BPF_REG_0,
							0, fp->k);
785
			*insn = BPF_EXIT_INSN();
786 787 788 789 790
			break;

		/* Store to stack. */
		case BPF_ST:
		case BPF_STX:
791
			stack_off = fp->k * 4  + 4;
792 793
			*insn = BPF_STX_MEM(BPF_W, BPF_REG_FP, BPF_CLASS(fp->code) ==
					    BPF_ST ? BPF_REG_A : BPF_REG_X,
794 795 796 797 798 799 800
					    -stack_off);
			/* check_load_and_stores() verifies that classic BPF can
			 * load from stack only after write, so tracking
			 * stack_depth for ST|STX insns is enough
			 */
			if (new_prog && new_prog->aux->stack_depth < stack_off)
				new_prog->aux->stack_depth = stack_off;
801 802 803 804 805
			break;

		/* Load from stack. */
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
806
			stack_off = fp->k * 4  + 4;
807 808
			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD  ?
					    BPF_REG_A : BPF_REG_X, BPF_REG_FP,
809
					    -stack_off);
810 811 812 813 814
			break;

		/* A = K or X = K */
		case BPF_LD | BPF_IMM:
		case BPF_LDX | BPF_IMM:
815 816
			*insn = BPF_MOV32_IMM(BPF_CLASS(fp->code) == BPF_LD ?
					      BPF_REG_A : BPF_REG_X, fp->k);
817 818 819 820
			break;

		/* X = A */
		case BPF_MISC | BPF_TAX:
821
			*insn = BPF_MOV64_REG(BPF_REG_X, BPF_REG_A);
822 823 824 825
			break;

		/* A = X */
		case BPF_MISC | BPF_TXA:
826
			*insn = BPF_MOV64_REG(BPF_REG_A, BPF_REG_X);
827 828 829 830 831
			break;

		/* A = skb->len or X = skb->len */
		case BPF_LD | BPF_W | BPF_LEN:
		case BPF_LDX | BPF_W | BPF_LEN:
832 833 834
			*insn = BPF_LDX_MEM(BPF_W, BPF_CLASS(fp->code) == BPF_LD ?
					    BPF_REG_A : BPF_REG_X, BPF_REG_CTX,
					    offsetof(struct sk_buff, len));
835 836
			break;

837
		/* Access seccomp_data fields. */
838
		case BPF_LDX | BPF_ABS | BPF_W:
839 840
			/* A = *(u32 *) (ctx + K) */
			*insn = BPF_LDX_MEM(BPF_W, BPF_REG_A, BPF_REG_CTX, fp->k);
841 842
			break;

S
Stephen Hemminger 已提交
843
		/* Unknown instruction. */
L
Linus Torvalds 已提交
844
		default:
845
			goto err;
L
Linus Torvalds 已提交
846
		}
847 848 849 850 851 852

		insn++;
		if (new_prog)
			memcpy(new_insn, tmp_insns,
			       sizeof(*insn) * (insn - tmp_insns));
		new_insn += insn - tmp_insns;
L
Linus Torvalds 已提交
853 854
	}

855 856
	if (!new_prog) {
		/* Only calculating new length. */
857
		*new_len = new_insn - first_insn;
858 859
		if (*seen_ld_abs)
			*new_len += 4; /* Prologue bits. */
860 861 862 863
		return 0;
	}

	pass++;
864 865
	if (new_flen != new_insn - first_insn) {
		new_flen = new_insn - first_insn;
866 867 868 869 870 871 872
		if (pass > 2)
			goto err;
		goto do_pass;
	}

	kfree(addrs);
	BUG_ON(*new_len != new_flen);
L
Linus Torvalds 已提交
873
	return 0;
874 875 876
err:
	kfree(addrs);
	return -EINVAL;
L
Linus Torvalds 已提交
877 878
}

879 880
/* Security:
 *
881
 * As we dont want to clear mem[] array for each packet going through
L
Li RongQing 已提交
882
 * __bpf_prog_run(), we check that filter loaded by user never try to read
883
 * a cell if not previously written, and we check all branches to be sure
L
Lucas De Marchi 已提交
884
 * a malicious user doesn't try to abuse us.
885
 */
886
static int check_load_and_stores(const struct sock_filter *filter, int flen)
887
{
888
	u16 *masks, memvalid = 0; /* One bit per cell, 16 cells */
889 890 891
	int pc, ret = 0;

	BUILD_BUG_ON(BPF_MEMWORDS > 16);
892

893
	masks = kmalloc_array(flen, sizeof(*masks), GFP_KERNEL);
894 895
	if (!masks)
		return -ENOMEM;
896

897 898 899 900 901 902
	memset(masks, 0xff, flen * sizeof(*masks));

	for (pc = 0; pc < flen; pc++) {
		memvalid &= masks[pc];

		switch (filter[pc].code) {
903 904
		case BPF_ST:
		case BPF_STX:
905 906
			memvalid |= (1 << filter[pc].k);
			break;
907 908
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
909 910 911 912 913
			if (!(memvalid & (1 << filter[pc].k))) {
				ret = -EINVAL;
				goto error;
			}
			break;
914 915
		case BPF_JMP | BPF_JA:
			/* A jump must set masks on target */
916 917 918
			masks[pc + 1 + filter[pc].k] &= memvalid;
			memvalid = ~0;
			break;
919 920 921 922 923 924 925 926 927
		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
			/* A jump must set masks on targets */
928 929 930 931 932 933 934 935 936 937 938
			masks[pc + 1 + filter[pc].jt] &= memvalid;
			masks[pc + 1 + filter[pc].jf] &= memvalid;
			memvalid = ~0;
			break;
		}
	}
error:
	kfree(masks);
	return ret;
}

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
static bool chk_code_allowed(u16 code_to_probe)
{
	static const bool codes[] = {
		/* 32 bit ALU operations */
		[BPF_ALU | BPF_ADD | BPF_K] = true,
		[BPF_ALU | BPF_ADD | BPF_X] = true,
		[BPF_ALU | BPF_SUB | BPF_K] = true,
		[BPF_ALU | BPF_SUB | BPF_X] = true,
		[BPF_ALU | BPF_MUL | BPF_K] = true,
		[BPF_ALU | BPF_MUL | BPF_X] = true,
		[BPF_ALU | BPF_DIV | BPF_K] = true,
		[BPF_ALU | BPF_DIV | BPF_X] = true,
		[BPF_ALU | BPF_MOD | BPF_K] = true,
		[BPF_ALU | BPF_MOD | BPF_X] = true,
		[BPF_ALU | BPF_AND | BPF_K] = true,
		[BPF_ALU | BPF_AND | BPF_X] = true,
		[BPF_ALU | BPF_OR | BPF_K] = true,
		[BPF_ALU | BPF_OR | BPF_X] = true,
		[BPF_ALU | BPF_XOR | BPF_K] = true,
		[BPF_ALU | BPF_XOR | BPF_X] = true,
		[BPF_ALU | BPF_LSH | BPF_K] = true,
		[BPF_ALU | BPF_LSH | BPF_X] = true,
		[BPF_ALU | BPF_RSH | BPF_K] = true,
		[BPF_ALU | BPF_RSH | BPF_X] = true,
		[BPF_ALU | BPF_NEG] = true,
		/* Load instructions */
		[BPF_LD | BPF_W | BPF_ABS] = true,
		[BPF_LD | BPF_H | BPF_ABS] = true,
		[BPF_LD | BPF_B | BPF_ABS] = true,
		[BPF_LD | BPF_W | BPF_LEN] = true,
		[BPF_LD | BPF_W | BPF_IND] = true,
		[BPF_LD | BPF_H | BPF_IND] = true,
		[BPF_LD | BPF_B | BPF_IND] = true,
		[BPF_LD | BPF_IMM] = true,
		[BPF_LD | BPF_MEM] = true,
		[BPF_LDX | BPF_W | BPF_LEN] = true,
		[BPF_LDX | BPF_B | BPF_MSH] = true,
		[BPF_LDX | BPF_IMM] = true,
		[BPF_LDX | BPF_MEM] = true,
		/* Store instructions */
		[BPF_ST] = true,
		[BPF_STX] = true,
		/* Misc instructions */
		[BPF_MISC | BPF_TAX] = true,
		[BPF_MISC | BPF_TXA] = true,
		/* Return instructions */
		[BPF_RET | BPF_K] = true,
		[BPF_RET | BPF_A] = true,
		/* Jump instructions */
		[BPF_JMP | BPF_JA] = true,
		[BPF_JMP | BPF_JEQ | BPF_K] = true,
		[BPF_JMP | BPF_JEQ | BPF_X] = true,
		[BPF_JMP | BPF_JGE | BPF_K] = true,
		[BPF_JMP | BPF_JGE | BPF_X] = true,
		[BPF_JMP | BPF_JGT | BPF_K] = true,
		[BPF_JMP | BPF_JGT | BPF_X] = true,
		[BPF_JMP | BPF_JSET | BPF_K] = true,
		[BPF_JMP | BPF_JSET | BPF_X] = true,
	};

	if (code_to_probe >= ARRAY_SIZE(codes))
		return false;

	return codes[code_to_probe];
}

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
static bool bpf_check_basics_ok(const struct sock_filter *filter,
				unsigned int flen)
{
	if (filter == NULL)
		return false;
	if (flen == 0 || flen > BPF_MAXINSNS)
		return false;

	return true;
}

L
Linus Torvalds 已提交
1016
/**
1017
 *	bpf_check_classic - verify socket filter code
L
Linus Torvalds 已提交
1018 1019 1020 1021 1022
 *	@filter: filter to verify
 *	@flen: length of filter
 *
 * Check the user's filter code. If we let some ugly
 * filter code slip through kaboom! The filter must contain
1023 1024
 * no references or jumps that are out of range, no illegal
 * instructions, and must end with a RET instruction.
L
Linus Torvalds 已提交
1025
 *
1026 1027 1028
 * All jumps are forward as they are not signed.
 *
 * Returns 0 if the rule set is legal or -EINVAL if not.
L
Linus Torvalds 已提交
1029
 */
1030 1031
static int bpf_check_classic(const struct sock_filter *filter,
			     unsigned int flen)
L
Linus Torvalds 已提交
1032
{
1033
	bool anc_found;
1034
	int pc;
L
Linus Torvalds 已提交
1035

1036
	/* Check the filter code now */
L
Linus Torvalds 已提交
1037
	for (pc = 0; pc < flen; pc++) {
1038
		const struct sock_filter *ftest = &filter[pc];
1039

1040 1041
		/* May we actually operate on this code? */
		if (!chk_code_allowed(ftest->code))
1042
			return -EINVAL;
1043

1044
		/* Some instructions need special checks */
1045 1046 1047 1048
		switch (ftest->code) {
		case BPF_ALU | BPF_DIV | BPF_K:
		case BPF_ALU | BPF_MOD | BPF_K:
			/* Check for division by zero */
E
Eric Dumazet 已提交
1049 1050 1051
			if (ftest->k == 0)
				return -EINVAL;
			break;
R
Rabin Vincent 已提交
1052 1053 1054 1055 1056
		case BPF_ALU | BPF_LSH | BPF_K:
		case BPF_ALU | BPF_RSH | BPF_K:
			if (ftest->k >= 32)
				return -EINVAL;
			break;
1057 1058 1059 1060 1061
		case BPF_LD | BPF_MEM:
		case BPF_LDX | BPF_MEM:
		case BPF_ST:
		case BPF_STX:
			/* Check for invalid memory addresses */
1062 1063 1064
			if (ftest->k >= BPF_MEMWORDS)
				return -EINVAL;
			break;
1065 1066
		case BPF_JMP | BPF_JA:
			/* Note, the large ftest->k might cause loops.
1067 1068 1069
			 * Compare this with conditional jumps below,
			 * where offsets are limited. --ANK (981016)
			 */
1070
			if (ftest->k >= (unsigned int)(flen - pc - 1))
1071
				return -EINVAL;
1072
			break;
1073 1074 1075 1076 1077 1078 1079 1080 1081
		case BPF_JMP | BPF_JEQ | BPF_K:
		case BPF_JMP | BPF_JEQ | BPF_X:
		case BPF_JMP | BPF_JGE | BPF_K:
		case BPF_JMP | BPF_JGE | BPF_X:
		case BPF_JMP | BPF_JGT | BPF_K:
		case BPF_JMP | BPF_JGT | BPF_X:
		case BPF_JMP | BPF_JSET | BPF_K:
		case BPF_JMP | BPF_JSET | BPF_X:
			/* Both conditionals must be safe */
1082
			if (pc + ftest->jt + 1 >= flen ||
1083 1084
			    pc + ftest->jf + 1 >= flen)
				return -EINVAL;
1085
			break;
1086 1087 1088
		case BPF_LD | BPF_W | BPF_ABS:
		case BPF_LD | BPF_H | BPF_ABS:
		case BPF_LD | BPF_B | BPF_ABS:
1089
			anc_found = false;
1090 1091 1092
			if (bpf_anc_helper(ftest) & BPF_ANC)
				anc_found = true;
			/* Ancillary operation unknown or unsupported */
1093 1094
			if (anc_found == false && ftest->k >= SKF_AD_OFF)
				return -EINVAL;
1095 1096
		}
	}
1097

1098
	/* Last instruction must be a RET code */
1099
	switch (filter[flen - 1].code) {
1100 1101
	case BPF_RET | BPF_K:
	case BPF_RET | BPF_A:
1102
		return check_load_and_stores(filter, flen);
1103
	}
1104

1105
	return -EINVAL;
L
Linus Torvalds 已提交
1106 1107
}

1108 1109
static int bpf_prog_store_orig_filter(struct bpf_prog *fp,
				      const struct sock_fprog *fprog)
1110
{
1111
	unsigned int fsize = bpf_classic_proglen(fprog);
1112 1113 1114 1115 1116 1117 1118 1119
	struct sock_fprog_kern *fkprog;

	fp->orig_prog = kmalloc(sizeof(*fkprog), GFP_KERNEL);
	if (!fp->orig_prog)
		return -ENOMEM;

	fkprog = fp->orig_prog;
	fkprog->len = fprog->len;
1120 1121 1122

	fkprog->filter = kmemdup(fp->insns, fsize,
				 GFP_KERNEL | __GFP_NOWARN);
1123 1124 1125 1126 1127 1128 1129 1130
	if (!fkprog->filter) {
		kfree(fp->orig_prog);
		return -ENOMEM;
	}

	return 0;
}

1131
static void bpf_release_orig_filter(struct bpf_prog *fp)
1132 1133 1134 1135 1136 1137 1138 1139 1140
{
	struct sock_fprog_kern *fprog = fp->orig_prog;

	if (fprog) {
		kfree(fprog->filter);
		kfree(fprog);
	}
}

1141 1142
static void __bpf_prog_release(struct bpf_prog *prog)
{
1143
	if (prog->type == BPF_PROG_TYPE_SOCKET_FILTER) {
1144 1145 1146 1147 1148
		bpf_prog_put(prog);
	} else {
		bpf_release_orig_filter(prog);
		bpf_prog_free(prog);
	}
1149 1150
}

1151 1152
static void __sk_filter_release(struct sk_filter *fp)
{
1153 1154
	__bpf_prog_release(fp->prog);
	kfree(fp);
1155 1156
}

1157
/**
E
Eric Dumazet 已提交
1158
 * 	sk_filter_release_rcu - Release a socket filter by rcu_head
1159 1160
 *	@rcu: rcu_head that contains the sk_filter to free
 */
1161
static void sk_filter_release_rcu(struct rcu_head *rcu)
1162 1163 1164
{
	struct sk_filter *fp = container_of(rcu, struct sk_filter, rcu);

1165
	__sk_filter_release(fp);
1166
}
1167 1168 1169 1170 1171 1172 1173 1174 1175

/**
 *	sk_filter_release - release a socket filter
 *	@fp: filter to remove
 *
 *	Remove a filter from a socket and release its resources.
 */
static void sk_filter_release(struct sk_filter *fp)
{
1176
	if (refcount_dec_and_test(&fp->refcnt))
1177 1178 1179 1180 1181
		call_rcu(&fp->rcu, sk_filter_release_rcu);
}

void sk_filter_uncharge(struct sock *sk, struct sk_filter *fp)
{
1182
	u32 filter_size = bpf_prog_size(fp->prog->len);
1183

1184 1185
	atomic_sub(filter_size, &sk->sk_omem_alloc);
	sk_filter_release(fp);
1186
}
1187

1188 1189 1190
/* try to charge the socket memory if there is space available
 * return true on success
 */
1191
static bool __sk_filter_charge(struct sock *sk, struct sk_filter *fp)
1192
{
1193
	u32 filter_size = bpf_prog_size(fp->prog->len);
1194 1195 1196 1197 1198 1199

	/* same check as in sock_kmalloc() */
	if (filter_size <= sysctl_optmem_max &&
	    atomic_read(&sk->sk_omem_alloc) + filter_size < sysctl_optmem_max) {
		atomic_add(filter_size, &sk->sk_omem_alloc);
		return true;
1200
	}
1201
	return false;
1202 1203
}

1204 1205
bool sk_filter_charge(struct sock *sk, struct sk_filter *fp)
{
1206 1207 1208 1209 1210 1211 1212 1213
	if (!refcount_inc_not_zero(&fp->refcnt))
		return false;

	if (!__sk_filter_charge(sk, fp)) {
		sk_filter_release(fp);
		return false;
	}
	return true;
1214 1215
}

1216
static struct bpf_prog *bpf_migrate_filter(struct bpf_prog *fp)
1217 1218
{
	struct sock_filter *old_prog;
1219
	struct bpf_prog *old_fp;
1220
	int err, new_len, old_len = fp->len;
1221
	bool seen_ld_abs = false;
1222 1223 1224 1225 1226 1227 1228

	/* We are free to overwrite insns et al right here as it
	 * won't be used at this point in time anymore internally
	 * after the migration to the internal BPF instruction
	 * representation.
	 */
	BUILD_BUG_ON(sizeof(struct sock_filter) !=
1229
		     sizeof(struct bpf_insn));
1230 1231 1232 1233 1234 1235

	/* Conversion cannot happen on overlapping memory areas,
	 * so we need to keep the user BPF around until the 2nd
	 * pass. At this time, the user BPF is stored in fp->insns.
	 */
	old_prog = kmemdup(fp->insns, old_len * sizeof(struct sock_filter),
1236
			   GFP_KERNEL | __GFP_NOWARN);
1237 1238 1239 1240 1241 1242
	if (!old_prog) {
		err = -ENOMEM;
		goto out_err;
	}

	/* 1st pass: calculate the new program length. */
1243 1244
	err = bpf_convert_filter(old_prog, old_len, NULL, &new_len,
				 &seen_ld_abs);
1245 1246 1247 1248 1249
	if (err)
		goto out_err_free;

	/* Expand fp for appending the new filter representation. */
	old_fp = fp;
1250
	fp = bpf_prog_realloc(old_fp, bpf_prog_size(new_len), 0);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	if (!fp) {
		/* The old_fp is still around in case we couldn't
		 * allocate new memory, so uncharge on that one.
		 */
		fp = old_fp;
		err = -ENOMEM;
		goto out_err_free;
	}

	fp->len = new_len;

1262
	/* 2nd pass: remap sock_filter insns into bpf_insn insns. */
1263 1264
	err = bpf_convert_filter(old_prog, old_len, fp, &new_len,
				 &seen_ld_abs);
1265
	if (err)
1266
		/* 2nd bpf_convert_filter() can fail only if it fails
1267 1268
		 * to allocate memory, remapping must succeed. Note,
		 * that at this time old_fp has already been released
1269
		 * by krealloc().
1270 1271 1272
		 */
		goto out_err_free;

1273
	fp = bpf_prog_select_runtime(fp, &err);
1274 1275
	if (err)
		goto out_err_free;
1276

1277 1278 1279 1280 1281 1282
	kfree(old_prog);
	return fp;

out_err_free:
	kfree(old_prog);
out_err:
1283
	__bpf_prog_release(fp);
1284 1285 1286
	return ERR_PTR(err);
}

1287 1288
static struct bpf_prog *bpf_prepare_filter(struct bpf_prog *fp,
					   bpf_aux_classic_check_t trans)
1289 1290 1291
{
	int err;

1292
	fp->bpf_func = NULL;
1293
	fp->jited = 0;
1294

1295
	err = bpf_check_classic(fp->insns, fp->len);
1296
	if (err) {
1297
		__bpf_prog_release(fp);
1298
		return ERR_PTR(err);
1299
	}
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	/* There might be additional checks and transformations
	 * needed on classic filters, f.e. in case of seccomp.
	 */
	if (trans) {
		err = trans(fp->insns, fp->len);
		if (err) {
			__bpf_prog_release(fp);
			return ERR_PTR(err);
		}
	}

1312 1313 1314
	/* Probe if we can JIT compile the filter and if so, do
	 * the compilation of the filter.
	 */
1315
	bpf_jit_compile(fp);
1316 1317 1318 1319

	/* JIT compiler couldn't process this filter, so do the
	 * internal BPF translation for the optimized interpreter.
	 */
1320
	if (!fp->jited)
1321
		fp = bpf_migrate_filter(fp);
1322 1323

	return fp;
1324 1325 1326
}

/**
1327
 *	bpf_prog_create - create an unattached filter
R
Randy Dunlap 已提交
1328
 *	@pfp: the unattached filter that is created
1329
 *	@fprog: the filter program
1330
 *
R
Randy Dunlap 已提交
1331
 * Create a filter independent of any socket. We first run some
1332 1333 1334 1335
 * sanity checks on it to make sure it does not explode on us later.
 * If an error occurs or there is insufficient memory for the filter
 * a negative errno code is returned. On success the return is zero.
 */
1336
int bpf_prog_create(struct bpf_prog **pfp, struct sock_fprog_kern *fprog)
1337
{
1338
	unsigned int fsize = bpf_classic_proglen(fprog);
1339
	struct bpf_prog *fp;
1340 1341

	/* Make sure new filter is there and in the right amounts. */
1342
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1343 1344
		return -EINVAL;

1345
	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1346 1347
	if (!fp)
		return -ENOMEM;
1348

1349 1350 1351
	memcpy(fp->insns, fprog->filter, fsize);

	fp->len = fprog->len;
1352 1353 1354 1355 1356
	/* Since unattached filters are not copied back to user
	 * space through sk_get_filter(), we do not need to hold
	 * a copy here, and can spare us the work.
	 */
	fp->orig_prog = NULL;
1357

1358
	/* bpf_prepare_filter() already takes care of freeing
1359 1360
	 * memory in case something goes wrong.
	 */
1361
	fp = bpf_prepare_filter(fp, NULL);
1362 1363
	if (IS_ERR(fp))
		return PTR_ERR(fp);
1364 1365 1366 1367

	*pfp = fp;
	return 0;
}
1368
EXPORT_SYMBOL_GPL(bpf_prog_create);
1369

1370 1371 1372 1373 1374
/**
 *	bpf_prog_create_from_user - create an unattached filter from user buffer
 *	@pfp: the unattached filter that is created
 *	@fprog: the filter program
 *	@trans: post-classic verifier transformation handler
1375
 *	@save_orig: save classic BPF program
1376 1377 1378 1379 1380 1381
 *
 * This function effectively does the same as bpf_prog_create(), only
 * that it builds up its insns buffer from user space provided buffer.
 * It also allows for passing a bpf_aux_classic_check_t handler.
 */
int bpf_prog_create_from_user(struct bpf_prog **pfp, struct sock_fprog *fprog,
1382
			      bpf_aux_classic_check_t trans, bool save_orig)
1383 1384 1385
{
	unsigned int fsize = bpf_classic_proglen(fprog);
	struct bpf_prog *fp;
1386
	int err;
1387 1388

	/* Make sure new filter is there and in the right amounts. */
1389
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
		return -EINVAL;

	fp = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
	if (!fp)
		return -ENOMEM;

	if (copy_from_user(fp->insns, fprog->filter, fsize)) {
		__bpf_prog_free(fp);
		return -EFAULT;
	}

	fp->len = fprog->len;
	fp->orig_prog = NULL;

1404 1405 1406 1407 1408 1409 1410 1411
	if (save_orig) {
		err = bpf_prog_store_orig_filter(fp, fprog);
		if (err) {
			__bpf_prog_free(fp);
			return -ENOMEM;
		}
	}

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	/* bpf_prepare_filter() already takes care of freeing
	 * memory in case something goes wrong.
	 */
	fp = bpf_prepare_filter(fp, trans);
	if (IS_ERR(fp))
		return PTR_ERR(fp);

	*pfp = fp;
	return 0;
}
1422
EXPORT_SYMBOL_GPL(bpf_prog_create_from_user);
1423

1424
void bpf_prog_destroy(struct bpf_prog *fp)
1425
{
1426
	__bpf_prog_release(fp);
1427
}
1428
EXPORT_SYMBOL_GPL(bpf_prog_destroy);
1429

1430
static int __sk_attach_prog(struct bpf_prog *prog, struct sock *sk)
1431 1432 1433 1434 1435 1436 1437 1438 1439
{
	struct sk_filter *fp, *old_fp;

	fp = kmalloc(sizeof(*fp), GFP_KERNEL);
	if (!fp)
		return -ENOMEM;

	fp->prog = prog;

1440
	if (!__sk_filter_charge(sk, fp)) {
1441 1442 1443
		kfree(fp);
		return -ENOMEM;
	}
1444
	refcount_set(&fp->refcnt, 1);
1445

1446 1447
	old_fp = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
1448
	rcu_assign_pointer(sk->sk_filter, fp);
1449

1450 1451 1452 1453 1454 1455
	if (old_fp)
		sk_filter_uncharge(sk, old_fp);

	return 0;
}

1456 1457
static
struct bpf_prog *__get_filter(struct sock_fprog *fprog, struct sock *sk)
L
Linus Torvalds 已提交
1458
{
1459
	unsigned int fsize = bpf_classic_proglen(fprog);
1460
	struct bpf_prog *prog;
L
Linus Torvalds 已提交
1461 1462
	int err;

1463
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1464
		return ERR_PTR(-EPERM);
1465

L
Linus Torvalds 已提交
1466
	/* Make sure new filter is there and in the right amounts. */
1467
	if (!bpf_check_basics_ok(fprog->filter, fprog->len))
1468
		return ERR_PTR(-EINVAL);
L
Linus Torvalds 已提交
1469

1470
	prog = bpf_prog_alloc(bpf_prog_size(fprog->len), 0);
1471
	if (!prog)
1472
		return ERR_PTR(-ENOMEM);
1473

1474
	if (copy_from_user(prog->insns, fprog->filter, fsize)) {
1475
		__bpf_prog_free(prog);
1476
		return ERR_PTR(-EFAULT);
L
Linus Torvalds 已提交
1477 1478
	}

1479
	prog->len = fprog->len;
L
Linus Torvalds 已提交
1480

1481
	err = bpf_prog_store_orig_filter(prog, fprog);
1482
	if (err) {
1483
		__bpf_prog_free(prog);
1484
		return ERR_PTR(-ENOMEM);
1485 1486
	}

1487
	/* bpf_prepare_filter() already takes care of freeing
1488 1489
	 * memory in case something goes wrong.
	 */
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
	return bpf_prepare_filter(prog, NULL);
}

/**
 *	sk_attach_filter - attach a socket filter
 *	@fprog: the filter program
 *	@sk: the socket to use
 *
 * Attach the user's filter code. We first run some sanity checks on
 * it to make sure it does not explode on us later. If an error
 * occurs or there is insufficient memory for the filter a negative
 * errno code is returned. On success the return is zero.
 */
1503
int sk_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1504 1505 1506 1507
{
	struct bpf_prog *prog = __get_filter(fprog, sk);
	int err;

1508 1509 1510
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1511
	err = __sk_attach_prog(prog, sk);
1512
	if (err < 0) {
1513
		__bpf_prog_release(prog);
1514
		return err;
1515 1516
	}

1517
	return 0;
L
Linus Torvalds 已提交
1518
}
1519
EXPORT_SYMBOL_GPL(sk_attach_filter);
L
Linus Torvalds 已提交
1520

1521
int sk_reuseport_attach_filter(struct sock_fprog *fprog, struct sock *sk)
1522
{
1523
	struct bpf_prog *prog = __get_filter(fprog, sk);
1524
	int err;
1525

1526 1527 1528
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1529 1530 1531 1532 1533 1534
	if (bpf_prog_size(prog->len) > sysctl_optmem_max)
		err = -ENOMEM;
	else
		err = reuseport_attach_prog(sk, prog);

	if (err)
1535 1536
		__bpf_prog_release(prog);

1537
	return err;
1538 1539 1540 1541
}

static struct bpf_prog *__get_bpf(u32 ufd, struct sock *sk)
{
1542
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
1543
		return ERR_PTR(-EPERM);
1544

1545
	return bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
}

int sk_attach_bpf(u32 ufd, struct sock *sk)
{
	struct bpf_prog *prog = __get_bpf(ufd, sk);
	int err;

	if (IS_ERR(prog))
		return PTR_ERR(prog);

1556
	err = __sk_attach_prog(prog, sk);
1557
	if (err < 0) {
1558
		bpf_prog_put(prog);
1559
		return err;
1560 1561 1562 1563 1564
	}

	return 0;
}

1565 1566
int sk_reuseport_attach_bpf(u32 ufd, struct sock *sk)
{
1567
	struct bpf_prog *prog;
1568 1569
	int err;

1570 1571 1572 1573 1574 1575
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

	prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SOCKET_FILTER);
	if (IS_ERR(prog) && PTR_ERR(prog) == -EINVAL)
		prog = bpf_prog_get_type(ufd, BPF_PROG_TYPE_SK_REUSEPORT);
1576 1577 1578
	if (IS_ERR(prog))
		return PTR_ERR(prog);

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT) {
		/* Like other non BPF_PROG_TYPE_SOCKET_FILTER
		 * bpf prog (e.g. sockmap).  It depends on the
		 * limitation imposed by bpf_prog_load().
		 * Hence, sysctl_optmem_max is not checked.
		 */
		if ((sk->sk_type != SOCK_STREAM &&
		     sk->sk_type != SOCK_DGRAM) ||
		    (sk->sk_protocol != IPPROTO_UDP &&
		     sk->sk_protocol != IPPROTO_TCP) ||
		    (sk->sk_family != AF_INET &&
		     sk->sk_family != AF_INET6)) {
			err = -ENOTSUPP;
			goto err_prog_put;
		}
	} else {
		/* BPF_PROG_TYPE_SOCKET_FILTER */
		if (bpf_prog_size(prog->len) > sysctl_optmem_max) {
			err = -ENOMEM;
			goto err_prog_put;
		}
1600 1601
	}

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
	err = reuseport_attach_prog(sk, prog);
err_prog_put:
	if (err)
		bpf_prog_put(prog);

	return err;
}

void sk_reuseport_prog_free(struct bpf_prog *prog)
{
	if (!prog)
		return;

	if (prog->type == BPF_PROG_TYPE_SK_REUSEPORT)
		bpf_prog_put(prog);
	else
		bpf_prog_destroy(prog);
1619 1620
}

1621 1622 1623 1624 1625 1626 1627 1628
struct bpf_scratchpad {
	union {
		__be32 diff[MAX_BPF_STACK / sizeof(__be32)];
		u8     buff[MAX_BPF_STACK];
	};
};

static DEFINE_PER_CPU(struct bpf_scratchpad, bpf_sp);
1629

1630 1631 1632 1633 1634 1635
static inline int __bpf_try_make_writable(struct sk_buff *skb,
					  unsigned int write_len)
{
	return skb_ensure_writable(skb, write_len);
}

1636 1637 1638
static inline int bpf_try_make_writable(struct sk_buff *skb,
					unsigned int write_len)
{
1639
	int err = __bpf_try_make_writable(skb, write_len);
1640

1641
	bpf_compute_data_pointers(skb);
1642 1643 1644
	return err;
}

1645 1646 1647 1648 1649
static int bpf_try_make_head_writable(struct sk_buff *skb)
{
	return bpf_try_make_writable(skb, skb_headlen(skb));
}

1650 1651 1652 1653 1654 1655
static inline void bpf_push_mac_rcsum(struct sk_buff *skb)
{
	if (skb_at_tc_ingress(skb))
		skb_postpush_rcsum(skb, skb_mac_header(skb), skb->mac_len);
}

1656 1657 1658 1659 1660 1661
static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
{
	if (skb_at_tc_ingress(skb))
		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
}

1662 1663
BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
	   const void *, from, u32, len, u64, flags)
1664 1665 1666
{
	void *ptr;

1667
	if (unlikely(flags & ~(BPF_F_RECOMPUTE_CSUM | BPF_F_INVALIDATE_HASH)))
1668
		return -EINVAL;
1669
	if (unlikely(offset > 0xffff))
1670
		return -EFAULT;
1671
	if (unlikely(bpf_try_make_writable(skb, offset + len)))
1672 1673
		return -EFAULT;

1674
	ptr = skb->data + offset;
1675
	if (flags & BPF_F_RECOMPUTE_CSUM)
1676
		__skb_postpull_rcsum(skb, ptr, len, offset);
1677 1678 1679

	memcpy(ptr, from, len);

1680
	if (flags & BPF_F_RECOMPUTE_CSUM)
1681
		__skb_postpush_rcsum(skb, ptr, len, offset);
1682 1683
	if (flags & BPF_F_INVALIDATE_HASH)
		skb_clear_hash(skb);
1684

1685 1686 1687
	return 0;
}

1688
static const struct bpf_func_proto bpf_skb_store_bytes_proto = {
1689 1690 1691 1692 1693
	.func		= bpf_skb_store_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
1694 1695
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE,
1696 1697 1698
	.arg5_type	= ARG_ANYTHING,
};

1699 1700
BPF_CALL_4(bpf_skb_load_bytes, const struct sk_buff *, skb, u32, offset,
	   void *, to, u32, len)
1701 1702 1703
{
	void *ptr;

1704
	if (unlikely(offset > 0xffff))
1705
		goto err_clear;
1706 1707 1708

	ptr = skb_header_pointer(skb, offset, len, to);
	if (unlikely(!ptr))
1709
		goto err_clear;
1710 1711 1712 1713
	if (ptr != to)
		memcpy(to, ptr, len);

	return 0;
1714 1715 1716
err_clear:
	memset(to, 0, len);
	return -EFAULT;
1717 1718
}

1719
static const struct bpf_func_proto bpf_skb_load_bytes_proto = {
1720 1721 1722 1723 1724
	.func		= bpf_skb_load_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
1725 1726
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
1727 1728
};

1729 1730 1731
BPF_CALL_5(bpf_skb_load_bytes_relative, const struct sk_buff *, skb,
	   u32, offset, void *, to, u32, len, u32, start_header)
{
1732 1733 1734
	u8 *end = skb_tail_pointer(skb);
	u8 *net = skb_network_header(skb);
	u8 *mac = skb_mac_header(skb);
1735 1736
	u8 *ptr;

1737
	if (unlikely(offset > 0xffff || len > (end - mac)))
1738 1739 1740 1741
		goto err_clear;

	switch (start_header) {
	case BPF_HDR_START_MAC:
1742
		ptr = mac + offset;
1743 1744
		break;
	case BPF_HDR_START_NET:
1745
		ptr = net + offset;
1746 1747 1748 1749 1750
		break;
	default:
		goto err_clear;
	}

1751
	if (likely(ptr >= mac && ptr + len <= end)) {
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
		memcpy(to, ptr, len);
		return 0;
	}

err_clear:
	memset(to, 0, len);
	return -EFAULT;
}

static const struct bpf_func_proto bpf_skb_load_bytes_relative_proto = {
	.func		= bpf_skb_load_bytes_relative,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
	.arg5_type	= ARG_ANYTHING,
};

1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
BPF_CALL_2(bpf_skb_pull_data, struct sk_buff *, skb, u32, len)
{
	/* Idea is the following: should the needed direct read/write
	 * test fail during runtime, we can pull in more data and redo
	 * again, since implicitly, we invalidate previous checks here.
	 *
	 * Or, since we know how much we need to make read/writeable,
	 * this can be done once at the program beginning for direct
	 * access case. By this we overcome limitations of only current
	 * headroom being accessible.
	 */
	return bpf_try_make_writable(skb, len ? : skb_headlen(skb));
}

static const struct bpf_func_proto bpf_skb_pull_data_proto = {
	.func		= bpf_skb_pull_data,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
static inline int sk_skb_try_make_writable(struct sk_buff *skb,
					   unsigned int write_len)
{
	int err = __bpf_try_make_writable(skb, write_len);

	bpf_compute_data_end_sk_skb(skb);
	return err;
}

BPF_CALL_2(sk_skb_pull_data, struct sk_buff *, skb, u32, len)
{
	/* Idea is the following: should the needed direct read/write
	 * test fail during runtime, we can pull in more data and redo
	 * again, since implicitly, we invalidate previous checks here.
	 *
	 * Or, since we know how much we need to make read/writeable,
	 * this can be done once at the program beginning for direct
	 * access case. By this we overcome limitations of only current
	 * headroom being accessible.
	 */
	return sk_skb_try_make_writable(skb, len ? : skb_headlen(skb));
}

static const struct bpf_func_proto sk_skb_pull_data_proto = {
	.func		= sk_skb_pull_data,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1825 1826
BPF_CALL_5(bpf_l3_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1827
{
1828
	__sum16 *ptr;
1829

1830 1831
	if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK)))
		return -EINVAL;
1832
	if (unlikely(offset > 0xffff || offset & 1))
1833
		return -EFAULT;
1834
	if (unlikely(bpf_try_make_writable(skb, offset + sizeof(*ptr))))
1835 1836
		return -EFAULT;

1837
	ptr = (__sum16 *)(skb->data + offset);
1838
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1839 1840 1841 1842 1843 1844
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		csum_replace_by_diff(ptr, to);
		break;
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
	case 2:
		csum_replace2(ptr, from, to);
		break;
	case 4:
		csum_replace4(ptr, from, to);
		break;
	default:
		return -EINVAL;
	}

	return 0;
}

1858
static const struct bpf_func_proto bpf_l3_csum_replace_proto = {
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
	.func		= bpf_l3_csum_replace,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
	.arg5_type	= ARG_ANYTHING,
};

1869 1870
BPF_CALL_5(bpf_l4_csum_replace, struct sk_buff *, skb, u32, offset,
	   u64, from, u64, to, u64, flags)
1871
{
1872
	bool is_pseudo = flags & BPF_F_PSEUDO_HDR;
1873
	bool is_mmzero = flags & BPF_F_MARK_MANGLED_0;
1874
	bool do_mforce = flags & BPF_F_MARK_ENFORCE;
1875
	__sum16 *ptr;
1876

1877 1878
	if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_MARK_ENFORCE |
			       BPF_F_PSEUDO_HDR | 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 1884
		return -EFAULT;

1885
	ptr = (__sum16 *)(skb->data + offset);
1886
	if (is_mmzero && !do_mforce && !*ptr)
1887
		return 0;
1888

1889
	switch (flags & BPF_F_HDR_FIELD_MASK) {
1890 1891 1892 1893 1894 1895
	case 0:
		if (unlikely(from != 0))
			return -EINVAL;

		inet_proto_csum_replace_by_diff(ptr, skb, to, is_pseudo);
		break;
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
	case 2:
		inet_proto_csum_replace2(ptr, skb, from, to, is_pseudo);
		break;
	case 4:
		inet_proto_csum_replace4(ptr, skb, from, to, is_pseudo);
		break;
	default:
		return -EINVAL;
	}

1906 1907
	if (is_mmzero && !*ptr)
		*ptr = CSUM_MANGLED_0;
1908 1909 1910
	return 0;
}

1911
static const struct bpf_func_proto bpf_l4_csum_replace_proto = {
1912 1913 1914 1915 1916 1917 1918 1919
	.func		= bpf_l4_csum_replace,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
	.arg5_type	= ARG_ANYTHING,
1920 1921
};

1922 1923
BPF_CALL_5(bpf_csum_diff, __be32 *, from, u32, from_size,
	   __be32 *, to, u32, to_size, __wsum, seed)
1924
{
1925
	struct bpf_scratchpad *sp = this_cpu_ptr(&bpf_sp);
1926
	u32 diff_size = from_size + to_size;
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
	int i, j = 0;

	/* This is quite flexible, some examples:
	 *
	 * from_size == 0, to_size > 0,  seed := csum --> pushing data
	 * from_size > 0,  to_size == 0, seed := csum --> pulling data
	 * from_size > 0,  to_size > 0,  seed := 0    --> diffing data
	 *
	 * Even for diffing, from_size and to_size don't need to be equal.
	 */
	if (unlikely(((from_size | to_size) & (sizeof(__be32) - 1)) ||
		     diff_size > sizeof(sp->diff)))
		return -EINVAL;

	for (i = 0; i < from_size / sizeof(__be32); i++, j++)
		sp->diff[j] = ~from[i];
	for (i = 0; i <   to_size / sizeof(__be32); i++, j++)
		sp->diff[j] = to[i];

	return csum_partial(sp->diff, diff_size, seed);
}

1949
static const struct bpf_func_proto bpf_csum_diff_proto = {
1950 1951
	.func		= bpf_csum_diff,
	.gpl_only	= false,
1952
	.pkt_access	= true,
1953
	.ret_type	= RET_INTEGER,
1954
	.arg1_type	= ARG_PTR_TO_MEM_OR_NULL,
1955
	.arg2_type	= ARG_CONST_SIZE_OR_ZERO,
1956
	.arg3_type	= ARG_PTR_TO_MEM_OR_NULL,
1957
	.arg4_type	= ARG_CONST_SIZE_OR_ZERO,
1958 1959 1960
	.arg5_type	= ARG_ANYTHING,
};

1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
BPF_CALL_2(bpf_csum_update, struct sk_buff *, skb, __wsum, csum)
{
	/* The interface is to be used in combination with bpf_csum_diff()
	 * for direct packet writes. csum rotation for alignment as well
	 * as emulating csum_sub() can be done from the eBPF program.
	 */
	if (skb->ip_summed == CHECKSUM_COMPLETE)
		return (skb->csum = csum_add(skb->csum, csum));

	return -ENOTSUPP;
}

static const struct bpf_func_proto bpf_csum_update_proto = {
	.func		= bpf_csum_update,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

1981 1982 1983 1984 1985
static inline int __bpf_rx_skb(struct net_device *dev, struct sk_buff *skb)
{
	return dev_forward_skb(dev, skb);
}

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
static inline int __bpf_rx_skb_no_mac(struct net_device *dev,
				      struct sk_buff *skb)
{
	int ret = ____dev_forward_skb(dev, skb);

	if (likely(!ret)) {
		skb->dev = dev;
		ret = netif_rx(skb);
	}

	return ret;
}

1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
static inline int __bpf_tx_skb(struct net_device *dev, struct sk_buff *skb)
{
	int ret;

	if (unlikely(__this_cpu_read(xmit_recursion) > XMIT_RECURSION_LIMIT)) {
		net_crit_ratelimited("bpf: recursion limit reached on datapath, buggy bpf program?\n");
		kfree_skb(skb);
		return -ENETDOWN;
	}

	skb->dev = dev;

	__this_cpu_inc(xmit_recursion);
	ret = dev_queue_xmit(skb);
	__this_cpu_dec(xmit_recursion);

	return ret;
}

2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
static int __bpf_redirect_no_mac(struct sk_buff *skb, struct net_device *dev,
				 u32 flags)
{
	/* skb->mac_len is not set on normal egress */
	unsigned int mlen = skb->network_header - skb->mac_header;

	__skb_pull(skb, mlen);

	/* At ingress, the mac header has already been pulled once.
	 * At egress, skb_pospull_rcsum has to be done in case that
	 * the skb is originated from ingress (i.e. a forwarded skb)
	 * to ensure that rcsum starts at net header.
	 */
	if (!skb_at_tc_ingress(skb))
		skb_postpull_rcsum(skb, skb_mac_header(skb), mlen);
	skb_pop_mac_header(skb);
	skb_reset_mac_len(skb);
	return flags & BPF_F_INGRESS ?
	       __bpf_rx_skb_no_mac(dev, skb) : __bpf_tx_skb(dev, skb);
}

static int __bpf_redirect_common(struct sk_buff *skb, struct net_device *dev,
				 u32 flags)
{
2042 2043 2044 2045 2046 2047
	/* Verify that a link layer header is carried */
	if (unlikely(skb->mac_header >= skb->network_header)) {
		kfree_skb(skb);
		return -ERANGE;
	}

2048 2049 2050 2051 2052 2053 2054 2055
	bpf_push_mac_rcsum(skb);
	return flags & BPF_F_INGRESS ?
	       __bpf_rx_skb(dev, skb) : __bpf_tx_skb(dev, skb);
}

static int __bpf_redirect(struct sk_buff *skb, struct net_device *dev,
			  u32 flags)
{
2056
	if (dev_is_mac_header_xmit(dev))
2057
		return __bpf_redirect_common(skb, dev, flags);
2058 2059
	else
		return __bpf_redirect_no_mac(skb, dev, flags);
2060 2061
}

2062
BPF_CALL_3(bpf_clone_redirect, struct sk_buff *, skb, u32, ifindex, u64, flags)
2063 2064
{
	struct net_device *dev;
2065 2066
	struct sk_buff *clone;
	int ret;
2067

2068 2069 2070
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return -EINVAL;

2071 2072 2073 2074
	dev = dev_get_by_index_rcu(dev_net(skb->dev), ifindex);
	if (unlikely(!dev))
		return -EINVAL;

2075 2076
	clone = skb_clone(skb, GFP_ATOMIC);
	if (unlikely(!clone))
2077 2078
		return -ENOMEM;

2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
	/* For direct write, we need to keep the invariant that the skbs
	 * we're dealing with need to be uncloned. Should uncloning fail
	 * here, we need to free the just generated clone to unclone once
	 * again.
	 */
	ret = bpf_try_make_head_writable(skb);
	if (unlikely(ret)) {
		kfree_skb(clone);
		return -ENOMEM;
	}

2090
	return __bpf_redirect(clone, dev, flags);
2091 2092
}

2093
static const struct bpf_func_proto bpf_clone_redirect_proto = {
2094 2095 2096 2097 2098 2099 2100 2101
	.func           = bpf_clone_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

2102 2103
DEFINE_PER_CPU(struct bpf_redirect_info, bpf_redirect_info);
EXPORT_PER_CPU_SYMBOL_GPL(bpf_redirect_info);
2104

2105
BPF_CALL_2(bpf_redirect, u32, ifindex, u64, flags)
2106
{
2107
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2108

2109 2110 2111
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return TC_ACT_SHOT;

2112 2113
	ri->ifindex = ifindex;
	ri->flags = flags;
2114

2115 2116 2117 2118 2119
	return TC_ACT_REDIRECT;
}

int skb_do_redirect(struct sk_buff *skb)
{
2120
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
2121 2122 2123 2124 2125 2126 2127 2128 2129
	struct net_device *dev;

	dev = dev_get_by_index_rcu(dev_net(skb->dev), ri->ifindex);
	ri->ifindex = 0;
	if (unlikely(!dev)) {
		kfree_skb(skb);
		return -EINVAL;
	}

2130
	return __bpf_redirect(skb, dev, ri->flags);
2131 2132
}

2133
static const struct bpf_func_proto bpf_redirect_proto = {
2134 2135 2136 2137 2138 2139 2140
	.func           = bpf_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);

	/* If user passes invalid input drop the packet. */
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	tcb->bpf.flags = flags;
	tcb->bpf.sk_redir = __sock_hash_lookup_elem(map, key);
	if (!tcb->bpf.sk_redir)
		return SK_DROP;

	return SK_PASS;
}

static const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
	.func           = bpf_sk_redirect_hash,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_PTR_TO_MAP_KEY,
	.arg4_type      = ARG_ANYTHING,
};

2168 2169
BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
	   struct bpf_map *, map, u32, key, u64, flags)
2170
{
2171
	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
2172

2173
	/* If user passes invalid input drop the packet. */
2174
	if (unlikely(flags & ~(BPF_F_INGRESS)))
2175
		return SK_DROP;
2176

2177
	tcb->bpf.flags = flags;
2178 2179 2180
	tcb->bpf.sk_redir = __sock_map_lookup_elem(map, key);
	if (!tcb->bpf.sk_redir)
		return SK_DROP;
2181

2182
	return SK_PASS;
2183 2184
}

2185
struct sock *do_sk_redirect_map(struct sk_buff *skb)
2186
{
2187
	struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
2188

2189
	return tcb->bpf.sk_redir;
2190 2191 2192 2193 2194 2195
}

static const struct bpf_func_proto bpf_sk_redirect_map_proto = {
	.func           = bpf_sk_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
2196 2197
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
2198
	.arg3_type      = ARG_ANYTHING,
2199
	.arg4_type      = ARG_ANYTHING,
2200 2201
};

2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg_buff *, msg,
	   struct bpf_map *, map, void *, key, u64, flags)
{
	/* If user passes invalid input drop the packet. */
	if (unlikely(flags & ~(BPF_F_INGRESS)))
		return SK_DROP;

	msg->flags = flags;
	msg->sk_redir = __sock_hash_lookup_elem(map, key);
	if (!msg->sk_redir)
		return SK_DROP;

	return SK_PASS;
}

static const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
	.func           = bpf_msg_redirect_hash,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_PTR_TO_MAP_KEY,
	.arg4_type      = ARG_ANYTHING,
};

2227 2228 2229 2230
BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg_buff *, msg,
	   struct bpf_map *, map, u32, key, u64, flags)
{
	/* If user passes invalid input drop the packet. */
2231
	if (unlikely(flags & ~(BPF_F_INGRESS)))
2232 2233 2234
		return SK_DROP;

	msg->flags = flags;
2235 2236 2237
	msg->sk_redir = __sock_map_lookup_elem(map, key);
	if (!msg->sk_redir)
		return SK_DROP;
2238 2239 2240 2241 2242 2243

	return SK_PASS;
}

struct sock *do_msg_redirect_map(struct sk_msg_buff *msg)
{
2244
	return msg->sk_redir;
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
}

static const struct bpf_func_proto bpf_msg_redirect_map_proto = {
	.func           = bpf_msg_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_ANYTHING,
	.arg4_type      = ARG_ANYTHING,
};

2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
BPF_CALL_2(bpf_msg_apply_bytes, struct sk_msg_buff *, msg, u32, bytes)
{
	msg->apply_bytes = bytes;
	return 0;
}

static const struct bpf_func_proto bpf_msg_apply_bytes_proto = {
	.func           = bpf_msg_apply_bytes,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
};

2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
BPF_CALL_2(bpf_msg_cork_bytes, struct sk_msg_buff *, msg, u32, bytes)
{
	msg->cork_bytes = bytes;
	return 0;
}

static const struct bpf_func_proto bpf_msg_cork_bytes_proto = {
	.func           = bpf_msg_cork_bytes,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
};

2285 2286 2287 2288 2289 2290 2291
#define sk_msg_iter_var(var)			\
	do {					\
		var++;				\
		if (var == MAX_SKB_FRAGS)	\
			var = 0;		\
	} while (0)

2292 2293 2294
BPF_CALL_4(bpf_msg_pull_data,
	   struct sk_msg_buff *, msg, u32, start, u32, end, u64, flags)
{
T
Tushar Dave 已提交
2295
	unsigned int len = 0, offset = 0, copy = 0, poffset = 0;
2296
	int bytes = end - start, bytes_sg_total;
2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
	struct scatterlist *sg = msg->sg_data;
	int first_sg, last_sg, i, shift;
	unsigned char *p, *to, *from;
	struct page *page;

	if (unlikely(flags || end <= start))
		return -EINVAL;

	/* First find the starting scatterlist element */
	i = msg->sg_start;
	do {
		len = sg[i].length;
		if (start < offset + len)
			break;
2311
		offset += len;
2312
		sk_msg_iter_var(i);
2313 2314 2315 2316 2317 2318
	} while (i != msg->sg_end);

	if (unlikely(start >= offset + len))
		return -EINVAL;

	first_sg = i;
2319 2320 2321 2322 2323
	/* The start may point into the sg element so we need to also
	 * account for the headroom.
	 */
	bytes_sg_total = start - offset + bytes;
	if (!msg->sg_copy[i] && bytes_sg_total <= len)
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
		goto out;

	/* At this point we need to linearize multiple scatterlist
	 * elements or a single shared page. Either way we need to
	 * copy into a linear buffer exclusively owned by BPF. Then
	 * place the buffer in the scatterlist and fixup the original
	 * entries by removing the entries now in the linear buffer
	 * and shifting the remaining entries. For now we do not try
	 * to copy partial entries to avoid complexity of running out
	 * of sg_entry slots. The downside is reading a single byte
	 * will copy the entire sg entry.
	 */
	do {
		copy += sg[i].length;
2338
		sk_msg_iter_var(i);
2339
		if (bytes_sg_total <= copy)
2340 2341 2342 2343
			break;
	} while (i != msg->sg_end);
	last_sg = i;

2344
	if (unlikely(bytes_sg_total > copy))
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
		return -EINVAL;

	page = alloc_pages(__GFP_NOWARN | GFP_ATOMIC, get_order(copy));
	if (unlikely(!page))
		return -ENOMEM;
	p = page_address(page);

	i = first_sg;
	do {
		from = sg_virt(&sg[i]);
		len = sg[i].length;
T
Tushar Dave 已提交
2356
		to = p + poffset;
2357 2358

		memcpy(to, from, len);
T
Tushar Dave 已提交
2359
		poffset += len;
2360 2361 2362
		sg[i].length = 0;
		put_page(sg_page(&sg[i]));

2363
		sk_msg_iter_var(i);
2364 2365 2366 2367 2368 2369 2370 2371 2372
	} while (i != last_sg);

	sg[first_sg].length = copy;
	sg_set_page(&sg[first_sg], page, copy, 0);

	/* To repair sg ring we need to shift entries. If we only
	 * had a single entry though we can just replace it and
	 * be done. Otherwise walk the ring and shift the entries.
	 */
2373 2374 2375 2376
	WARN_ON_ONCE(last_sg == first_sg);
	shift = last_sg > first_sg ?
		last_sg - first_sg - 1 :
		MAX_SKB_FRAGS - first_sg + last_sg - 1;
2377 2378 2379
	if (!shift)
		goto out;

2380 2381
	i = first_sg;
	sk_msg_iter_var(i);
2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397
	do {
		int move_from;

		if (i + shift >= MAX_SKB_FRAGS)
			move_from = i + shift - MAX_SKB_FRAGS;
		else
			move_from = i + shift;

		if (move_from == msg->sg_end)
			break;

		sg[i] = sg[move_from];
		sg[move_from].length = 0;
		sg[move_from].page_link = 0;
		sg[move_from].offset = 0;

2398
		sk_msg_iter_var(i);
2399 2400 2401 2402 2403
	} while (1);
	msg->sg_end -= shift;
	if (msg->sg_end < 0)
		msg->sg_end += MAX_SKB_FRAGS;
out:
2404
	msg->data = sg_virt(&sg[first_sg]) + start - offset;
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
	msg->data_end = msg->data + bytes;

	return 0;
}

static const struct bpf_func_proto bpf_msg_pull_data_proto = {
	.func		= bpf_msg_pull_data,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
};

2420
BPF_CALL_1(bpf_get_cgroup_classid, const struct sk_buff *, skb)
2421
{
2422
	return task_get_classid(skb);
2423 2424 2425 2426 2427 2428 2429 2430 2431
}

static const struct bpf_func_proto bpf_get_cgroup_classid_proto = {
	.func           = bpf_get_cgroup_classid,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

2432
BPF_CALL_1(bpf_get_route_realm, const struct sk_buff *, skb)
2433
{
2434
	return dst_tclassid(skb);
2435 2436 2437 2438 2439 2440 2441 2442 2443
}

static const struct bpf_func_proto bpf_get_route_realm_proto = {
	.func           = bpf_get_route_realm,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

2444
BPF_CALL_1(bpf_get_hash_recalc, struct sk_buff *, skb)
2445 2446 2447 2448 2449 2450
{
	/* If skb_clear_hash() was called due to mangling, we can
	 * trigger SW recalculation here. Later access to hash
	 * can then use the inline skb->hash via context directly
	 * instead of calling this helper again.
	 */
2451
	return skb_get_hash(skb);
2452 2453 2454 2455 2456 2457 2458 2459 2460
}

static const struct bpf_func_proto bpf_get_hash_recalc_proto = {
	.func		= bpf_get_hash_recalc,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
BPF_CALL_1(bpf_set_hash_invalid, struct sk_buff *, skb)
{
	/* After all direct packet write, this can be used once for
	 * triggering a lazy recalc on next skb_get_hash() invocation.
	 */
	skb_clear_hash(skb);
	return 0;
}

static const struct bpf_func_proto bpf_set_hash_invalid_proto = {
	.func		= bpf_set_hash_invalid,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
BPF_CALL_2(bpf_set_hash, struct sk_buff *, skb, u32, hash)
{
	/* Set user specified hash as L4(+), so that it gets returned
	 * on skb_get_hash() call unless BPF prog later on triggers a
	 * skb_clear_hash().
	 */
	__skb_set_sw_hash(skb, hash, true);
	return 0;
}

static const struct bpf_func_proto bpf_set_hash_proto = {
	.func		= bpf_set_hash,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

2495 2496
BPF_CALL_3(bpf_skb_vlan_push, struct sk_buff *, skb, __be16, vlan_proto,
	   u16, vlan_tci)
2497
{
2498
	int ret;
2499 2500 2501 2502 2503

	if (unlikely(vlan_proto != htons(ETH_P_8021Q) &&
		     vlan_proto != htons(ETH_P_8021AD)))
		vlan_proto = htons(ETH_P_8021Q);

2504
	bpf_push_mac_rcsum(skb);
2505
	ret = skb_vlan_push(skb, vlan_proto, vlan_tci);
2506 2507
	bpf_pull_mac_rcsum(skb);

2508
	bpf_compute_data_pointers(skb);
2509
	return ret;
2510 2511
}

2512
static const struct bpf_func_proto bpf_skb_vlan_push_proto = {
2513 2514 2515 2516 2517 2518 2519 2520
	.func           = bpf_skb_vlan_push,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

2521
BPF_CALL_1(bpf_skb_vlan_pop, struct sk_buff *, skb)
2522
{
2523
	int ret;
2524

2525
	bpf_push_mac_rcsum(skb);
2526
	ret = skb_vlan_pop(skb);
2527 2528
	bpf_pull_mac_rcsum(skb);

2529
	bpf_compute_data_pointers(skb);
2530
	return ret;
2531 2532
}

2533
static const struct bpf_func_proto bpf_skb_vlan_pop_proto = {
2534 2535 2536 2537 2538 2539
	.func           = bpf_skb_vlan_pop,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611
static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
{
	/* Caller already did skb_cow() with len as headroom,
	 * so no need to do it here.
	 */
	skb_push(skb, len);
	memmove(skb->data, skb->data + len, off);
	memset(skb->data + off, 0, len);

	/* No skb_postpush_rcsum(skb, skb->data + off, len)
	 * needed here as it does not change the skb->csum
	 * result for checksum complete when summing over
	 * zeroed blocks.
	 */
	return 0;
}

static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
{
	/* skb_ensure_writable() is not needed here, as we're
	 * already working on an uncloned skb.
	 */
	if (unlikely(!pskb_may_pull(skb, off + len)))
		return -ENOMEM;

	skb_postpull_rcsum(skb, skb->data + off, len);
	memmove(skb->data + len, skb->data, off);
	__skb_pull(skb, len);

	return 0;
}

static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
{
	bool trans_same = skb->transport_header == skb->network_header;
	int ret;

	/* There's no need for __skb_push()/__skb_pull() pair to
	 * get to the start of the mac header as we're guaranteed
	 * to always start from here under eBPF.
	 */
	ret = bpf_skb_generic_push(skb, off, len);
	if (likely(!ret)) {
		skb->mac_header -= len;
		skb->network_header -= len;
		if (trans_same)
			skb->transport_header = skb->network_header;
	}

	return ret;
}

static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
{
	bool trans_same = skb->transport_header == skb->network_header;
	int ret;

	/* Same here, __skb_push()/__skb_pull() pair not needed. */
	ret = bpf_skb_generic_pop(skb, off, len);
	if (likely(!ret)) {
		skb->mac_header += len;
		skb->network_header += len;
		if (trans_same)
			skb->transport_header = skb->network_header;
	}

	return ret;
}

static int bpf_skb_proto_4_to_6(struct sk_buff *skb)
{
	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2612
	u32 off = skb_mac_header_len(skb);
2613 2614
	int ret;

2615 2616 2617 2618
	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
		return -ENOTSUPP;

2619 2620 2621 2622 2623 2624 2625 2626 2627
	ret = skb_cow(skb, len_diff);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2628 2629
		struct skb_shared_info *shinfo = skb_shinfo(skb);

2630 2631
		/* SKB_GSO_TCPV4 needs to be changed into
		 * SKB_GSO_TCPV6.
2632
		 */
2633 2634 2635
		if (shinfo->gso_type & SKB_GSO_TCPV4) {
			shinfo->gso_type &= ~SKB_GSO_TCPV4;
			shinfo->gso_type |=  SKB_GSO_TCPV6;
2636 2637 2638
		}

		/* Due to IPv6 header, MSS needs to be downgraded. */
2639
		skb_decrease_gso_size(shinfo, len_diff);
2640
		/* Header must be checked, and gso_segs recomputed. */
2641 2642
		shinfo->gso_type |= SKB_GSO_DODGY;
		shinfo->gso_segs = 0;
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653
	}

	skb->protocol = htons(ETH_P_IPV6);
	skb_clear_hash(skb);

	return 0;
}

static int bpf_skb_proto_6_to_4(struct sk_buff *skb)
{
	const u32 len_diff = sizeof(struct ipv6hdr) - sizeof(struct iphdr);
2654
	u32 off = skb_mac_header_len(skb);
2655 2656
	int ret;

2657 2658 2659 2660
	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
		return -ENOTSUPP;

2661 2662 2663 2664 2665 2666 2667 2668 2669
	ret = skb_unclone(skb, GFP_ATOMIC);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2670 2671
		struct skb_shared_info *shinfo = skb_shinfo(skb);

2672 2673
		/* SKB_GSO_TCPV6 needs to be changed into
		 * SKB_GSO_TCPV4.
2674
		 */
2675 2676 2677
		if (shinfo->gso_type & SKB_GSO_TCPV6) {
			shinfo->gso_type &= ~SKB_GSO_TCPV6;
			shinfo->gso_type |=  SKB_GSO_TCPV4;
2678 2679 2680
		}

		/* Due to IPv4 header, MSS can be upgraded. */
2681
		skb_increase_gso_size(shinfo, len_diff);
2682
		/* Header must be checked, and gso_segs recomputed. */
2683 2684
		shinfo->gso_type |= SKB_GSO_DODGY;
		shinfo->gso_segs = 0;
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707
	}

	skb->protocol = htons(ETH_P_IP);
	skb_clear_hash(skb);

	return 0;
}

static int bpf_skb_proto_xlat(struct sk_buff *skb, __be16 to_proto)
{
	__be16 from_proto = skb->protocol;

	if (from_proto == htons(ETH_P_IP) &&
	      to_proto == htons(ETH_P_IPV6))
		return bpf_skb_proto_4_to_6(skb);

	if (from_proto == htons(ETH_P_IPV6) &&
	      to_proto == htons(ETH_P_IP))
		return bpf_skb_proto_6_to_4(skb);

	return -ENOTSUPP;
}

2708 2709
BPF_CALL_3(bpf_skb_change_proto, struct sk_buff *, skb, __be16, proto,
	   u64, flags)
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
{
	int ret;

	if (unlikely(flags))
		return -EINVAL;

	/* General idea is that this helper does the basic groundwork
	 * needed for changing the protocol, and eBPF program fills the
	 * rest through bpf_skb_store_bytes(), bpf_lX_csum_replace()
	 * and other helpers, rather than passing a raw buffer here.
	 *
	 * The rationale is to keep this minimal and without a need to
	 * deal with raw packet data. F.e. even if we would pass buffers
	 * here, the program still needs to call the bpf_lX_csum_replace()
	 * helpers anyway. Plus, this way we keep also separation of
	 * concerns, since f.e. bpf_skb_store_bytes() should only take
	 * care of stores.
	 *
	 * Currently, additional options and extension header space are
	 * not supported, but flags register is reserved so we can adapt
	 * that. For offloads, we mark packet as dodgy, so that headers
	 * need to be verified first.
	 */
	ret = bpf_skb_proto_xlat(skb, proto);
2734
	bpf_compute_data_pointers(skb);
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
	return ret;
}

static const struct bpf_func_proto bpf_skb_change_proto_proto = {
	.func		= bpf_skb_change_proto,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

2747
BPF_CALL_2(bpf_skb_change_type, struct sk_buff *, skb, u32, pkt_type)
2748 2749
{
	/* We only allow a restricted subset to be changed for now. */
2750 2751
	if (unlikely(!skb_pkt_type_ok(skb->pkt_type) ||
		     !skb_pkt_type_ok(pkt_type)))
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
		return -EINVAL;

	skb->pkt_type = pkt_type;
	return 0;
}

static const struct bpf_func_proto bpf_skb_change_type_proto = {
	.func		= bpf_skb_change_type,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
static u32 bpf_skb_net_base_len(const struct sk_buff *skb)
{
	switch (skb->protocol) {
	case htons(ETH_P_IP):
		return sizeof(struct iphdr);
	case htons(ETH_P_IPV6):
		return sizeof(struct ipv6hdr);
	default:
		return ~0U;
	}
}

static int bpf_skb_net_grow(struct sk_buff *skb, u32 len_diff)
{
	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
	int ret;

2783 2784 2785 2786
	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
		return -ENOTSUPP;

2787 2788 2789 2790 2791 2792 2793 2794 2795
	ret = skb_cow(skb, len_diff);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_push(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2796 2797
		struct skb_shared_info *shinfo = skb_shinfo(skb);

2798
		/* Due to header grow, MSS needs to be downgraded. */
2799
		skb_decrease_gso_size(shinfo, len_diff);
2800
		/* Header must be checked, and gso_segs recomputed. */
2801 2802
		shinfo->gso_type |= SKB_GSO_DODGY;
		shinfo->gso_segs = 0;
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
	}

	return 0;
}

static int bpf_skb_net_shrink(struct sk_buff *skb, u32 len_diff)
{
	u32 off = skb_mac_header_len(skb) + bpf_skb_net_base_len(skb);
	int ret;

2813 2814 2815 2816
	/* SCTP uses GSO_BY_FRAGS, thus cannot adjust it. */
	if (skb_is_gso(skb) && unlikely(skb_is_gso_sctp(skb)))
		return -ENOTSUPP;

2817 2818 2819 2820 2821 2822 2823 2824 2825
	ret = skb_unclone(skb, GFP_ATOMIC);
	if (unlikely(ret < 0))
		return ret;

	ret = bpf_skb_net_hdr_pop(skb, off, len_diff);
	if (unlikely(ret < 0))
		return ret;

	if (skb_is_gso(skb)) {
2826 2827
		struct skb_shared_info *shinfo = skb_shinfo(skb);

2828
		/* Due to header shrink, MSS can be upgraded. */
2829
		skb_increase_gso_size(shinfo, len_diff);
2830
		/* Header must be checked, and gso_segs recomputed. */
2831 2832
		shinfo->gso_type |= SKB_GSO_DODGY;
		shinfo->gso_segs = 0;
2833 2834 2835 2836 2837 2838 2839
	}

	return 0;
}

static u32 __bpf_skb_max_len(const struct sk_buff *skb)
{
2840 2841
	return skb->dev ? skb->dev->mtu + skb->dev->hard_header_len :
			  SKB_MAX_ALLOC;
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
}

static int bpf_skb_adjust_net(struct sk_buff *skb, s32 len_diff)
{
	bool trans_same = skb->transport_header == skb->network_header;
	u32 len_cur, len_diff_abs = abs(len_diff);
	u32 len_min = bpf_skb_net_base_len(skb);
	u32 len_max = __bpf_skb_max_len(skb);
	__be16 proto = skb->protocol;
	bool shrink = len_diff < 0;
	int ret;

	if (unlikely(len_diff_abs > 0xfffU))
		return -EFAULT;
	if (unlikely(proto != htons(ETH_P_IP) &&
		     proto != htons(ETH_P_IPV6)))
		return -ENOTSUPP;

	len_cur = skb->len - skb_network_offset(skb);
	if (skb_transport_header_was_set(skb) && !trans_same)
		len_cur = skb_network_header_len(skb);
	if ((shrink && (len_diff_abs >= len_cur ||
			len_cur - len_diff_abs < len_min)) ||
	    (!shrink && (skb->len + len_diff_abs > len_max &&
			 !skb_is_gso(skb))))
		return -ENOTSUPP;

	ret = shrink ? bpf_skb_net_shrink(skb, len_diff_abs) :
		       bpf_skb_net_grow(skb, len_diff_abs);

2872
	bpf_compute_data_pointers(skb);
2873
	return ret;
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
}

BPF_CALL_4(bpf_skb_adjust_room, struct sk_buff *, skb, s32, len_diff,
	   u32, mode, u64, flags)
{
	if (unlikely(flags))
		return -EINVAL;
	if (likely(mode == BPF_ADJ_ROOM_NET))
		return bpf_skb_adjust_net(skb, len_diff);

	return -ENOTSUPP;
}

static const struct bpf_func_proto bpf_skb_adjust_room_proto = {
	.func		= bpf_skb_adjust_room,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_ANYTHING,
};

2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
static u32 __bpf_skb_min_len(const struct sk_buff *skb)
{
	u32 min_len = skb_network_offset(skb);

	if (skb_transport_header_was_set(skb))
		min_len = skb_transport_offset(skb);
	if (skb->ip_summed == CHECKSUM_PARTIAL)
		min_len = skb_checksum_start_offset(skb) +
			  skb->csum_offset + sizeof(__sum16);
	return min_len;
}

static int bpf_skb_grow_rcsum(struct sk_buff *skb, unsigned int new_len)
{
	unsigned int old_len = skb->len;
	int ret;

	ret = __skb_grow_rcsum(skb, new_len);
	if (!ret)
		memset(skb->data + old_len, 0, new_len - old_len);
	return ret;
}

static int bpf_skb_trim_rcsum(struct sk_buff *skb, unsigned int new_len)
{
	return __skb_trim_rcsum(skb, new_len);
}

2925 2926
static inline int __bpf_skb_change_tail(struct sk_buff *skb, u32 new_len,
					u64 flags)
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
{
	u32 max_len = __bpf_skb_max_len(skb);
	u32 min_len = __bpf_skb_min_len(skb);
	int ret;

	if (unlikely(flags || new_len > max_len || new_len < min_len))
		return -EINVAL;
	if (skb->encapsulation)
		return -ENOTSUPP;

	/* The basic idea of this helper is that it's performing the
	 * needed work to either grow or trim an skb, and eBPF program
	 * rewrites the rest via helpers like bpf_skb_store_bytes(),
	 * bpf_lX_csum_replace() and others rather than passing a raw
	 * buffer here. This one is a slow path helper and intended
	 * for replies with control messages.
	 *
	 * Like in bpf_skb_change_proto(), we want to keep this rather
	 * minimal and without protocol specifics so that we are able
	 * to separate concerns as in bpf_skb_store_bytes() should only
	 * be the one responsible for writing buffers.
	 *
	 * It's really expected to be a slow path operation here for
	 * control message replies, so we're implicitly linearizing,
	 * uncloning and drop offloads from the skb by this.
	 */
	ret = __bpf_try_make_writable(skb, skb->len);
	if (!ret) {
		if (new_len > skb->len)
			ret = bpf_skb_grow_rcsum(skb, new_len);
		else if (new_len < skb->len)
			ret = bpf_skb_trim_rcsum(skb, new_len);
		if (!ret && skb_is_gso(skb))
			skb_gso_reset(skb);
	}
2962 2963 2964 2965 2966 2967 2968
	return ret;
}

BPF_CALL_3(bpf_skb_change_tail, struct sk_buff *, skb, u32, new_len,
	   u64, flags)
{
	int ret = __bpf_skb_change_tail(skb, new_len, flags);
2969

2970
	bpf_compute_data_pointers(skb);
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982
	return ret;
}

static const struct bpf_func_proto bpf_skb_change_tail_proto = {
	.func		= bpf_skb_change_tail,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

2983
BPF_CALL_3(sk_skb_change_tail, struct sk_buff *, skb, u32, new_len,
2984
	   u64, flags)
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
{
	int ret = __bpf_skb_change_tail(skb, new_len, flags);

	bpf_compute_data_end_sk_skb(skb);
	return ret;
}

static const struct bpf_func_proto sk_skb_change_tail_proto = {
	.func		= sk_skb_change_tail,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

static inline int __bpf_skb_change_head(struct sk_buff *skb, u32 head_room,
					u64 flags)
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
{
	u32 max_len = __bpf_skb_max_len(skb);
	u32 new_len = skb->len + head_room;
	int ret;

	if (unlikely(flags || (!skb_is_gso(skb) && new_len > max_len) ||
		     new_len < skb->len))
		return -EINVAL;

	ret = skb_cow(skb, head_room);
	if (likely(!ret)) {
		/* Idea for this helper is that we currently only
		 * allow to expand on mac header. This means that
		 * skb->protocol network header, etc, stay as is.
		 * Compared to bpf_skb_change_tail(), we're more
		 * flexible due to not needing to linearize or
		 * reset GSO. Intention for this helper is to be
		 * used by an L3 skb that needs to push mac header
		 * for redirection into L2 device.
		 */
		__skb_push(skb, head_room);
		memset(skb->data, 0, head_room);
		skb_reset_mac_header(skb);
	}

3028 3029 3030 3031 3032 3033 3034 3035
	return ret;
}

BPF_CALL_3(bpf_skb_change_head, struct sk_buff *, skb, u32, head_room,
	   u64, flags)
{
	int ret = __bpf_skb_change_head(skb, head_room, flags);

3036
	bpf_compute_data_pointers(skb);
3037
	return ret;
3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048
}

static const struct bpf_func_proto bpf_skb_change_head_proto = {
	.func		= bpf_skb_change_head,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};

3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
BPF_CALL_3(sk_skb_change_head, struct sk_buff *, skb, u32, head_room,
	   u64, flags)
{
	int ret = __bpf_skb_change_head(skb, head_room, flags);

	bpf_compute_data_end_sk_skb(skb);
	return ret;
}

static const struct bpf_func_proto sk_skb_change_head_proto = {
	.func		= sk_skb_change_head,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};
3066 3067 3068 3069 3070 3071
static unsigned long xdp_get_metalen(const struct xdp_buff *xdp)
{
	return xdp_data_meta_unsupported(xdp) ? 0 :
	       xdp->data - xdp->data_meta;
}

3072 3073
BPF_CALL_2(bpf_xdp_adjust_head, struct xdp_buff *, xdp, int, offset)
{
3074
	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3075
	unsigned long metalen = xdp_get_metalen(xdp);
3076
	void *data_start = xdp_frame_end + metalen;
3077 3078
	void *data = xdp->data + offset;

3079
	if (unlikely(data < data_start ||
3080 3081 3082
		     data > xdp->data_end - ETH_HLEN))
		return -EINVAL;

3083 3084 3085 3086
	if (metalen)
		memmove(xdp->data_meta + offset,
			xdp->data_meta, metalen);
	xdp->data_meta += offset;
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099
	xdp->data = data;

	return 0;
}

static const struct bpf_func_proto bpf_xdp_adjust_head_proto = {
	.func		= bpf_xdp_adjust_head,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
BPF_CALL_2(bpf_xdp_adjust_tail, struct xdp_buff *, xdp, int, offset)
{
	void *data_end = xdp->data_end + offset;

	/* only shrinking is allowed for now. */
	if (unlikely(offset >= 0))
		return -EINVAL;

	if (unlikely(data_end < xdp->data + ETH_HLEN))
		return -EINVAL;

	xdp->data_end = data_end;

	return 0;
}

static const struct bpf_func_proto bpf_xdp_adjust_tail_proto = {
	.func		= bpf_xdp_adjust_tail,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

3124 3125
BPF_CALL_2(bpf_xdp_adjust_meta, struct xdp_buff *, xdp, int, offset)
{
3126
	void *xdp_frame_end = xdp->data_hard_start + sizeof(struct xdp_frame);
3127 3128 3129 3130 3131
	void *meta = xdp->data_meta + offset;
	unsigned long metalen = xdp->data - meta;

	if (xdp_data_meta_unsupported(xdp))
		return -ENOTSUPP;
3132
	if (unlikely(meta < xdp_frame_end ||
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
		     meta > xdp->data))
		return -EINVAL;
	if (unlikely((metalen & (sizeof(__u32) - 1)) ||
		     (metalen > 32)))
		return -EACCES;

	xdp->data_meta = meta;

	return 0;
}

static const struct bpf_func_proto bpf_xdp_adjust_meta_proto = {
	.func		= bpf_xdp_adjust_meta,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

3152 3153 3154 3155
static int __bpf_tx_xdp(struct net_device *dev,
			struct bpf_map *map,
			struct xdp_buff *xdp,
			u32 index)
3156
{
3157
	struct xdp_frame *xdpf;
3158
	int err, sent;
3159 3160 3161

	if (!dev->netdev_ops->ndo_xdp_xmit) {
		return -EOPNOTSUPP;
3162
	}
3163

3164 3165 3166 3167
	err = xdp_ok_fwd_dev(dev, xdp->data_end - xdp->data);
	if (unlikely(err))
		return err;

3168 3169 3170 3171
	xdpf = convert_to_xdp_frame(xdp);
	if (unlikely(!xdpf))
		return -EOVERFLOW;

3172
	sent = dev->netdev_ops->ndo_xdp_xmit(dev, 1, &xdpf, XDP_XMIT_FLUSH);
3173 3174
	if (sent <= 0)
		return sent;
3175 3176 3177 3178 3179 3180 3181 3182 3183 3184
	return 0;
}

static int __bpf_tx_xdp_map(struct net_device *dev_rx, void *fwd,
			    struct bpf_map *map,
			    struct xdp_buff *xdp,
			    u32 index)
{
	int err;

3185 3186
	switch (map->map_type) {
	case BPF_MAP_TYPE_DEVMAP: {
3187
		struct bpf_dtab_netdev *dst = fwd;
3188

3189
		err = dev_map_enqueue(dst, xdp, dev_rx);
3190
		if (unlikely(err))
3191
			return err;
3192
		__dev_map_insert_ctx(map, index);
3193 3194 3195
		break;
	}
	case BPF_MAP_TYPE_CPUMAP: {
3196 3197 3198
		struct bpf_cpu_map_entry *rcpu = fwd;

		err = cpu_map_enqueue(rcpu, xdp, dev_rx);
3199
		if (unlikely(err))
3200 3201
			return err;
		__cpu_map_insert_ctx(map, index);
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
		break;
	}
	case BPF_MAP_TYPE_XSKMAP: {
		struct xdp_sock *xs = fwd;

		err = __xsk_map_redirect(map, xdp, xs);
		return err;
	}
	default:
		break;
3212
	}
3213
	return 0;
3214 3215
}

3216 3217
void xdp_do_flush_map(void)
{
3218
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3219 3220 3221
	struct bpf_map *map = ri->map_to_flush;

	ri->map_to_flush = NULL;
3222 3223 3224 3225 3226 3227 3228 3229
	if (map) {
		switch (map->map_type) {
		case BPF_MAP_TYPE_DEVMAP:
			__dev_map_flush(map);
			break;
		case BPF_MAP_TYPE_CPUMAP:
			__cpu_map_flush(map);
			break;
3230 3231 3232
		case BPF_MAP_TYPE_XSKMAP:
			__xsk_map_flush(map);
			break;
3233 3234 3235 3236
		default:
			break;
		}
	}
3237 3238 3239
}
EXPORT_SYMBOL_GPL(xdp_do_flush_map);

3240 3241 3242 3243 3244 3245 3246
static void *__xdp_map_lookup_elem(struct bpf_map *map, u32 index)
{
	switch (map->map_type) {
	case BPF_MAP_TYPE_DEVMAP:
		return __dev_map_lookup_elem(map, index);
	case BPF_MAP_TYPE_CPUMAP:
		return __cpu_map_lookup_elem(map, index);
3247 3248
	case BPF_MAP_TYPE_XSKMAP:
		return __xsk_map_lookup_elem(map, index);
3249 3250 3251 3252 3253
	default:
		return NULL;
	}
}

3254
void bpf_clear_redirect_map(struct bpf_map *map)
3255
{
3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
	struct bpf_redirect_info *ri;
	int cpu;

	for_each_possible_cpu(cpu) {
		ri = per_cpu_ptr(&bpf_redirect_info, cpu);
		/* Avoid polluting remote cacheline due to writes if
		 * not needed. Once we pass this test, we need the
		 * cmpxchg() to make sure it hasn't been changed in
		 * the meantime by remote CPU.
		 */
		if (unlikely(READ_ONCE(ri->map) == map))
			cmpxchg(&ri->map, map, NULL);
	}
3269 3270
}

3271
static int xdp_do_redirect_map(struct net_device *dev, struct xdp_buff *xdp,
3272
			       struct bpf_prog *xdp_prog, struct bpf_map *map)
3273
{
3274
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3275
	u32 index = ri->ifindex;
3276
	void *fwd = NULL;
3277
	int err;
3278 3279

	ri->ifindex = 0;
3280
	WRITE_ONCE(ri->map, NULL);
3281

3282
	fwd = __xdp_map_lookup_elem(map, index);
3283 3284
	if (!fwd) {
		err = -EINVAL;
3285
		goto err;
3286
	}
3287
	if (ri->map_to_flush && unlikely(ri->map_to_flush != map))
3288 3289
		xdp_do_flush_map();

3290
	err = __bpf_tx_xdp_map(dev, fwd, map, xdp, index);
3291 3292 3293 3294
	if (unlikely(err))
		goto err;

	ri->map_to_flush = map;
3295
	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
3296 3297
	return 0;
err:
3298
	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
3299 3300 3301
	return err;
}

3302 3303
int xdp_do_redirect(struct net_device *dev, struct xdp_buff *xdp,
		    struct bpf_prog *xdp_prog)
3304
{
3305
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3306
	struct bpf_map *map = READ_ONCE(ri->map);
3307
	struct net_device *fwd;
W
William Tu 已提交
3308
	u32 index = ri->ifindex;
3309
	int err;
3310

3311 3312
	if (map)
		return xdp_do_redirect_map(dev, xdp, xdp_prog, map);
3313

W
William Tu 已提交
3314
	fwd = dev_get_by_index_rcu(dev_net(dev), index);
3315
	ri->ifindex = 0;
3316
	if (unlikely(!fwd)) {
3317
		err = -EINVAL;
3318
		goto err;
3319 3320
	}

3321
	err = __bpf_tx_xdp(fwd, NULL, xdp, 0);
3322 3323 3324 3325 3326 3327 3328
	if (unlikely(err))
		goto err;

	_trace_xdp_redirect(dev, xdp_prog, index);
	return 0;
err:
	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3329
	return err;
3330 3331 3332
}
EXPORT_SYMBOL_GPL(xdp_do_redirect);

3333 3334
static int xdp_do_generic_redirect_map(struct net_device *dev,
				       struct sk_buff *skb,
3335
				       struct xdp_buff *xdp,
3336 3337
				       struct bpf_prog *xdp_prog,
				       struct bpf_map *map)
3338
{
3339
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
W
William Tu 已提交
3340
	u32 index = ri->ifindex;
3341
	void *fwd = NULL;
3342
	int err = 0;
3343 3344

	ri->ifindex = 0;
3345
	WRITE_ONCE(ri->map, NULL);
3346

3347
	fwd = __xdp_map_lookup_elem(map, index);
3348 3349
	if (unlikely(!fwd)) {
		err = -EINVAL;
3350
		goto err;
3351 3352
	}

3353
	if (map->map_type == BPF_MAP_TYPE_DEVMAP) {
3354 3355 3356 3357
		struct bpf_dtab_netdev *dst = fwd;

		err = dev_map_generic_redirect(dst, skb, xdp_prog);
		if (unlikely(err))
3358
			goto err;
3359 3360 3361 3362 3363 3364 3365
	} else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
		struct xdp_sock *xs = fwd;

		err = xsk_generic_rcv(xs, xdp);
		if (err)
			goto err;
		consume_skb(skb);
3366 3367 3368
	} else {
		/* TODO: Handle BPF_MAP_TYPE_CPUMAP */
		err = -EBADRQC;
3369
		goto err;
3370
	}
3371

3372 3373 3374 3375 3376 3377 3378 3379
	_trace_xdp_redirect_map(dev, xdp_prog, fwd, map, index);
	return 0;
err:
	_trace_xdp_redirect_map_err(dev, xdp_prog, fwd, map, index, err);
	return err;
}

int xdp_do_generic_redirect(struct net_device *dev, struct sk_buff *skb,
3380
			    struct xdp_buff *xdp, struct bpf_prog *xdp_prog)
3381
{
3382
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3383
	struct bpf_map *map = READ_ONCE(ri->map);
3384 3385 3386 3387
	u32 index = ri->ifindex;
	struct net_device *fwd;
	int err = 0;

3388 3389 3390
	if (map)
		return xdp_do_generic_redirect_map(dev, skb, xdp, xdp_prog,
						   map);
3391 3392 3393 3394
	ri->ifindex = 0;
	fwd = dev_get_by_index_rcu(dev_net(dev), index);
	if (unlikely(!fwd)) {
		err = -EINVAL;
3395
		goto err;
3396 3397
	}

3398 3399
	err = xdp_ok_fwd_dev(fwd, skb->len);
	if (unlikely(err))
3400 3401
		goto err;

3402
	skb->dev = fwd;
3403
	_trace_xdp_redirect(dev, xdp_prog, index);
3404
	generic_xdp_tx(skb, xdp_prog);
3405 3406
	return 0;
err:
3407
	_trace_xdp_redirect_err(dev, xdp_prog, index, err);
3408
	return err;
3409 3410 3411
}
EXPORT_SYMBOL_GPL(xdp_do_generic_redirect);

3412 3413
BPF_CALL_2(bpf_xdp_redirect, u32, ifindex, u64, flags)
{
3414
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3415 3416 3417 3418 3419 3420

	if (unlikely(flags))
		return XDP_ABORTED;

	ri->ifindex = ifindex;
	ri->flags = flags;
3421
	WRITE_ONCE(ri->map, NULL);
3422

3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
	return XDP_REDIRECT;
}

static const struct bpf_func_proto bpf_xdp_redirect_proto = {
	.func           = bpf_xdp_redirect,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_ANYTHING,
	.arg2_type      = ARG_ANYTHING,
};

3434 3435
BPF_CALL_3(bpf_xdp_redirect_map, struct bpf_map *, map, u32, ifindex,
	   u64, flags)
3436
{
3437
	struct bpf_redirect_info *ri = this_cpu_ptr(&bpf_redirect_info);
3438 3439 3440 3441 3442 3443

	if (unlikely(flags))
		return XDP_ABORTED;

	ri->ifindex = ifindex;
	ri->flags = flags;
3444
	WRITE_ONCE(ri->map, map);
3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457

	return XDP_REDIRECT;
}

static const struct bpf_func_proto bpf_xdp_redirect_map_proto = {
	.func           = bpf_xdp_redirect_map,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_CONST_MAP_PTR,
	.arg2_type      = ARG_ANYTHING,
	.arg3_type      = ARG_ANYTHING,
};

3458
static unsigned long bpf_skb_copy(void *dst_buff, const void *skb,
3459
				  unsigned long off, unsigned long len)
3460
{
3461
	void *ptr = skb_header_pointer(skb, off, len, dst_buff);
3462 3463 3464 3465 3466 3467 3468 3469 3470

	if (unlikely(!ptr))
		return len;
	if (ptr != dst_buff)
		memcpy(dst_buff, ptr, len);

	return 0;
}

3471 3472
BPF_CALL_5(bpf_skb_event_output, struct sk_buff *, skb, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491
{
	u64 skb_size = (flags & BPF_F_CTXLEN_MASK) >> 32;

	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
		return -EINVAL;
	if (unlikely(skb_size > skb->len))
		return -EFAULT;

	return bpf_event_output(map, flags, meta, meta_size, skb, skb_size,
				bpf_skb_copy);
}

static const struct bpf_func_proto bpf_skb_event_output_proto = {
	.func		= bpf_skb_event_output,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
3492
	.arg4_type	= ARG_PTR_TO_MEM,
3493
	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
3494 3495
};

3496 3497 3498 3499 3500
static unsigned short bpf_tunnel_key_af(u64 flags)
{
	return flags & BPF_F_TUNINFO_IPV6 ? AF_INET6 : AF_INET;
}

3501 3502
BPF_CALL_4(bpf_skb_get_tunnel_key, struct sk_buff *, skb, struct bpf_tunnel_key *, to,
	   u32, size, u64, flags)
3503
{
3504 3505
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
	u8 compat[sizeof(struct bpf_tunnel_key)];
3506 3507
	void *to_orig = to;
	int err;
3508

3509 3510 3511 3512 3513 3514 3515 3516
	if (unlikely(!info || (flags & ~(BPF_F_TUNINFO_IPV6)))) {
		err = -EINVAL;
		goto err_clear;
	}
	if (ip_tunnel_info_af(info) != bpf_tunnel_key_af(flags)) {
		err = -EPROTO;
		goto err_clear;
	}
3517
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
3518
		err = -EINVAL;
3519
		switch (size) {
3520
		case offsetof(struct bpf_tunnel_key, tunnel_label):
3521
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3522
			goto set_compat;
3523 3524 3525 3526 3527
		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
			/* Fixup deprecated structure layouts here, so we have
			 * a common path later on.
			 */
			if (ip_tunnel_info_af(info) != AF_INET)
3528
				goto err_clear;
3529
set_compat:
3530 3531 3532
			to = (struct bpf_tunnel_key *)compat;
			break;
		default:
3533
			goto err_clear;
3534 3535
		}
	}
3536 3537

	to->tunnel_id = be64_to_cpu(info->key.tun_id);
3538 3539
	to->tunnel_tos = info->key.tos;
	to->tunnel_ttl = info->key.ttl;
3540
	to->tunnel_ext = 0;
3541

3542
	if (flags & BPF_F_TUNINFO_IPV6) {
3543 3544
		memcpy(to->remote_ipv6, &info->key.u.ipv6.src,
		       sizeof(to->remote_ipv6));
3545 3546
		to->tunnel_label = be32_to_cpu(info->key.label);
	} else {
3547
		to->remote_ipv4 = be32_to_cpu(info->key.u.ipv4.src);
3548 3549
		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
		to->tunnel_label = 0;
3550
	}
3551 3552

	if (unlikely(size != sizeof(struct bpf_tunnel_key)))
3553
		memcpy(to_orig, to, size);
3554 3555

	return 0;
3556 3557 3558
err_clear:
	memset(to_orig, 0, size);
	return err;
3559 3560
}

3561
static const struct bpf_func_proto bpf_skb_get_tunnel_key_proto = {
3562 3563 3564 3565
	.func		= bpf_skb_get_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
3566 3567
	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg3_type	= ARG_CONST_SIZE,
3568 3569 3570
	.arg4_type	= ARG_ANYTHING,
};

3571
BPF_CALL_3(bpf_skb_get_tunnel_opt, struct sk_buff *, skb, u8 *, to, u32, size)
3572 3573
{
	const struct ip_tunnel_info *info = skb_tunnel_info(skb);
3574
	int err;
3575 3576

	if (unlikely(!info ||
3577 3578 3579 3580 3581 3582 3583 3584
		     !(info->key.tun_flags & TUNNEL_OPTIONS_PRESENT))) {
		err = -ENOENT;
		goto err_clear;
	}
	if (unlikely(size < info->options_len)) {
		err = -ENOMEM;
		goto err_clear;
	}
3585 3586

	ip_tunnel_info_opts_get(to, info);
3587 3588
	if (size > info->options_len)
		memset(to + info->options_len, 0, size - info->options_len);
3589 3590

	return info->options_len;
3591 3592 3593
err_clear:
	memset(to, 0, size);
	return err;
3594 3595 3596 3597 3598 3599 3600
}

static const struct bpf_func_proto bpf_skb_get_tunnel_opt_proto = {
	.func		= bpf_skb_get_tunnel_opt,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
3601 3602
	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg3_type	= ARG_CONST_SIZE,
3603 3604
};

3605 3606
static struct metadata_dst __percpu *md_dst;

3607 3608
BPF_CALL_4(bpf_skb_set_tunnel_key, struct sk_buff *, skb,
	   const struct bpf_tunnel_key *, from, u32, size, u64, flags)
3609 3610
{
	struct metadata_dst *md = this_cpu_ptr(md_dst);
3611
	u8 compat[sizeof(struct bpf_tunnel_key)];
3612 3613
	struct ip_tunnel_info *info;

3614
	if (unlikely(flags & ~(BPF_F_TUNINFO_IPV6 | BPF_F_ZERO_CSUM_TX |
3615
			       BPF_F_DONT_FRAGMENT | BPF_F_SEQ_NUMBER)))
3616
		return -EINVAL;
3617 3618
	if (unlikely(size != sizeof(struct bpf_tunnel_key))) {
		switch (size) {
3619
		case offsetof(struct bpf_tunnel_key, tunnel_label):
3620
		case offsetof(struct bpf_tunnel_key, tunnel_ext):
3621 3622 3623 3624 3625 3626
		case offsetof(struct bpf_tunnel_key, remote_ipv6[1]):
			/* Fixup deprecated structure layouts here, so we have
			 * a common path later on.
			 */
			memcpy(compat, from, size);
			memset(compat + size, 0, sizeof(compat) - size);
3627
			from = (const struct bpf_tunnel_key *) compat;
3628 3629 3630 3631 3632
			break;
		default:
			return -EINVAL;
		}
	}
3633 3634
	if (unlikely((!(flags & BPF_F_TUNINFO_IPV6) && from->tunnel_label) ||
		     from->tunnel_ext))
3635
		return -EINVAL;
3636 3637 3638 3639 3640 3641

	skb_dst_drop(skb);
	dst_hold((struct dst_entry *) md);
	skb_dst_set(skb, (struct dst_entry *) md);

	info = &md->u.tun_info;
W
William Tu 已提交
3642
	memset(info, 0, sizeof(*info));
3643
	info->mode = IP_TUNNEL_INFO_TX;
3644

3645
	info->key.tun_flags = TUNNEL_KEY | TUNNEL_CSUM | TUNNEL_NOCACHE;
3646 3647
	if (flags & BPF_F_DONT_FRAGMENT)
		info->key.tun_flags |= TUNNEL_DONT_FRAGMENT;
W
William Tu 已提交
3648 3649
	if (flags & BPF_F_ZERO_CSUM_TX)
		info->key.tun_flags &= ~TUNNEL_CSUM;
3650 3651
	if (flags & BPF_F_SEQ_NUMBER)
		info->key.tun_flags |= TUNNEL_SEQ;
3652

3653
	info->key.tun_id = cpu_to_be64(from->tunnel_id);
3654 3655 3656 3657 3658 3659 3660
	info->key.tos = from->tunnel_tos;
	info->key.ttl = from->tunnel_ttl;

	if (flags & BPF_F_TUNINFO_IPV6) {
		info->mode |= IP_TUNNEL_INFO_IPV6;
		memcpy(&info->key.u.ipv6.dst, from->remote_ipv6,
		       sizeof(from->remote_ipv6));
3661 3662
		info->key.label = cpu_to_be32(from->tunnel_label) &
				  IPV6_FLOWLABEL_MASK;
3663 3664 3665
	} else {
		info->key.u.ipv4.dst = cpu_to_be32(from->remote_ipv4);
	}
3666 3667 3668 3669

	return 0;
}

3670
static const struct bpf_func_proto bpf_skb_set_tunnel_key_proto = {
3671 3672 3673 3674
	.func		= bpf_skb_set_tunnel_key,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
3675 3676
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
3677 3678 3679
	.arg4_type	= ARG_ANYTHING,
};

3680 3681
BPF_CALL_3(bpf_skb_set_tunnel_opt, struct sk_buff *, skb,
	   const u8 *, from, u32, size)
3682 3683 3684 3685 3686 3687
{
	struct ip_tunnel_info *info = skb_tunnel_info(skb);
	const struct metadata_dst *md = this_cpu_ptr(md_dst);

	if (unlikely(info != &md->u.tun_info || (size & (sizeof(u32) - 1))))
		return -EINVAL;
3688
	if (unlikely(size > IP_TUNNEL_OPTS_MAX))
3689 3690
		return -ENOMEM;

3691
	ip_tunnel_info_opts_set(info, from, size, TUNNEL_OPTIONS_PRESENT);
3692 3693 3694 3695 3696 3697 3698 3699 3700

	return 0;
}

static const struct bpf_func_proto bpf_skb_set_tunnel_opt_proto = {
	.func		= bpf_skb_set_tunnel_opt,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
3701 3702
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
3703 3704 3705 3706
};

static const struct bpf_func_proto *
bpf_get_skb_set_tunnel_proto(enum bpf_func_id which)
3707 3708
{
	if (!md_dst) {
3709 3710 3711 3712 3713 3714
		struct metadata_dst __percpu *tmp;

		tmp = metadata_dst_alloc_percpu(IP_TUNNEL_OPTS_MAX,
						METADATA_IP_TUNNEL,
						GFP_KERNEL);
		if (!tmp)
3715
			return NULL;
3716 3717
		if (cmpxchg(&md_dst, NULL, tmp))
			metadata_dst_free_percpu(tmp);
3718
	}
3719 3720 3721 3722 3723 3724 3725 3726 3727

	switch (which) {
	case BPF_FUNC_skb_set_tunnel_key:
		return &bpf_skb_set_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return &bpf_skb_set_tunnel_opt_proto;
	default:
		return NULL;
	}
3728 3729
}

3730 3731
BPF_CALL_3(bpf_skb_under_cgroup, struct sk_buff *, skb, struct bpf_map *, map,
	   u32, idx)
3732 3733 3734 3735 3736
{
	struct bpf_array *array = container_of(map, struct bpf_array, map);
	struct cgroup *cgrp;
	struct sock *sk;

3737
	sk = skb_to_full_sk(skb);
3738 3739
	if (!sk || !sk_fullsock(sk))
		return -ENOENT;
3740
	if (unlikely(idx >= array->map.max_entries))
3741 3742
		return -E2BIG;

3743
	cgrp = READ_ONCE(array->ptrs[idx]);
3744 3745 3746
	if (unlikely(!cgrp))
		return -EAGAIN;

3747
	return sk_under_cgroup_hierarchy(sk, cgrp);
3748 3749
}

3750 3751
static const struct bpf_func_proto bpf_skb_under_cgroup_proto = {
	.func		= bpf_skb_under_cgroup,
3752 3753 3754 3755 3756 3757 3758
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
};

3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777
#ifdef CONFIG_SOCK_CGROUP_DATA
BPF_CALL_1(bpf_skb_cgroup_id, const struct sk_buff *, skb)
{
	struct sock *sk = skb_to_full_sk(skb);
	struct cgroup *cgrp;

	if (!sk || !sk_fullsock(sk))
		return 0;

	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
	return cgrp->kn->id.id;
}

static const struct bpf_func_proto bpf_skb_cgroup_id_proto = {
	.func           = bpf_skb_cgroup_id,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803

BPF_CALL_2(bpf_skb_ancestor_cgroup_id, const struct sk_buff *, skb, int,
	   ancestor_level)
{
	struct sock *sk = skb_to_full_sk(skb);
	struct cgroup *ancestor;
	struct cgroup *cgrp;

	if (!sk || !sk_fullsock(sk))
		return 0;

	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
	ancestor = cgroup_ancestor(cgrp, ancestor_level);
	if (!ancestor)
		return 0;

	return ancestor->kn->id.id;
}

static const struct bpf_func_proto bpf_skb_ancestor_cgroup_id_proto = {
	.func           = bpf_skb_ancestor_cgroup_id,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_ANYTHING,
};
3804 3805
#endif

3806 3807 3808 3809 3810 3811 3812
static unsigned long bpf_xdp_copy(void *dst_buff, const void *src_buff,
				  unsigned long off, unsigned long len)
{
	memcpy(dst_buff, src_buff + off, len);
	return 0;
}

3813 3814
BPF_CALL_5(bpf_xdp_event_output, struct xdp_buff *, xdp, struct bpf_map *, map,
	   u64, flags, void *, meta, u64, meta_size)
3815 3816 3817 3818 3819 3820 3821 3822
{
	u64 xdp_size = (flags & BPF_F_CTXLEN_MASK) >> 32;

	if (unlikely(flags & ~(BPF_F_CTXLEN_MASK | BPF_F_INDEX_MASK)))
		return -EINVAL;
	if (unlikely(xdp_size > (unsigned long)(xdp->data_end - xdp->data)))
		return -EFAULT;

M
Martin KaFai Lau 已提交
3823 3824
	return bpf_event_output(map, flags, meta, meta_size, xdp->data,
				xdp_size, bpf_xdp_copy);
3825 3826 3827 3828 3829 3830 3831 3832 3833
}

static const struct bpf_func_proto bpf_xdp_event_output_proto = {
	.func		= bpf_xdp_event_output,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_CONST_MAP_PTR,
	.arg3_type	= ARG_ANYTHING,
3834
	.arg4_type	= ARG_PTR_TO_MEM,
3835
	.arg5_type	= ARG_CONST_SIZE_OR_ZERO,
3836 3837
};

3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
BPF_CALL_1(bpf_get_socket_cookie, struct sk_buff *, skb)
{
	return skb->sk ? sock_gen_cookie(skb->sk) : 0;
}

static const struct bpf_func_proto bpf_get_socket_cookie_proto = {
	.func           = bpf_get_socket_cookie,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
BPF_CALL_1(bpf_get_socket_cookie_sock_addr, struct bpf_sock_addr_kern *, ctx)
{
	return sock_gen_cookie(ctx->sk);
}

static const struct bpf_func_proto bpf_get_socket_cookie_sock_addr_proto = {
	.func		= bpf_get_socket_cookie_sock_addr,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

BPF_CALL_1(bpf_get_socket_cookie_sock_ops, struct bpf_sock_ops_kern *, ctx)
{
	return sock_gen_cookie(ctx->sk);
}

static const struct bpf_func_proto bpf_get_socket_cookie_sock_ops_proto = {
	.func		= bpf_get_socket_cookie_sock_ops,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
};

3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891
BPF_CALL_1(bpf_get_socket_uid, struct sk_buff *, skb)
{
	struct sock *sk = sk_to_full_sk(skb->sk);
	kuid_t kuid;

	if (!sk || !sk_fullsock(sk))
		return overflowuid;
	kuid = sock_net_uid(sock_net(sk), sk);
	return from_kuid_munged(sock_net(sk)->user_ns, kuid);
}

static const struct bpf_func_proto bpf_get_socket_uid_proto = {
	.func           = bpf_get_socket_uid,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
};

3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
BPF_CALL_5(bpf_setsockopt, struct bpf_sock_ops_kern *, bpf_sock,
	   int, level, int, optname, char *, optval, int, optlen)
{
	struct sock *sk = bpf_sock->sk;
	int ret = 0;
	int val;

	if (!sk_fullsock(sk))
		return -EINVAL;

	if (level == SOL_SOCKET) {
		if (optlen != sizeof(int))
			return -EINVAL;
		val = *((int *)optval);

		/* Only some socketops are supported */
		switch (optname) {
		case SO_RCVBUF:
			sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
			sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
			break;
		case SO_SNDBUF:
			sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
			sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
			break;
		case SO_MAX_PACING_RATE:
			sk->sk_max_pacing_rate = val;
			sk->sk_pacing_rate = min(sk->sk_pacing_rate,
						 sk->sk_max_pacing_rate);
			break;
		case SO_PRIORITY:
			sk->sk_priority = val;
			break;
		case SO_RCVLOWAT:
			if (val < 0)
				val = INT_MAX;
			sk->sk_rcvlowat = val ? : 1;
			break;
		case SO_MARK:
			sk->sk_mark = val;
			break;
		default:
			ret = -EINVAL;
		}
L
Lawrence Brakmo 已提交
3936
#ifdef CONFIG_INET
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
	} else if (level == SOL_IP) {
		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
			return -EINVAL;

		val = *((int *)optval);
		/* Only some options are supported */
		switch (optname) {
		case IP_TOS:
			if (val < -1 || val > 0xff) {
				ret = -EINVAL;
			} else {
				struct inet_sock *inet = inet_sk(sk);

				if (val == -1)
					val = 0;
				inet->tos = val;
			}
			break;
		default:
			ret = -EINVAL;
		}
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
#if IS_ENABLED(CONFIG_IPV6)
	} else if (level == SOL_IPV6) {
		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
			return -EINVAL;

		val = *((int *)optval);
		/* Only some options are supported */
		switch (optname) {
		case IPV6_TCLASS:
			if (val < -1 || val > 0xff) {
				ret = -EINVAL;
			} else {
				struct ipv6_pinfo *np = inet6_sk(sk);

				if (val == -1)
					val = 0;
				np->tclass = val;
			}
			break;
		default:
			ret = -EINVAL;
		}
#endif
3981 3982
	} else if (level == SOL_TCP &&
		   sk->sk_prot->setsockopt == tcp_setsockopt) {
3983 3984
		if (optname == TCP_CONGESTION) {
			char name[TCP_CA_NAME_MAX];
3985
			bool reinit = bpf_sock->op > BPF_SOCK_OPS_NEEDS_ECN;
3986 3987 3988 3989

			strncpy(name, optval, min_t(long, optlen,
						    TCP_CA_NAME_MAX-1));
			name[TCP_CA_NAME_MAX-1] = 0;
3990 3991
			ret = tcp_set_congestion_control(sk, name, false,
							 reinit);
3992
		} else {
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
			struct tcp_sock *tp = tcp_sk(sk);

			if (optlen != sizeof(int))
				return -EINVAL;

			val = *((int *)optval);
			/* Only some options are supported */
			switch (optname) {
			case TCP_BPF_IW:
				if (val <= 0 || tp->data_segs_out > 0)
					ret = -EINVAL;
				else
					tp->snd_cwnd = val;
				break;
4007 4008 4009 4010 4011 4012 4013
			case TCP_BPF_SNDCWND_CLAMP:
				if (val <= 0) {
					ret = -EINVAL;
				} else {
					tp->snd_cwnd_clamp = val;
					tp->snd_ssthresh = val;
				}
4014
				break;
4015 4016 4017 4018 4019 4020
			case TCP_SAVE_SYN:
				if (val < 0 || val > 1)
					ret = -EINVAL;
				else
					tp->save_syn = val;
				break;
4021 4022 4023
			default:
				ret = -EINVAL;
			}
4024 4025
		}
#endif
4026 4027 4028 4029 4030 4031 4032 4033
	} else {
		ret = -EINVAL;
	}
	return ret;
}

static const struct bpf_func_proto bpf_setsockopt_proto = {
	.func		= bpf_setsockopt,
4034
	.gpl_only	= false,
4035 4036 4037 4038 4039 4040 4041 4042
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_PTR_TO_MEM,
	.arg5_type	= ARG_CONST_SIZE,
};

4043 4044 4045
BPF_CALL_5(bpf_getsockopt, struct bpf_sock_ops_kern *, bpf_sock,
	   int, level, int, optname, char *, optval, int, optlen)
{
4046
	struct inet_connection_sock *icsk;
4047
	struct sock *sk = bpf_sock->sk;
4048
	struct tcp_sock *tp;
4049 4050 4051 4052 4053

	if (!sk_fullsock(sk))
		goto err_clear;
#ifdef CONFIG_INET
	if (level == SOL_TCP && sk->sk_prot->getsockopt == tcp_getsockopt) {
4054 4055 4056
		switch (optname) {
		case TCP_CONGESTION:
			icsk = inet_csk(sk);
4057 4058 4059 4060 4061

			if (!icsk->icsk_ca_ops || optlen <= 1)
				goto err_clear;
			strncpy(optval, icsk->icsk_ca_ops->name, optlen);
			optval[optlen - 1] = 0;
4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
			break;
		case TCP_SAVED_SYN:
			tp = tcp_sk(sk);

			if (optlen <= 0 || !tp->saved_syn ||
			    optlen > tp->saved_syn[0])
				goto err_clear;
			memcpy(optval, tp->saved_syn + 1, optlen);
			break;
		default:
4072 4073
			goto err_clear;
		}
4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
	} else if (level == SOL_IP) {
		struct inet_sock *inet = inet_sk(sk);

		if (optlen != sizeof(int) || sk->sk_family != AF_INET)
			goto err_clear;

		/* Only some options are supported */
		switch (optname) {
		case IP_TOS:
			*((int *)optval) = (int)inet->tos;
			break;
		default:
			goto err_clear;
		}
4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
#if IS_ENABLED(CONFIG_IPV6)
	} else if (level == SOL_IPV6) {
		struct ipv6_pinfo *np = inet6_sk(sk);

		if (optlen != sizeof(int) || sk->sk_family != AF_INET6)
			goto err_clear;

		/* Only some options are supported */
		switch (optname) {
		case IPV6_TCLASS:
			*((int *)optval) = (int)np->tclass;
			break;
		default:
			goto err_clear;
		}
#endif
4104 4105 4106
	} else {
		goto err_clear;
	}
4107
	return 0;
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124
#endif
err_clear:
	memset(optval, 0, optlen);
	return -EINVAL;
}

static const struct bpf_func_proto bpf_getsockopt_proto = {
	.func		= bpf_getsockopt,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
	.arg4_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg5_type	= ARG_CONST_SIZE,
};

4125 4126 4127 4128 4129 4130
BPF_CALL_2(bpf_sock_ops_cb_flags_set, struct bpf_sock_ops_kern *, bpf_sock,
	   int, argval)
{
	struct sock *sk = bpf_sock->sk;
	int val = argval & BPF_SOCK_OPS_ALL_CB_FLAGS;

4131
	if (!IS_ENABLED(CONFIG_INET) || !sk_fullsock(sk))
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147
		return -EINVAL;

	if (val)
		tcp_sk(sk)->bpf_sock_ops_cb_flags = val;

	return argval & (~BPF_SOCK_OPS_ALL_CB_FLAGS);
}

static const struct bpf_func_proto bpf_sock_ops_cb_flags_set_proto = {
	.func		= bpf_sock_ops_cb_flags_set,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
};

A
Andrey Ignatov 已提交
4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193
const struct ipv6_bpf_stub *ipv6_bpf_stub __read_mostly;
EXPORT_SYMBOL_GPL(ipv6_bpf_stub);

BPF_CALL_3(bpf_bind, struct bpf_sock_addr_kern *, ctx, struct sockaddr *, addr,
	   int, addr_len)
{
#ifdef CONFIG_INET
	struct sock *sk = ctx->sk;
	int err;

	/* Binding to port can be expensive so it's prohibited in the helper.
	 * Only binding to IP is supported.
	 */
	err = -EINVAL;
	if (addr->sa_family == AF_INET) {
		if (addr_len < sizeof(struct sockaddr_in))
			return err;
		if (((struct sockaddr_in *)addr)->sin_port != htons(0))
			return err;
		return __inet_bind(sk, addr, addr_len, true, false);
#if IS_ENABLED(CONFIG_IPV6)
	} else if (addr->sa_family == AF_INET6) {
		if (addr_len < SIN6_LEN_RFC2133)
			return err;
		if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
			return err;
		/* ipv6_bpf_stub cannot be NULL, since it's called from
		 * bpf_cgroup_inet6_connect hook and ipv6 is already loaded
		 */
		return ipv6_bpf_stub->inet6_bind(sk, addr, addr_len, true, false);
#endif /* CONFIG_IPV6 */
	}
#endif /* CONFIG_INET */

	return -EAFNOSUPPORT;
}

static const struct bpf_func_proto bpf_bind_proto = {
	.func		= bpf_bind,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_PTR_TO_MEM,
	.arg3_type	= ARG_CONST_SIZE,
};

4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
#ifdef CONFIG_XFRM
BPF_CALL_5(bpf_skb_get_xfrm_state, struct sk_buff *, skb, u32, index,
	   struct bpf_xfrm_state *, to, u32, size, u64, flags)
{
	const struct sec_path *sp = skb_sec_path(skb);
	const struct xfrm_state *x;

	if (!sp || unlikely(index >= sp->len || flags))
		goto err_clear;

	x = sp->xvec[index];

	if (unlikely(size != sizeof(struct bpf_xfrm_state)))
		goto err_clear;

	to->reqid = x->props.reqid;
	to->spi = x->id.spi;
	to->family = x->props.family;
4212 4213
	to->ext = 0;

4214 4215 4216 4217 4218
	if (to->family == AF_INET6) {
		memcpy(to->remote_ipv6, x->props.saddr.a6,
		       sizeof(to->remote_ipv6));
	} else {
		to->remote_ipv4 = x->props.saddr.a4;
4219
		memset(&to->remote_ipv6[1], 0, sizeof(__u32) * 3);
4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
	}

	return 0;
err_clear:
	memset(to, 0, size);
	return -EINVAL;
}

static const struct bpf_func_proto bpf_skb_get_xfrm_state_proto = {
	.func		= bpf_skb_get_xfrm_state,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
	.arg5_type	= ARG_ANYTHING,
};
#endif

4240 4241 4242 4243 4244 4245 4246 4247 4248
#if IS_ENABLED(CONFIG_INET) || IS_ENABLED(CONFIG_IPV6)
static int bpf_fib_set_fwd_params(struct bpf_fib_lookup *params,
				  const struct neighbour *neigh,
				  const struct net_device *dev)
{
	memcpy(params->dmac, neigh->ha, ETH_ALEN);
	memcpy(params->smac, dev->dev_addr, ETH_ALEN);
	params->h_vlan_TCI = 0;
	params->h_vlan_proto = 0;
4249
	params->ifindex = dev->ifindex;
4250

4251
	return 0;
4252 4253 4254 4255 4256
}
#endif

#if IS_ENABLED(CONFIG_INET)
static int bpf_ipv4_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4257
			       u32 flags, bool check_mtu)
4258 4259 4260 4261 4262 4263 4264 4265
{
	struct in_device *in_dev;
	struct neighbour *neigh;
	struct net_device *dev;
	struct fib_result res;
	struct fib_nh *nh;
	struct flowi4 fl4;
	int err;
4266
	u32 mtu;
4267 4268 4269 4270 4271 4272 4273 4274

	dev = dev_get_by_index_rcu(net, params->ifindex);
	if (unlikely(!dev))
		return -ENODEV;

	/* verify forwarding is enabled on this interface */
	in_dev = __in_dev_get_rcu(dev);
	if (unlikely(!in_dev || !IN_DEV_FORWARD(in_dev)))
4275
		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299

	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
		fl4.flowi4_iif = 1;
		fl4.flowi4_oif = params->ifindex;
	} else {
		fl4.flowi4_iif = params->ifindex;
		fl4.flowi4_oif = 0;
	}
	fl4.flowi4_tos = params->tos & IPTOS_RT_MASK;
	fl4.flowi4_scope = RT_SCOPE_UNIVERSE;
	fl4.flowi4_flags = 0;

	fl4.flowi4_proto = params->l4_protocol;
	fl4.daddr = params->ipv4_dst;
	fl4.saddr = params->ipv4_src;
	fl4.fl4_sport = params->sport;
	fl4.fl4_dport = params->dport;

	if (flags & BPF_FIB_LOOKUP_DIRECT) {
		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
		struct fib_table *tb;

		tb = fib_get_table(net, tbid);
		if (unlikely(!tb))
4300
			return BPF_FIB_LKUP_RET_NOT_FWDED;
4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311

		err = fib_table_lookup(tb, &fl4, &res, FIB_LOOKUP_NOREF);
	} else {
		fl4.flowi4_mark = 0;
		fl4.flowi4_secid = 0;
		fl4.flowi4_tun_key.tun_id = 0;
		fl4.flowi4_uid = sock_net_uid(net, NULL);

		err = fib_lookup(net, &fl4, &res, FIB_LOOKUP_NOREF);
	}

4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325
	if (err) {
		/* map fib lookup errors to RTN_ type */
		if (err == -EINVAL)
			return BPF_FIB_LKUP_RET_BLACKHOLE;
		if (err == -EHOSTUNREACH)
			return BPF_FIB_LKUP_RET_UNREACHABLE;
		if (err == -EACCES)
			return BPF_FIB_LKUP_RET_PROHIBIT;

		return BPF_FIB_LKUP_RET_NOT_FWDED;
	}

	if (res.type != RTN_UNICAST)
		return BPF_FIB_LKUP_RET_NOT_FWDED;
4326 4327 4328 4329

	if (res.fi->fib_nhs > 1)
		fib_select_path(net, &res, &fl4, NULL);

4330 4331 4332
	if (check_mtu) {
		mtu = ip_mtu_from_fib_result(&res, params->ipv4_dst);
		if (params->tot_len > mtu)
4333
			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4334 4335
	}

4336 4337 4338 4339
	nh = &res.fi->fib_nh[res.nh_sel];

	/* do not handle lwt encaps right now */
	if (nh->nh_lwtstate)
4340
		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351

	dev = nh->nh_dev;
	if (nh->nh_gw)
		params->ipv4_dst = nh->nh_gw;

	params->rt_metric = res.fi->fib_priority;

	/* xdp and cls_bpf programs are run in RCU-bh so
	 * rcu_read_lock_bh is not needed here
	 */
	neigh = __ipv4_neigh_lookup_noref(dev, (__force u32)params->ipv4_dst);
4352 4353
	if (!neigh)
		return BPF_FIB_LKUP_RET_NO_NEIGH;
4354

4355
	return bpf_fib_set_fwd_params(params, neigh, dev);
4356 4357 4358 4359 4360
}
#endif

#if IS_ENABLED(CONFIG_IPV6)
static int bpf_ipv6_fib_lookup(struct net *net, struct bpf_fib_lookup *params,
4361
			       u32 flags, bool check_mtu)
4362 4363 4364 4365 4366 4367 4368 4369 4370 4371
{
	struct in6_addr *src = (struct in6_addr *) params->ipv6_src;
	struct in6_addr *dst = (struct in6_addr *) params->ipv6_dst;
	struct neighbour *neigh;
	struct net_device *dev;
	struct inet6_dev *idev;
	struct fib6_info *f6i;
	struct flowi6 fl6;
	int strict = 0;
	int oif;
4372
	u32 mtu;
4373 4374 4375

	/* link local addresses are never forwarded */
	if (rt6_need_strict(dst) || rt6_need_strict(src))
4376
		return BPF_FIB_LKUP_RET_NOT_FWDED;
4377 4378 4379 4380 4381 4382 4383

	dev = dev_get_by_index_rcu(net, params->ifindex);
	if (unlikely(!dev))
		return -ENODEV;

	idev = __in6_dev_get_safely(dev);
	if (unlikely(!idev || !net->ipv6.devconf_all->forwarding))
4384
		return BPF_FIB_LKUP_RET_FWD_DISABLED;
4385 4386 4387 4388 4389 4390 4391 4392 4393

	if (flags & BPF_FIB_LOOKUP_OUTPUT) {
		fl6.flowi6_iif = 1;
		oif = fl6.flowi6_oif = params->ifindex;
	} else {
		oif = fl6.flowi6_iif = params->ifindex;
		fl6.flowi6_oif = 0;
		strict = RT6_LOOKUP_F_HAS_SADDR;
	}
4394
	fl6.flowlabel = params->flowinfo;
4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410
	fl6.flowi6_scope = 0;
	fl6.flowi6_flags = 0;
	fl6.mp_hash = 0;

	fl6.flowi6_proto = params->l4_protocol;
	fl6.daddr = *dst;
	fl6.saddr = *src;
	fl6.fl6_sport = params->sport;
	fl6.fl6_dport = params->dport;

	if (flags & BPF_FIB_LOOKUP_DIRECT) {
		u32 tbid = l3mdev_fib_table_rcu(dev) ? : RT_TABLE_MAIN;
		struct fib6_table *tb;

		tb = ipv6_stub->fib6_get_table(net, tbid);
		if (unlikely(!tb))
4411
			return BPF_FIB_LKUP_RET_NOT_FWDED;
4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423

		f6i = ipv6_stub->fib6_table_lookup(net, tb, oif, &fl6, strict);
	} else {
		fl6.flowi6_mark = 0;
		fl6.flowi6_secid = 0;
		fl6.flowi6_tun_key.tun_id = 0;
		fl6.flowi6_uid = sock_net_uid(net, NULL);

		f6i = ipv6_stub->fib6_lookup(net, oif, &fl6, strict);
	}

	if (unlikely(IS_ERR_OR_NULL(f6i) || f6i == net->ipv6.fib6_null_entry))
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437
		return BPF_FIB_LKUP_RET_NOT_FWDED;

	if (unlikely(f6i->fib6_flags & RTF_REJECT)) {
		switch (f6i->fib6_type) {
		case RTN_BLACKHOLE:
			return BPF_FIB_LKUP_RET_BLACKHOLE;
		case RTN_UNREACHABLE:
			return BPF_FIB_LKUP_RET_UNREACHABLE;
		case RTN_PROHIBIT:
			return BPF_FIB_LKUP_RET_PROHIBIT;
		default:
			return BPF_FIB_LKUP_RET_NOT_FWDED;
		}
	}
4438

4439 4440
	if (f6i->fib6_type != RTN_UNICAST)
		return BPF_FIB_LKUP_RET_NOT_FWDED;
4441 4442 4443 4444 4445 4446

	if (f6i->fib6_nsiblings && fl6.flowi6_oif == 0)
		f6i = ipv6_stub->fib6_multipath_select(net, f6i, &fl6,
						       fl6.flowi6_oif, NULL,
						       strict);

4447 4448 4449
	if (check_mtu) {
		mtu = ipv6_stub->ip6_mtu_from_fib6(f6i, dst, src);
		if (params->tot_len > mtu)
4450
			return BPF_FIB_LKUP_RET_FRAG_NEEDED;
4451 4452
	}

4453
	if (f6i->fib6_nh.nh_lwtstate)
4454
		return BPF_FIB_LKUP_RET_UNSUPP_LWT;
4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467

	if (f6i->fib6_flags & RTF_GATEWAY)
		*dst = f6i->fib6_nh.nh_gw;

	dev = f6i->fib6_nh.nh_dev;
	params->rt_metric = f6i->fib6_metric;

	/* xdp and cls_bpf programs are run in RCU-bh so rcu_read_lock_bh is
	 * not needed here. Can not use __ipv6_neigh_lookup_noref here
	 * because we need to get nd_tbl via the stub
	 */
	neigh = ___neigh_lookup_noref(ipv6_stub->nd_tbl, neigh_key_eq128,
				      ndisc_hashfn, dst, dev);
4468 4469
	if (!neigh)
		return BPF_FIB_LKUP_RET_NO_NEIGH;
4470

4471
	return bpf_fib_set_fwd_params(params, neigh, dev);
4472 4473 4474 4475 4476 4477 4478 4479 4480
}
#endif

BPF_CALL_4(bpf_xdp_fib_lookup, struct xdp_buff *, ctx,
	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
{
	if (plen < sizeof(*params))
		return -EINVAL;

4481 4482 4483
	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
		return -EINVAL;

4484 4485 4486 4487
	switch (params->family) {
#if IS_ENABLED(CONFIG_INET)
	case AF_INET:
		return bpf_ipv4_fib_lookup(dev_net(ctx->rxq->dev), params,
4488
					   flags, true);
4489 4490 4491 4492
#endif
#if IS_ENABLED(CONFIG_IPV6)
	case AF_INET6:
		return bpf_ipv6_fib_lookup(dev_net(ctx->rxq->dev), params,
4493
					   flags, true);
4494 4495
#endif
	}
4496
	return -EAFNOSUPPORT;
4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511
}

static const struct bpf_func_proto bpf_xdp_fib_lookup_proto = {
	.func		= bpf_xdp_fib_lookup,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_PTR_TO_MEM,
	.arg3_type      = ARG_CONST_SIZE,
	.arg4_type	= ARG_ANYTHING,
};

BPF_CALL_4(bpf_skb_fib_lookup, struct sk_buff *, skb,
	   struct bpf_fib_lookup *, params, int, plen, u32, flags)
{
4512
	struct net *net = dev_net(skb->dev);
4513
	int rc = -EAFNOSUPPORT;
4514

4515 4516 4517
	if (plen < sizeof(*params))
		return -EINVAL;

4518 4519 4520
	if (flags & ~(BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT))
		return -EINVAL;

4521 4522 4523
	switch (params->family) {
#if IS_ENABLED(CONFIG_INET)
	case AF_INET:
4524
		rc = bpf_ipv4_fib_lookup(net, params, flags, false);
4525
		break;
4526 4527 4528
#endif
#if IS_ENABLED(CONFIG_IPV6)
	case AF_INET6:
4529
		rc = bpf_ipv6_fib_lookup(net, params, flags, false);
4530
		break;
4531 4532
#endif
	}
4533

4534
	if (!rc) {
4535 4536
		struct net_device *dev;

4537
		dev = dev_get_by_index_rcu(net, params->ifindex);
4538
		if (!is_skb_forwardable(dev, skb))
4539
			rc = BPF_FIB_LKUP_RET_FRAG_NEEDED;
4540 4541
	}

4542
	return rc;
4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554
}

static const struct bpf_func_proto bpf_skb_fib_lookup_proto = {
	.func		= bpf_skb_fib_lookup,
	.gpl_only	= true,
	.ret_type	= RET_INTEGER,
	.arg1_type      = ARG_PTR_TO_CTX,
	.arg2_type      = ARG_PTR_TO_MEM,
	.arg3_type      = ARG_CONST_SIZE,
	.arg4_type	= ARG_ANYTHING,
};

4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len)
{
	int err;
	struct ipv6_sr_hdr *srh = (struct ipv6_sr_hdr *)hdr;

	if (!seg6_validate_srh(srh, len))
		return -EINVAL;

	switch (type) {
	case BPF_LWT_ENCAP_SEG6_INLINE:
		if (skb->protocol != htons(ETH_P_IPV6))
			return -EBADMSG;

		err = seg6_do_srh_inline(skb, srh);
		break;
	case BPF_LWT_ENCAP_SEG6:
		skb_reset_inner_headers(skb);
		skb->encapsulation = 1;
		err = seg6_do_srh_encap(skb, srh, IPPROTO_IPV6);
		break;
	default:
		return -EINVAL;
	}

	bpf_compute_data_pointers(skb);
	if (err)
		return err;

	ipv6_hdr(skb)->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
	skb_set_transport_header(skb, sizeof(struct ipv6hdr));

	return seg6_lookup_nexthop(skb, NULL, 0);
}
#endif /* CONFIG_IPV6_SEG6_BPF */

BPF_CALL_4(bpf_lwt_push_encap, struct sk_buff *, skb, u32, type, void *, hdr,
	   u32, len)
{
	switch (type) {
#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
	case BPF_LWT_ENCAP_SEG6:
	case BPF_LWT_ENCAP_SEG6_INLINE:
		return bpf_push_seg6_encap(skb, type, hdr, len);
#endif
	default:
		return -EINVAL;
	}
}

static const struct bpf_func_proto bpf_lwt_push_encap_proto = {
	.func		= bpf_lwt_push_encap,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE
};

4615
#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4616 4617 4618 4619 4620
BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
	   const void *, from, u32, len)
{
	struct seg6_bpf_srh_state *srh_state =
		this_cpu_ptr(&seg6_bpf_srh_states);
4621
	struct ipv6_sr_hdr *srh = srh_state->srh;
4622 4623 4624
	void *srh_tlvs, *srh_end, *ptr;
	int srhoff = 0;

4625
	if (srh == NULL)
4626 4627 4628 4629 4630 4631 4632
		return -EINVAL;

	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);

	ptr = skb->data + offset;
	if (ptr >= srh_tlvs && ptr + len <= srh_end)
4633
		srh_state->valid = false;
4634 4635 4636 4637 4638 4639
	else if (ptr < (void *)&srh->flags ||
		 ptr + len > (void *)&srh->segments)
		return -EFAULT;

	if (unlikely(bpf_try_make_writable(skb, offset + len)))
		return -EFAULT;
4640 4641 4642
	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
		return -EINVAL;
	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657

	memcpy(skb->data + offset, from, len);
	return 0;
}

static const struct bpf_func_proto bpf_lwt_seg6_store_bytes_proto = {
	.func		= bpf_lwt_seg6_store_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE
};

4658
static void bpf_update_srh_state(struct sk_buff *skb)
4659 4660 4661 4662 4663
{
	struct seg6_bpf_srh_state *srh_state =
		this_cpu_ptr(&seg6_bpf_srh_states);
	int srhoff = 0;

4664 4665 4666 4667 4668 4669
	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0) {
		srh_state->srh = NULL;
	} else {
		srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
		srh_state->hdrlen = srh_state->srh->hdrlen << 3;
		srh_state->valid = true;
4670
	}
4671 4672 4673 4674 4675 4676 4677 4678 4679
}

BPF_CALL_4(bpf_lwt_seg6_action, struct sk_buff *, skb,
	   u32, action, void *, param, u32, param_len)
{
	struct seg6_bpf_srh_state *srh_state =
		this_cpu_ptr(&seg6_bpf_srh_states);
	int hdroff = 0;
	int err;
4680 4681 4682

	switch (action) {
	case SEG6_LOCAL_ACTION_END_X:
4683 4684
		if (!seg6_bpf_has_valid_srh(skb))
			return -EBADMSG;
4685 4686 4687 4688
		if (param_len != sizeof(struct in6_addr))
			return -EINVAL;
		return seg6_lookup_nexthop(skb, (struct in6_addr *)param, 0);
	case SEG6_LOCAL_ACTION_END_T:
4689 4690
		if (!seg6_bpf_has_valid_srh(skb))
			return -EBADMSG;
4691 4692 4693
		if (param_len != sizeof(int))
			return -EINVAL;
		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
4694 4695 4696
	case SEG6_LOCAL_ACTION_END_DT6:
		if (!seg6_bpf_has_valid_srh(skb))
			return -EBADMSG;
4697 4698
		if (param_len != sizeof(int))
			return -EINVAL;
4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711

		if (ipv6_find_hdr(skb, &hdroff, IPPROTO_IPV6, NULL, NULL) < 0)
			return -EBADMSG;
		if (!pskb_pull(skb, hdroff))
			return -EBADMSG;

		skb_postpull_rcsum(skb, skb_network_header(skb), hdroff);
		skb_reset_network_header(skb);
		skb_reset_transport_header(skb);
		skb->encapsulation = 0;

		bpf_compute_data_pointers(skb);
		bpf_update_srh_state(skb);
4712 4713
		return seg6_lookup_nexthop(skb, NULL, *(int *)param);
	case SEG6_LOCAL_ACTION_END_B6:
4714 4715
		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
			return -EBADMSG;
4716 4717 4718
		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6_INLINE,
					  param, param_len);
		if (!err)
4719 4720
			bpf_update_srh_state(skb);

4721 4722
		return err;
	case SEG6_LOCAL_ACTION_END_B6_ENCAP:
4723 4724
		if (srh_state->srh && !seg6_bpf_has_valid_srh(skb))
			return -EBADMSG;
4725 4726 4727
		err = bpf_push_seg6_encap(skb, BPF_LWT_ENCAP_SEG6,
					  param, param_len);
		if (!err)
4728 4729
			bpf_update_srh_state(skb);

4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750
		return err;
	default:
		return -EINVAL;
	}
}

static const struct bpf_func_proto bpf_lwt_seg6_action_proto = {
	.func		= bpf_lwt_seg6_action,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_MEM,
	.arg4_type	= ARG_CONST_SIZE
};

BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
	   s32, len)
{
	struct seg6_bpf_srh_state *srh_state =
		this_cpu_ptr(&seg6_bpf_srh_states);
4751
	struct ipv6_sr_hdr *srh = srh_state->srh;
4752 4753 4754 4755 4756
	void *srh_end, *srh_tlvs, *ptr;
	struct ipv6hdr *hdr;
	int srhoff = 0;
	int ret;

4757
	if (unlikely(srh == NULL))
4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787
		return -EINVAL;

	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
			((srh->first_segment + 1) << 4));
	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
			srh_state->hdrlen);
	ptr = skb->data + offset;

	if (unlikely(ptr < srh_tlvs || ptr > srh_end))
		return -EFAULT;
	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
		return -EFAULT;

	if (len > 0) {
		ret = skb_cow_head(skb, len);
		if (unlikely(ret < 0))
			return ret;

		ret = bpf_skb_net_hdr_push(skb, offset, len);
	} else {
		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
	}

	bpf_compute_data_pointers(skb);
	if (unlikely(ret < 0))
		return ret;

	hdr = (struct ipv6hdr *)skb->data;
	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));

4788 4789 4790
	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
		return -EINVAL;
	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
4791
	srh_state->hdrlen += len;
4792
	srh_state->valid = false;
4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803
	return 0;
}

static const struct bpf_func_proto bpf_lwt_seg6_adjust_srh_proto = {
	.func		= bpf_lwt_seg6_adjust_srh,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_ANYTHING,
};
4804
#endif /* CONFIG_IPV6_SEG6_BPF */
4805 4806 4807 4808 4809 4810 4811 4812

bool bpf_helper_changes_pkt_data(void *func)
{
	if (func == bpf_skb_vlan_push ||
	    func == bpf_skb_vlan_pop ||
	    func == bpf_skb_store_bytes ||
	    func == bpf_skb_change_proto ||
	    func == bpf_skb_change_head ||
4813
	    func == sk_skb_change_head ||
4814
	    func == bpf_skb_change_tail ||
4815
	    func == sk_skb_change_tail ||
4816 4817
	    func == bpf_skb_adjust_room ||
	    func == bpf_skb_pull_data ||
4818
	    func == sk_skb_pull_data ||
4819 4820 4821 4822 4823 4824 4825
	    func == bpf_clone_redirect ||
	    func == bpf_l3_csum_replace ||
	    func == bpf_l4_csum_replace ||
	    func == bpf_xdp_adjust_head ||
	    func == bpf_xdp_adjust_meta ||
	    func == bpf_msg_pull_data ||
	    func == bpf_xdp_adjust_tail ||
4826
#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
4827 4828
	    func == bpf_lwt_seg6_store_bytes ||
	    func == bpf_lwt_seg6_adjust_srh ||
4829 4830 4831
	    func == bpf_lwt_seg6_action ||
#endif
	    func == bpf_lwt_push_encap)
4832 4833 4834 4835 4836
		return true;

	return false;
}

4837
static const struct bpf_func_proto *
4838
bpf_base_func_proto(enum bpf_func_id func_id)
4839 4840 4841 4842 4843 4844 4845 4846
{
	switch (func_id) {
	case BPF_FUNC_map_lookup_elem:
		return &bpf_map_lookup_elem_proto;
	case BPF_FUNC_map_update_elem:
		return &bpf_map_update_elem_proto;
	case BPF_FUNC_map_delete_elem:
		return &bpf_map_delete_elem_proto;
4847 4848
	case BPF_FUNC_get_prandom_u32:
		return &bpf_get_prandom_u32_proto;
4849
	case BPF_FUNC_get_smp_processor_id:
4850
		return &bpf_get_raw_smp_processor_id_proto;
4851 4852
	case BPF_FUNC_get_numa_node_id:
		return &bpf_get_numa_node_id_proto;
4853 4854
	case BPF_FUNC_tail_call:
		return &bpf_tail_call_proto;
4855 4856
	case BPF_FUNC_ktime_get_ns:
		return &bpf_ktime_get_ns_proto;
4857
	case BPF_FUNC_trace_printk:
4858 4859
		if (capable(CAP_SYS_ADMIN))
			return bpf_get_trace_printk_proto();
4860
		/* else: fall through */
4861 4862 4863 4864 4865
	default:
		return NULL;
	}
}

4866
static const struct bpf_func_proto *
4867
sock_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4868 4869 4870 4871 4872 4873 4874
{
	switch (func_id) {
	/* inet and inet6 sockets are created in a process
	 * context so there is always a valid uid/gid
	 */
	case BPF_FUNC_get_current_uid_gid:
		return &bpf_get_current_uid_gid_proto;
4875 4876
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
4877 4878 4879 4880 4881
	default:
		return bpf_base_func_proto(func_id);
	}
}

A
Andrey Ignatov 已提交
4882 4883 4884 4885 4886 4887 4888 4889 4890
static const struct bpf_func_proto *
sock_addr_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
{
	switch (func_id) {
	/* inet and inet6 sockets are created in a process
	 * context so there is always a valid uid/gid
	 */
	case BPF_FUNC_get_current_uid_gid:
		return &bpf_get_current_uid_gid_proto;
A
Andrey Ignatov 已提交
4891 4892 4893 4894 4895 4896 4897 4898
	case BPF_FUNC_bind:
		switch (prog->expected_attach_type) {
		case BPF_CGROUP_INET4_CONNECT:
		case BPF_CGROUP_INET6_CONNECT:
			return &bpf_bind_proto;
		default:
			return NULL;
		}
4899 4900
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_sock_addr_proto;
4901 4902
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
A
Andrey Ignatov 已提交
4903 4904 4905 4906 4907
	default:
		return bpf_base_func_proto(func_id);
	}
}

4908
static const struct bpf_func_proto *
4909
sk_filter_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4910 4911 4912 4913
{
	switch (func_id) {
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
4914 4915
	case BPF_FUNC_skb_load_bytes_relative:
		return &bpf_skb_load_bytes_relative_proto;
4916 4917
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
4918 4919
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
4920 4921 4922 4923 4924
	default:
		return bpf_base_func_proto(func_id);
	}
}

4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935
static const struct bpf_func_proto *
cg_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
{
	switch (func_id) {
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
	default:
		return sk_filter_func_proto(func_id, prog);
	}
}

4936
static const struct bpf_func_proto *
4937
tc_cls_act_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
4938 4939 4940 4941
{
	switch (func_id) {
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
4942 4943
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
4944 4945
	case BPF_FUNC_skb_load_bytes_relative:
		return &bpf_skb_load_bytes_relative_proto;
4946 4947
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
4948 4949
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
4950 4951
	case BPF_FUNC_csum_update:
		return &bpf_csum_update_proto;
4952 4953 4954 4955
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
4956 4957
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
4958 4959
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
4960 4961 4962 4963
	case BPF_FUNC_skb_vlan_push:
		return &bpf_skb_vlan_push_proto;
	case BPF_FUNC_skb_vlan_pop:
		return &bpf_skb_vlan_pop_proto;
4964 4965
	case BPF_FUNC_skb_change_proto:
		return &bpf_skb_change_proto_proto;
4966 4967
	case BPF_FUNC_skb_change_type:
		return &bpf_skb_change_type_proto;
4968 4969
	case BPF_FUNC_skb_adjust_room:
		return &bpf_skb_adjust_room_proto;
4970 4971
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
4972 4973 4974
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
4975 4976 4977 4978 4979
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_skb_get_tunnel_opt:
		return &bpf_skb_get_tunnel_opt_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return bpf_get_skb_set_tunnel_proto(func_id);
4980 4981
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
4982 4983
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
4984 4985
	case BPF_FUNC_get_hash_recalc:
		return &bpf_get_hash_recalc_proto;
4986 4987
	case BPF_FUNC_set_hash_invalid:
		return &bpf_set_hash_invalid_proto;
4988 4989
	case BPF_FUNC_set_hash:
		return &bpf_set_hash_proto;
4990
	case BPF_FUNC_perf_event_output:
4991
		return &bpf_skb_event_output_proto;
4992 4993
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
4994 4995
	case BPF_FUNC_skb_under_cgroup:
		return &bpf_skb_under_cgroup_proto;
4996 4997
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
4998 4999
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
5000 5001
	case BPF_FUNC_fib_lookup:
		return &bpf_skb_fib_lookup_proto;
5002 5003 5004 5005
#ifdef CONFIG_XFRM
	case BPF_FUNC_skb_get_xfrm_state:
		return &bpf_skb_get_xfrm_state_proto;
#endif
5006 5007 5008
#ifdef CONFIG_SOCK_CGROUP_DATA
	case BPF_FUNC_skb_cgroup_id:
		return &bpf_skb_cgroup_id_proto;
5009 5010
	case BPF_FUNC_skb_ancestor_cgroup_id:
		return &bpf_skb_ancestor_cgroup_id_proto;
5011
#endif
5012
	default:
5013
		return bpf_base_func_proto(func_id);
5014 5015 5016
	}
}

5017
static const struct bpf_func_proto *
5018
xdp_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5019
{
5020 5021 5022
	switch (func_id) {
	case BPF_FUNC_perf_event_output:
		return &bpf_xdp_event_output_proto;
5023 5024
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
5025 5026
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
5027 5028
	case BPF_FUNC_xdp_adjust_head:
		return &bpf_xdp_adjust_head_proto;
5029 5030
	case BPF_FUNC_xdp_adjust_meta:
		return &bpf_xdp_adjust_meta_proto;
5031 5032
	case BPF_FUNC_redirect:
		return &bpf_xdp_redirect_proto;
5033
	case BPF_FUNC_redirect_map:
5034
		return &bpf_xdp_redirect_map_proto;
5035 5036
	case BPF_FUNC_xdp_adjust_tail:
		return &bpf_xdp_adjust_tail_proto;
5037 5038
	case BPF_FUNC_fib_lookup:
		return &bpf_xdp_fib_lookup_proto;
5039
	default:
5040
		return bpf_base_func_proto(func_id);
5041
	}
5042 5043
}

5044
static const struct bpf_func_proto *
5045
sock_ops_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5046 5047 5048 5049
{
	switch (func_id) {
	case BPF_FUNC_setsockopt:
		return &bpf_setsockopt_proto;
5050 5051
	case BPF_FUNC_getsockopt:
		return &bpf_getsockopt_proto;
5052 5053
	case BPF_FUNC_sock_ops_cb_flags_set:
		return &bpf_sock_ops_cb_flags_set_proto;
5054 5055
	case BPF_FUNC_sock_map_update:
		return &bpf_sock_map_update_proto;
5056 5057
	case BPF_FUNC_sock_hash_update:
		return &bpf_sock_hash_update_proto;
5058 5059
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_sock_ops_proto;
5060 5061
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
5062 5063 5064 5065 5066
	default:
		return bpf_base_func_proto(func_id);
	}
}

5067 5068
static const struct bpf_func_proto *
sk_msg_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5069 5070 5071 5072
{
	switch (func_id) {
	case BPF_FUNC_msg_redirect_map:
		return &bpf_msg_redirect_map_proto;
5073 5074
	case BPF_FUNC_msg_redirect_hash:
		return &bpf_msg_redirect_hash_proto;
5075 5076
	case BPF_FUNC_msg_apply_bytes:
		return &bpf_msg_apply_bytes_proto;
5077 5078
	case BPF_FUNC_msg_cork_bytes:
		return &bpf_msg_cork_bytes_proto;
5079 5080
	case BPF_FUNC_msg_pull_data:
		return &bpf_msg_pull_data_proto;
5081 5082
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
5083 5084 5085 5086 5087
	default:
		return bpf_base_func_proto(func_id);
	}
}

5088 5089
static const struct bpf_func_proto *
sk_skb_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5090 5091
{
	switch (func_id) {
5092 5093
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
5094 5095
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
5096
	case BPF_FUNC_skb_pull_data:
5097
		return &sk_skb_pull_data_proto;
5098
	case BPF_FUNC_skb_change_tail:
5099
		return &sk_skb_change_tail_proto;
5100
	case BPF_FUNC_skb_change_head:
5101
		return &sk_skb_change_head_proto;
5102 5103 5104 5105
	case BPF_FUNC_get_socket_cookie:
		return &bpf_get_socket_cookie_proto;
	case BPF_FUNC_get_socket_uid:
		return &bpf_get_socket_uid_proto;
5106 5107
	case BPF_FUNC_sk_redirect_map:
		return &bpf_sk_redirect_map_proto;
5108 5109
	case BPF_FUNC_sk_redirect_hash:
		return &bpf_sk_redirect_hash_proto;
5110 5111
	case BPF_FUNC_get_local_storage:
		return &bpf_get_local_storage_proto;
5112 5113 5114 5115 5116
	default:
		return bpf_base_func_proto(func_id);
	}
}

5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154
static const struct bpf_func_proto *
lwt_out_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
{
	switch (func_id) {
	case BPF_FUNC_skb_load_bytes:
		return &bpf_skb_load_bytes_proto;
	case BPF_FUNC_skb_pull_data:
		return &bpf_skb_pull_data_proto;
	case BPF_FUNC_csum_diff:
		return &bpf_csum_diff_proto;
	case BPF_FUNC_get_cgroup_classid:
		return &bpf_get_cgroup_classid_proto;
	case BPF_FUNC_get_route_realm:
		return &bpf_get_route_realm_proto;
	case BPF_FUNC_get_hash_recalc:
		return &bpf_get_hash_recalc_proto;
	case BPF_FUNC_perf_event_output:
		return &bpf_skb_event_output_proto;
	case BPF_FUNC_get_smp_processor_id:
		return &bpf_get_smp_processor_id_proto;
	case BPF_FUNC_skb_under_cgroup:
		return &bpf_skb_under_cgroup_proto;
	default:
		return bpf_base_func_proto(func_id);
	}
}

static const struct bpf_func_proto *
lwt_in_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
{
	switch (func_id) {
	case BPF_FUNC_lwt_push_encap:
		return &bpf_lwt_push_encap_proto;
	default:
		return lwt_out_func_proto(func_id, prog);
	}
}

5155
static const struct bpf_func_proto *
5156
lwt_xmit_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185
{
	switch (func_id) {
	case BPF_FUNC_skb_get_tunnel_key:
		return &bpf_skb_get_tunnel_key_proto;
	case BPF_FUNC_skb_set_tunnel_key:
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_skb_get_tunnel_opt:
		return &bpf_skb_get_tunnel_opt_proto;
	case BPF_FUNC_skb_set_tunnel_opt:
		return bpf_get_skb_set_tunnel_proto(func_id);
	case BPF_FUNC_redirect:
		return &bpf_redirect_proto;
	case BPF_FUNC_clone_redirect:
		return &bpf_clone_redirect_proto;
	case BPF_FUNC_skb_change_tail:
		return &bpf_skb_change_tail_proto;
	case BPF_FUNC_skb_change_head:
		return &bpf_skb_change_head_proto;
	case BPF_FUNC_skb_store_bytes:
		return &bpf_skb_store_bytes_proto;
	case BPF_FUNC_csum_update:
		return &bpf_csum_update_proto;
	case BPF_FUNC_l3_csum_replace:
		return &bpf_l3_csum_replace_proto;
	case BPF_FUNC_l4_csum_replace:
		return &bpf_l4_csum_replace_proto;
	case BPF_FUNC_set_hash_invalid:
		return &bpf_set_hash_invalid_proto;
	default:
5186
		return lwt_out_func_proto(func_id, prog);
5187 5188 5189
	}
}

5190 5191 5192 5193
static const struct bpf_func_proto *
lwt_seg6local_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
{
	switch (func_id) {
5194
#if IS_ENABLED(CONFIG_IPV6_SEG6_BPF)
5195 5196 5197 5198 5199 5200
	case BPF_FUNC_lwt_seg6_store_bytes:
		return &bpf_lwt_seg6_store_bytes_proto;
	case BPF_FUNC_lwt_seg6_action:
		return &bpf_lwt_seg6_action_proto;
	case BPF_FUNC_lwt_seg6_adjust_srh:
		return &bpf_lwt_seg6_adjust_srh_proto;
5201
#endif
5202 5203
	default:
		return lwt_out_func_proto(func_id, prog);
5204 5205 5206
	}
}

5207
static bool bpf_skb_is_valid_access(int off, int size, enum bpf_access_type type,
5208
				    const struct bpf_prog *prog,
5209
				    struct bpf_insn_access_aux *info)
5210
{
5211
	const int size_default = sizeof(__u32);
5212

5213 5214
	if (off < 0 || off >= sizeof(struct __sk_buff))
		return false;
5215

5216
	/* The verifier guarantees that size > 0. */
5217 5218
	if (off % size != 0)
		return false;
5219 5220

	switch (off) {
5221 5222
	case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
		if (off + size > offsetofend(struct __sk_buff, cb[4]))
5223 5224
			return false;
		break;
5225 5226 5227 5228
	case bpf_ctx_range_till(struct __sk_buff, remote_ip6[0], remote_ip6[3]):
	case bpf_ctx_range_till(struct __sk_buff, local_ip6[0], local_ip6[3]):
	case bpf_ctx_range_till(struct __sk_buff, remote_ip4, remote_ip4):
	case bpf_ctx_range_till(struct __sk_buff, local_ip4, local_ip4):
5229
	case bpf_ctx_range(struct __sk_buff, data):
5230
	case bpf_ctx_range(struct __sk_buff, data_meta):
5231 5232
	case bpf_ctx_range(struct __sk_buff, data_end):
		if (size != size_default)
5233
			return false;
5234 5235
		break;
	default:
5236
		/* Only narrow read access allowed for now. */
5237
		if (type == BPF_WRITE) {
5238
			if (size != size_default)
5239 5240
				return false;
		} else {
5241 5242
			bpf_ctx_record_field_size(info, size_default);
			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
5243
				return false;
5244
		}
5245
	}
5246 5247 5248 5249

	return true;
}

5250
static bool sk_filter_is_valid_access(int off, int size,
5251
				      enum bpf_access_type type,
5252
				      const struct bpf_prog *prog,
5253
				      struct bpf_insn_access_aux *info)
5254
{
5255
	switch (off) {
5256 5257
	case bpf_ctx_range(struct __sk_buff, tc_classid):
	case bpf_ctx_range(struct __sk_buff, data):
5258
	case bpf_ctx_range(struct __sk_buff, data_meta):
5259
	case bpf_ctx_range(struct __sk_buff, data_end):
5260
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5261
		return false;
5262
	}
5263

5264 5265
	if (type == BPF_WRITE) {
		switch (off) {
5266
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5267 5268 5269 5270 5271 5272
			break;
		default:
			return false;
		}
	}

5273
	return bpf_skb_is_valid_access(off, size, type, prog, info);
5274 5275
}

5276 5277
static bool lwt_is_valid_access(int off, int size,
				enum bpf_access_type type,
5278
				const struct bpf_prog *prog,
5279
				struct bpf_insn_access_aux *info)
5280 5281
{
	switch (off) {
5282
	case bpf_ctx_range(struct __sk_buff, tc_classid):
5283
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
5284
	case bpf_ctx_range(struct __sk_buff, data_meta):
5285 5286 5287 5288 5289
		return false;
	}

	if (type == BPF_WRITE) {
		switch (off) {
5290 5291 5292
		case bpf_ctx_range(struct __sk_buff, mark):
		case bpf_ctx_range(struct __sk_buff, priority):
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5293 5294 5295 5296 5297 5298
			break;
		default:
			return false;
		}
	}

5299 5300 5301 5302 5303 5304 5305 5306 5307
	switch (off) {
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
	}

5308
	return bpf_skb_is_valid_access(off, size, type, prog, info);
5309 5310
}

A
Andrey Ignatov 已提交
5311 5312 5313 5314
/* Attach type specific accesses */
static bool __sock_filter_check_attach_type(int off,
					    enum bpf_access_type access_type,
					    enum bpf_attach_type attach_type)
5315
{
A
Andrey Ignatov 已提交
5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344
	switch (off) {
	case offsetof(struct bpf_sock, bound_dev_if):
	case offsetof(struct bpf_sock, mark):
	case offsetof(struct bpf_sock, priority):
		switch (attach_type) {
		case BPF_CGROUP_INET_SOCK_CREATE:
			goto full_access;
		default:
			return false;
		}
	case bpf_ctx_range(struct bpf_sock, src_ip4):
		switch (attach_type) {
		case BPF_CGROUP_INET4_POST_BIND:
			goto read_only;
		default:
			return false;
		}
	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
		switch (attach_type) {
		case BPF_CGROUP_INET6_POST_BIND:
			goto read_only;
		default:
			return false;
		}
	case bpf_ctx_range(struct bpf_sock, src_port):
		switch (attach_type) {
		case BPF_CGROUP_INET4_POST_BIND:
		case BPF_CGROUP_INET6_POST_BIND:
			goto read_only;
5345 5346 5347 5348
		default:
			return false;
		}
	}
A
Andrey Ignatov 已提交
5349 5350 5351 5352 5353 5354 5355 5356 5357 5358
read_only:
	return access_type == BPF_READ;
full_access:
	return true;
}

static bool __sock_filter_check_size(int off, int size,
				     struct bpf_insn_access_aux *info)
{
	const int size_default = sizeof(__u32);
5359

A
Andrey Ignatov 已提交
5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375
	switch (off) {
	case bpf_ctx_range(struct bpf_sock, src_ip4):
	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
		bpf_ctx_record_field_size(info, size_default);
		return bpf_ctx_narrow_access_ok(off, size, size_default);
	}

	return size == size_default;
}

static bool sock_filter_is_valid_access(int off, int size,
					enum bpf_access_type type,
					const struct bpf_prog *prog,
					struct bpf_insn_access_aux *info)
{
	if (off < 0 || off >= sizeof(struct bpf_sock))
5376 5377 5378
		return false;
	if (off % size != 0)
		return false;
A
Andrey Ignatov 已提交
5379 5380 5381 5382
	if (!__sock_filter_check_attach_type(off, type,
					     prog->expected_attach_type))
		return false;
	if (!__sock_filter_check_size(off, size, info))
5383 5384 5385 5386
		return false;
	return true;
}

5387 5388
static int bpf_unclone_prologue(struct bpf_insn *insn_buf, bool direct_write,
				const struct bpf_prog *prog, int drop_verdict)
5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414
{
	struct bpf_insn *insn = insn_buf;

	if (!direct_write)
		return 0;

	/* if (!skb->cloned)
	 *       goto start;
	 *
	 * (Fast-path, otherwise approximation that we might be
	 *  a clone, do the rest in helper.)
	 */
	*insn++ = BPF_LDX_MEM(BPF_B, BPF_REG_6, BPF_REG_1, CLONED_OFFSET());
	*insn++ = BPF_ALU32_IMM(BPF_AND, BPF_REG_6, CLONED_MASK);
	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_6, 0, 7);

	/* ret = bpf_skb_pull_data(skb, 0); */
	*insn++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_1);
	*insn++ = BPF_ALU64_REG(BPF_XOR, BPF_REG_2, BPF_REG_2);
	*insn++ = BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0,
			       BPF_FUNC_skb_pull_data);
	/* if (!ret)
	 *      goto restore;
	 * return TC_ACT_SHOT;
	 */
	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2);
5415
	*insn++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_0, drop_verdict);
5416 5417 5418 5419 5420 5421 5422 5423 5424 5425
	*insn++ = BPF_EXIT_INSN();

	/* restore: */
	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_6);
	/* start: */
	*insn++ = prog->insnsi[0];

	return insn - insn_buf;
}

5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460
static int bpf_gen_ld_abs(const struct bpf_insn *orig,
			  struct bpf_insn *insn_buf)
{
	bool indirect = BPF_MODE(orig->code) == BPF_IND;
	struct bpf_insn *insn = insn_buf;

	/* We're guaranteed here that CTX is in R6. */
	*insn++ = BPF_MOV64_REG(BPF_REG_1, BPF_REG_CTX);
	if (!indirect) {
		*insn++ = BPF_MOV64_IMM(BPF_REG_2, orig->imm);
	} else {
		*insn++ = BPF_MOV64_REG(BPF_REG_2, orig->src_reg);
		if (orig->imm)
			*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, orig->imm);
	}

	switch (BPF_SIZE(orig->code)) {
	case BPF_B:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_8_no_cache);
		break;
	case BPF_H:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_16_no_cache);
		break;
	case BPF_W:
		*insn++ = BPF_EMIT_CALL(bpf_skb_load_helper_32_no_cache);
		break;
	}

	*insn++ = BPF_JMP_IMM(BPF_JSGE, BPF_REG_0, 0, 2);
	*insn++ = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
	*insn++ = BPF_EXIT_INSN();

	return insn - insn_buf;
}

5461 5462 5463 5464 5465 5466
static int tc_cls_act_prologue(struct bpf_insn *insn_buf, bool direct_write,
			       const struct bpf_prog *prog)
{
	return bpf_unclone_prologue(insn_buf, direct_write, prog, TC_ACT_SHOT);
}

5467
static bool tc_cls_act_is_valid_access(int off, int size,
5468
				       enum bpf_access_type type,
5469
				       const struct bpf_prog *prog,
5470
				       struct bpf_insn_access_aux *info)
5471 5472 5473
{
	if (type == BPF_WRITE) {
		switch (off) {
5474 5475 5476 5477 5478
		case bpf_ctx_range(struct __sk_buff, mark):
		case bpf_ctx_range(struct __sk_buff, tc_index):
		case bpf_ctx_range(struct __sk_buff, priority):
		case bpf_ctx_range(struct __sk_buff, tc_classid):
		case bpf_ctx_range_till(struct __sk_buff, cb[0], cb[4]):
5479 5480 5481 5482 5483
			break;
		default:
			return false;
		}
	}
5484

5485 5486 5487 5488
	switch (off) {
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
5489 5490 5491
	case bpf_ctx_range(struct __sk_buff, data_meta):
		info->reg_type = PTR_TO_PACKET_META;
		break;
5492 5493 5494
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
5495 5496
	case bpf_ctx_range_till(struct __sk_buff, family, local_port):
		return false;
5497 5498
	}

5499
	return bpf_skb_is_valid_access(off, size, type, prog, info);
5500 5501
}

5502
static bool __is_valid_xdp_access(int off, int size)
5503 5504 5505 5506 5507
{
	if (off < 0 || off >= sizeof(struct xdp_md))
		return false;
	if (off % size != 0)
		return false;
D
Daniel Borkmann 已提交
5508
	if (size != sizeof(__u32))
5509 5510 5511 5512 5513 5514 5515
		return false;

	return true;
}

static bool xdp_is_valid_access(int off, int size,
				enum bpf_access_type type,
5516
				const struct bpf_prog *prog,
5517
				struct bpf_insn_access_aux *info)
5518
{
5519 5520 5521 5522 5523 5524 5525
	if (type == BPF_WRITE) {
		if (bpf_prog_is_dev_bound(prog->aux)) {
			switch (off) {
			case offsetof(struct xdp_md, rx_queue_index):
				return __is_valid_xdp_access(off, size);
			}
		}
5526
		return false;
5527
	}
5528 5529 5530

	switch (off) {
	case offsetof(struct xdp_md, data):
5531
		info->reg_type = PTR_TO_PACKET;
5532
		break;
5533 5534 5535
	case offsetof(struct xdp_md, data_meta):
		info->reg_type = PTR_TO_PACKET_META;
		break;
5536
	case offsetof(struct xdp_md, data_end):
5537
		info->reg_type = PTR_TO_PACKET_END;
5538 5539 5540
		break;
	}

5541
	return __is_valid_xdp_access(off, size);
5542 5543 5544 5545
}

void bpf_warn_invalid_xdp_action(u32 act)
{
5546 5547 5548 5549 5550
	const u32 act_max = XDP_REDIRECT;

	WARN_ONCE(1, "%s XDP return value %u, expect packet loss!\n",
		  act > act_max ? "Illegal" : "Driver unsupported",
		  act);
5551 5552 5553
}
EXPORT_SYMBOL_GPL(bpf_warn_invalid_xdp_action);

A
Andrey Ignatov 已提交
5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572
static bool sock_addr_is_valid_access(int off, int size,
				      enum bpf_access_type type,
				      const struct bpf_prog *prog,
				      struct bpf_insn_access_aux *info)
{
	const int size_default = sizeof(__u32);

	if (off < 0 || off >= sizeof(struct bpf_sock_addr))
		return false;
	if (off % size != 0)
		return false;

	/* Disallow access to IPv6 fields from IPv4 contex and vise
	 * versa.
	 */
	switch (off) {
	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
		switch (prog->expected_attach_type) {
		case BPF_CGROUP_INET4_BIND:
A
Andrey Ignatov 已提交
5573
		case BPF_CGROUP_INET4_CONNECT:
A
Andrey Ignatov 已提交
5574
		case BPF_CGROUP_UDP4_SENDMSG:
A
Andrey Ignatov 已提交
5575 5576 5577 5578 5579 5580 5581 5582
			break;
		default:
			return false;
		}
		break;
	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
		switch (prog->expected_attach_type) {
		case BPF_CGROUP_INET6_BIND:
A
Andrey Ignatov 已提交
5583
		case BPF_CGROUP_INET6_CONNECT:
A
Andrey Ignatov 已提交
5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601
		case BPF_CGROUP_UDP6_SENDMSG:
			break;
		default:
			return false;
		}
		break;
	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
		switch (prog->expected_attach_type) {
		case BPF_CGROUP_UDP4_SENDMSG:
			break;
		default:
			return false;
		}
		break;
	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
				msg_src_ip6[3]):
		switch (prog->expected_attach_type) {
		case BPF_CGROUP_UDP6_SENDMSG:
A
Andrey Ignatov 已提交
5602 5603 5604 5605 5606 5607 5608 5609 5610 5611
			break;
		default:
			return false;
		}
		break;
	}

	switch (off) {
	case bpf_ctx_range(struct bpf_sock_addr, user_ip4):
	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
A
Andrey Ignatov 已提交
5612 5613 5614
	case bpf_ctx_range(struct bpf_sock_addr, msg_src_ip4):
	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
				msg_src_ip6[3]):
A
Andrey Ignatov 已提交
5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640
		/* Only narrow read access allowed for now. */
		if (type == BPF_READ) {
			bpf_ctx_record_field_size(info, size_default);
			if (!bpf_ctx_narrow_access_ok(off, size, size_default))
				return false;
		} else {
			if (size != size_default)
				return false;
		}
		break;
	case bpf_ctx_range(struct bpf_sock_addr, user_port):
		if (size != size_default)
			return false;
		break;
	default:
		if (type == BPF_READ) {
			if (size != size_default)
				return false;
		} else {
			return false;
		}
	}

	return true;
}

5641 5642
static bool sock_ops_is_valid_access(int off, int size,
				     enum bpf_access_type type,
5643
				     const struct bpf_prog *prog,
5644
				     struct bpf_insn_access_aux *info)
L
Lawrence Brakmo 已提交
5645
{
5646 5647
	const int size_default = sizeof(__u32);

L
Lawrence Brakmo 已提交
5648 5649
	if (off < 0 || off >= sizeof(struct bpf_sock_ops))
		return false;
5650

L
Lawrence Brakmo 已提交
5651 5652 5653 5654 5655 5656
	/* The verifier guarantees that size > 0. */
	if (off % size != 0)
		return false;

	if (type == BPF_WRITE) {
		switch (off) {
5657
		case offsetof(struct bpf_sock_ops, reply):
5658
		case offsetof(struct bpf_sock_ops, sk_txhash):
5659 5660
			if (size != size_default)
				return false;
L
Lawrence Brakmo 已提交
5661 5662 5663 5664
			break;
		default:
			return false;
		}
5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676
	} else {
		switch (off) {
		case bpf_ctx_range_till(struct bpf_sock_ops, bytes_received,
					bytes_acked):
			if (size != sizeof(__u64))
				return false;
			break;
		default:
			if (size != size_default)
				return false;
			break;
		}
L
Lawrence Brakmo 已提交
5677 5678
	}

5679
	return true;
L
Lawrence Brakmo 已提交
5680 5681
}

5682 5683 5684
static int sk_skb_prologue(struct bpf_insn *insn_buf, bool direct_write,
			   const struct bpf_prog *prog)
{
5685
	return bpf_unclone_prologue(insn_buf, direct_write, prog, SK_DROP);
5686 5687
}

5688 5689
static bool sk_skb_is_valid_access(int off, int size,
				   enum bpf_access_type type,
5690
				   const struct bpf_prog *prog,
5691 5692
				   struct bpf_insn_access_aux *info)
{
5693 5694 5695 5696 5697 5698
	switch (off) {
	case bpf_ctx_range(struct __sk_buff, tc_classid):
	case bpf_ctx_range(struct __sk_buff, data_meta):
		return false;
	}

5699 5700 5701 5702 5703 5704 5705 5706 5707 5708
	if (type == BPF_WRITE) {
		switch (off) {
		case bpf_ctx_range(struct __sk_buff, tc_index):
		case bpf_ctx_range(struct __sk_buff, priority):
			break;
		default:
			return false;
		}
	}

5709
	switch (off) {
5710
	case bpf_ctx_range(struct __sk_buff, mark):
5711
		return false;
5712 5713 5714 5715 5716 5717 5718 5719
	case bpf_ctx_range(struct __sk_buff, data):
		info->reg_type = PTR_TO_PACKET;
		break;
	case bpf_ctx_range(struct __sk_buff, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		break;
	}

5720
	return bpf_skb_is_valid_access(off, size, type, prog, info);
5721 5722
}

5723 5724
static bool sk_msg_is_valid_access(int off, int size,
				   enum bpf_access_type type,
5725
				   const struct bpf_prog *prog,
5726 5727 5728 5729 5730 5731 5732 5733
				   struct bpf_insn_access_aux *info)
{
	if (type == BPF_WRITE)
		return false;

	switch (off) {
	case offsetof(struct sk_msg_md, data):
		info->reg_type = PTR_TO_PACKET;
5734 5735
		if (size != sizeof(__u64))
			return false;
5736 5737 5738
		break;
	case offsetof(struct sk_msg_md, data_end):
		info->reg_type = PTR_TO_PACKET_END;
5739 5740
		if (size != sizeof(__u64))
			return false;
5741
		break;
5742 5743 5744
	default:
		if (size != sizeof(__u32))
			return false;
5745 5746 5747 5748 5749 5750 5751 5752 5753 5754
	}

	if (off < 0 || off >= sizeof(struct sk_msg_md))
		return false;
	if (off % size != 0)
		return false;

	return true;
}

5755 5756 5757
static u32 bpf_convert_ctx_access(enum bpf_access_type type,
				  const struct bpf_insn *si,
				  struct bpf_insn *insn_buf,
5758
				  struct bpf_prog *prog, u32 *target_size)
5759 5760
{
	struct bpf_insn *insn = insn_buf;
5761
	int off;
5762

5763
	switch (si->off) {
5764
	case offsetof(struct __sk_buff, len):
5765
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5766 5767
				      bpf_target_off(struct sk_buff, len, 4,
						     target_size));
5768 5769
		break;

5770
	case offsetof(struct __sk_buff, protocol):
5771
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5772 5773
				      bpf_target_off(struct sk_buff, protocol, 2,
						     target_size));
5774 5775
		break;

5776
	case offsetof(struct __sk_buff, vlan_proto):
5777
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5778 5779
				      bpf_target_off(struct sk_buff, vlan_proto, 2,
						     target_size));
5780 5781
		break;

5782
	case offsetof(struct __sk_buff, priority):
5783
		if (type == BPF_WRITE)
5784
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
5785 5786
					      bpf_target_off(struct sk_buff, priority, 4,
							     target_size));
5787
		else
5788
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5789 5790
					      bpf_target_off(struct sk_buff, priority, 4,
							     target_size));
5791 5792
		break;

5793
	case offsetof(struct __sk_buff, ingress_ifindex):
5794
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5795 5796
				      bpf_target_off(struct sk_buff, skb_iif, 4,
						     target_size));
5797 5798 5799
		break;

	case offsetof(struct __sk_buff, ifindex):
5800
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
5801
				      si->dst_reg, si->src_reg,
5802
				      offsetof(struct sk_buff, dev));
5803 5804
		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
5805 5806
				      bpf_target_off(struct net_device, ifindex, 4,
						     target_size));
5807 5808
		break;

5809
	case offsetof(struct __sk_buff, hash):
5810
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5811 5812
				      bpf_target_off(struct sk_buff, hash, 4,
						     target_size));
5813 5814
		break;

5815
	case offsetof(struct __sk_buff, mark):
5816
		if (type == BPF_WRITE)
5817
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
5818 5819
					      bpf_target_off(struct sk_buff, mark, 4,
							     target_size));
5820
		else
5821
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5822 5823
					      bpf_target_off(struct sk_buff, mark, 4,
							     target_size));
5824
		break;
5825 5826

	case offsetof(struct __sk_buff, pkt_type):
5827 5828 5829 5830 5831 5832 5833 5834
		*target_size = 1;
		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
				      PKT_TYPE_OFFSET());
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
#ifdef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
#endif
		break;
5835 5836

	case offsetof(struct __sk_buff, queue_mapping):
5837 5838 5839 5840
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
				      bpf_target_off(struct sk_buff, queue_mapping, 2,
						     target_size));
		break;
5841 5842 5843

	case offsetof(struct __sk_buff, vlan_present):
	case offsetof(struct __sk_buff, vlan_tci):
5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
		BUILD_BUG_ON(VLAN_TAG_PRESENT != 0x1000);

		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
				      bpf_target_off(struct sk_buff, vlan_tci, 2,
						     target_size));
		if (si->off == offsetof(struct __sk_buff, vlan_tci)) {
			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg,
						~VLAN_TAG_PRESENT);
		} else {
			*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 12);
			*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
		}
		break;
5857 5858

	case offsetof(struct __sk_buff, cb[0]) ...
5859
	     offsetofend(struct __sk_buff, cb[4]) - 1:
5860
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, data) < 20);
5861 5862 5863
		BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
			      offsetof(struct qdisc_skb_cb, data)) %
			     sizeof(__u64));
5864

5865
		prog->cb_access = 1;
5866 5867 5868 5869
		off  = si->off;
		off -= offsetof(struct __sk_buff, cb[0]);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct qdisc_skb_cb, data);
5870
		if (type == BPF_WRITE)
5871
			*insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
5872
					      si->src_reg, off);
5873
		else
5874
			*insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
5875
					      si->src_reg, off);
5876 5877
		break;

5878
	case offsetof(struct __sk_buff, tc_classid):
5879 5880 5881 5882 5883 5884
		BUILD_BUG_ON(FIELD_SIZEOF(struct qdisc_skb_cb, tc_classid) != 2);

		off  = si->off;
		off -= offsetof(struct __sk_buff, tc_classid);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct qdisc_skb_cb, tc_classid);
5885
		*target_size = 2;
5886
		if (type == BPF_WRITE)
5887 5888
			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
					      si->src_reg, off);
5889
		else
5890 5891
			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
					      si->src_reg, off);
5892 5893
		break;

5894
	case offsetof(struct __sk_buff, data):
5895
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
5896
				      si->dst_reg, si->src_reg,
5897 5898 5899
				      offsetof(struct sk_buff, data));
		break;

5900 5901 5902 5903 5904 5905 5906 5907 5908
	case offsetof(struct __sk_buff, data_meta):
		off  = si->off;
		off -= offsetof(struct __sk_buff, data_meta);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct bpf_skb_data_end, data_meta);
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
				      si->src_reg, off);
		break;

5909
	case offsetof(struct __sk_buff, data_end):
5910 5911 5912 5913 5914 5915
		off  = si->off;
		off -= offsetof(struct __sk_buff, data_end);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct bpf_skb_data_end, data_end);
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
				      si->src_reg, off);
5916 5917
		break;

5918 5919 5920
	case offsetof(struct __sk_buff, tc_index):
#ifdef CONFIG_NET_SCHED
		if (type == BPF_WRITE)
5921
			*insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
5922 5923
					      bpf_target_off(struct sk_buff, tc_index, 2,
							     target_size));
5924
		else
5925
			*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
5926 5927
					      bpf_target_off(struct sk_buff, tc_index, 2,
							     target_size));
5928
#else
5929
		*target_size = 2;
5930
		if (type == BPF_WRITE)
5931
			*insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
5932
		else
5933
			*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
5934 5935 5936 5937 5938 5939
#endif
		break;

	case offsetof(struct __sk_buff, napi_id):
#if defined(CONFIG_NET_RX_BUSY_POLL)
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
5940 5941
				      bpf_target_off(struct sk_buff, napi_id, 4,
						     target_size));
5942 5943 5944
		*insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
#else
5945
		*target_size = 4;
5946
		*insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
5947
#endif
5948
		break;
5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048
	case offsetof(struct __sk_buff, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_family,
						     2, target_size));
		break;
	case offsetof(struct __sk_buff, remote_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_daddr,
						     4, target_size));
		break;
	case offsetof(struct __sk_buff, local_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_rcv_saddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_rcv_saddr,
						     4, target_size));
		break;
	case offsetof(struct __sk_buff, remote_ip6[0]) ...
	     offsetof(struct __sk_buff, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_daddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct __sk_buff, remote_ip6[0]);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_daddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;
	case offsetof(struct __sk_buff, local_ip6[0]) ...
	     offsetof(struct __sk_buff, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct __sk_buff, local_ip6[0]);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_rcv_saddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct __sk_buff, remote_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_dport,
						     2, target_size));
#ifndef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
		break;

	case offsetof(struct __sk_buff, local_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      bpf_target_off(struct sock_common,
						     skc_num, 2, target_size));
		break;
6049 6050 6051
	}

	return insn - insn_buf;
6052 6053
}

6054
static u32 sock_filter_convert_ctx_access(enum bpf_access_type type,
6055
					  const struct bpf_insn *si,
6056
					  struct bpf_insn *insn_buf,
6057
					  struct bpf_prog *prog, u32 *target_size)
6058 6059
{
	struct bpf_insn *insn = insn_buf;
A
Andrey Ignatov 已提交
6060
	int off;
6061

6062
	switch (si->off) {
6063 6064 6065 6066
	case offsetof(struct bpf_sock, bound_dev_if):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_bound_dev_if) != 4);

		if (type == BPF_WRITE)
6067
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
6068 6069
					offsetof(struct sock, sk_bound_dev_if));
		else
6070
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6071 6072
				      offsetof(struct sock, sk_bound_dev_if));
		break;
6073

6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095
	case offsetof(struct bpf_sock, mark):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_mark) != 4);

		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
					offsetof(struct sock, sk_mark));
		else
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
				      offsetof(struct sock, sk_mark));
		break;

	case offsetof(struct bpf_sock, priority):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_priority) != 4);

		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
					offsetof(struct sock, sk_priority));
		else
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
				      offsetof(struct sock, sk_priority));
		break;

6096 6097 6098
	case offsetof(struct bpf_sock, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock, sk_family) != 2);

6099
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
6100 6101 6102 6103
				      offsetof(struct sock, sk_family));
		break;

	case offsetof(struct bpf_sock, type):
6104
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6105
				      offsetof(struct sock, __sk_flags_offset));
6106 6107
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
6108 6109 6110
		break;

	case offsetof(struct bpf_sock, protocol):
6111
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
6112
				      offsetof(struct sock, __sk_flags_offset));
6113 6114
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_PROTO_SHIFT);
6115
		break;
A
Andrey Ignatov 已提交
6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152

	case offsetof(struct bpf_sock, src_ip4):
		*insn++ = BPF_LDX_MEM(
			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
			bpf_target_off(struct sock_common, skc_rcv_saddr,
				       FIELD_SIZEOF(struct sock_common,
						    skc_rcv_saddr),
				       target_size));
		break;

	case bpf_ctx_range_till(struct bpf_sock, src_ip6[0], src_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		off = si->off;
		off -= offsetof(struct bpf_sock, src_ip6[0]);
		*insn++ = BPF_LDX_MEM(
			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
			bpf_target_off(
				struct sock_common,
				skc_v6_rcv_saddr.s6_addr32[0],
				FIELD_SIZEOF(struct sock_common,
					     skc_v6_rcv_saddr.s6_addr32[0]),
				target_size) + off);
#else
		(void)off;
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct bpf_sock, src_port):
		*insn++ = BPF_LDX_MEM(
			BPF_FIELD_SIZEOF(struct sock_common, skc_num),
			si->dst_reg, si->src_reg,
			bpf_target_off(struct sock_common, skc_num,
				       FIELD_SIZEOF(struct sock_common,
						    skc_num),
				       target_size));
		break;
6153 6154 6155 6156 6157
	}

	return insn - insn_buf;
}

6158 6159
static u32 tc_cls_act_convert_ctx_access(enum bpf_access_type type,
					 const struct bpf_insn *si,
6160
					 struct bpf_insn *insn_buf,
6161
					 struct bpf_prog *prog, u32 *target_size)
6162 6163 6164
{
	struct bpf_insn *insn = insn_buf;

6165
	switch (si->off) {
6166 6167
	case offsetof(struct __sk_buff, ifindex):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
6168
				      si->dst_reg, si->src_reg,
6169
				      offsetof(struct sk_buff, dev));
6170
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6171 6172
				      bpf_target_off(struct net_device, ifindex, 4,
						     target_size));
6173 6174
		break;
	default:
6175 6176
		return bpf_convert_ctx_access(type, si, insn_buf, prog,
					      target_size);
6177 6178 6179 6180 6181
	}

	return insn - insn_buf;
}

6182 6183
static u32 xdp_convert_ctx_access(enum bpf_access_type type,
				  const struct bpf_insn *si,
6184
				  struct bpf_insn *insn_buf,
6185
				  struct bpf_prog *prog, u32 *target_size)
6186 6187 6188
{
	struct bpf_insn *insn = insn_buf;

6189
	switch (si->off) {
6190
	case offsetof(struct xdp_md, data):
6191
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data),
6192
				      si->dst_reg, si->src_reg,
6193 6194
				      offsetof(struct xdp_buff, data));
		break;
6195 6196 6197 6198 6199
	case offsetof(struct xdp_md, data_meta):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_meta),
				      si->dst_reg, si->src_reg,
				      offsetof(struct xdp_buff, data_meta));
		break;
6200
	case offsetof(struct xdp_md, data_end):
6201
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, data_end),
6202
				      si->dst_reg, si->src_reg,
6203 6204
				      offsetof(struct xdp_buff, data_end));
		break;
6205 6206 6207 6208 6209 6210 6211 6212
	case offsetof(struct xdp_md, ingress_ifindex):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
				      si->dst_reg, si->src_reg,
				      offsetof(struct xdp_buff, rxq));
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_rxq_info, dev),
				      si->dst_reg, si->dst_reg,
				      offsetof(struct xdp_rxq_info, dev));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6213
				      offsetof(struct net_device, ifindex));
6214 6215 6216 6217 6218 6219
		break;
	case offsetof(struct xdp_md, rx_queue_index):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct xdp_buff, rxq),
				      si->dst_reg, si->src_reg,
				      offsetof(struct xdp_buff, rxq));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
6220 6221
				      offsetof(struct xdp_rxq_info,
					       queue_index));
6222
		break;
6223 6224 6225 6226 6227
	}

	return insn - insn_buf;
}

A
Andrey Ignatov 已提交
6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368
/* SOCK_ADDR_LOAD_NESTED_FIELD() loads Nested Field S.F.NF where S is type of
 * context Structure, F is Field in context structure that contains a pointer
 * to Nested Structure of type NS that has the field NF.
 *
 * SIZE encodes the load size (BPF_B, BPF_H, etc). It's up to caller to make
 * sure that SIZE is not greater than actual size of S.F.NF.
 *
 * If offset OFF is provided, the load happens from that offset relative to
 * offset of NF.
 */
#define SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF)	       \
	do {								       \
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), si->dst_reg,     \
				      si->src_reg, offsetof(S, F));	       \
		*insn++ = BPF_LDX_MEM(					       \
			SIZE, si->dst_reg, si->dst_reg,			       \
			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
				       target_size)			       \
				+ OFF);					       \
	} while (0)

#define SOCK_ADDR_LOAD_NESTED_FIELD(S, NS, F, NF)			       \
	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(S, NS, F, NF,		       \
					     BPF_FIELD_SIZEOF(NS, NF), 0)

/* SOCK_ADDR_STORE_NESTED_FIELD_OFF() has semantic similar to
 * SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF() but for store operation.
 *
 * It doesn't support SIZE argument though since narrow stores are not
 * supported for now.
 *
 * In addition it uses Temporary Field TF (member of struct S) as the 3rd
 * "register" since two registers available in convert_ctx_access are not
 * enough: we can't override neither SRC, since it contains value to store, nor
 * DST since it contains pointer to context that may be used by later
 * instructions. But we need a temporary place to save pointer to nested
 * structure whose field we want to store to.
 */
#define SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF, TF)		       \
	do {								       \
		int tmp_reg = BPF_REG_9;				       \
		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
			--tmp_reg;					       \
		if (si->src_reg == tmp_reg || si->dst_reg == tmp_reg)	       \
			--tmp_reg;					       \
		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, tmp_reg,	       \
				      offsetof(S, TF));			       \
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(S, F), tmp_reg,	       \
				      si->dst_reg, offsetof(S, F));	       \
		*insn++ = BPF_STX_MEM(					       \
			BPF_FIELD_SIZEOF(NS, NF), tmp_reg, si->src_reg,	       \
			bpf_target_off(NS, NF, FIELD_SIZEOF(NS, NF),	       \
				       target_size)			       \
				+ OFF);					       \
		*insn++ = BPF_LDX_MEM(BPF_DW, tmp_reg, si->dst_reg,	       \
				      offsetof(S, TF));			       \
	} while (0)

#define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(S, NS, F, NF, SIZE, OFF, \
						      TF)		       \
	do {								       \
		if (type == BPF_WRITE) {				       \
			SOCK_ADDR_STORE_NESTED_FIELD_OFF(S, NS, F, NF, OFF,    \
							 TF);		       \
		} else {						       \
			SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(		       \
				S, NS, F, NF, SIZE, OFF);  \
		}							       \
	} while (0)

#define SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(S, NS, F, NF, TF)		       \
	SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(			       \
		S, NS, F, NF, BPF_FIELD_SIZEOF(NS, NF), 0, TF)

static u32 sock_addr_convert_ctx_access(enum bpf_access_type type,
					const struct bpf_insn *si,
					struct bpf_insn *insn_buf,
					struct bpf_prog *prog, u32 *target_size)
{
	struct bpf_insn *insn = insn_buf;
	int off;

	switch (si->off) {
	case offsetof(struct bpf_sock_addr, user_family):
		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
					    struct sockaddr, uaddr, sa_family);
		break;

	case offsetof(struct bpf_sock_addr, user_ip4):
		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct sockaddr_in, uaddr,
			sin_addr, BPF_SIZE(si->code), 0, tmp_reg);
		break;

	case bpf_ctx_range_till(struct bpf_sock_addr, user_ip6[0], user_ip6[3]):
		off = si->off;
		off -= offsetof(struct bpf_sock_addr, user_ip6[0]);
		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct sockaddr_in6, uaddr,
			sin6_addr.s6_addr32[0], BPF_SIZE(si->code), off,
			tmp_reg);
		break;

	case offsetof(struct bpf_sock_addr, user_port):
		/* To get port we need to know sa_family first and then treat
		 * sockaddr as either sockaddr_in or sockaddr_in6.
		 * Though we can simplify since port field has same offset and
		 * size in both structures.
		 * Here we check this invariant and use just one of the
		 * structures if it's true.
		 */
		BUILD_BUG_ON(offsetof(struct sockaddr_in, sin_port) !=
			     offsetof(struct sockaddr_in6, sin6_port));
		BUILD_BUG_ON(FIELD_SIZEOF(struct sockaddr_in, sin_port) !=
			     FIELD_SIZEOF(struct sockaddr_in6, sin6_port));
		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD(struct bpf_sock_addr_kern,
						     struct sockaddr_in6, uaddr,
						     sin6_port, tmp_reg);
		break;

	case offsetof(struct bpf_sock_addr, family):
		SOCK_ADDR_LOAD_NESTED_FIELD(struct bpf_sock_addr_kern,
					    struct sock, sk, sk_family);
		break;

	case offsetof(struct bpf_sock_addr, type):
		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct sock, sk,
			__sk_flags_offset, BPF_W, 0);
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_TYPE_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, SK_FL_TYPE_SHIFT);
		break;

	case offsetof(struct bpf_sock_addr, protocol):
		SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct sock, sk,
			__sk_flags_offset, BPF_W, 0);
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
					SK_FL_PROTO_SHIFT);
		break;
A
Andrey Ignatov 已提交
6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385

	case offsetof(struct bpf_sock_addr, msg_src_ip4):
		/* Treat t_ctx as struct in_addr for msg_src_ip4. */
		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct in_addr, t_ctx,
			s_addr, BPF_SIZE(si->code), 0, tmp_reg);
		break;

	case bpf_ctx_range_till(struct bpf_sock_addr, msg_src_ip6[0],
				msg_src_ip6[3]):
		off = si->off;
		off -= offsetof(struct bpf_sock_addr, msg_src_ip6[0]);
		/* Treat t_ctx as struct in6_addr for msg_src_ip6. */
		SOCK_ADDR_LOAD_OR_STORE_NESTED_FIELD_SIZE_OFF(
			struct bpf_sock_addr_kern, struct in6_addr, t_ctx,
			s6_addr32[0], BPF_SIZE(si->code), off, tmp_reg);
		break;
A
Andrey Ignatov 已提交
6386 6387 6388 6389 6390
	}

	return insn - insn_buf;
}

L
Lawrence Brakmo 已提交
6391 6392 6393
static u32 sock_ops_convert_ctx_access(enum bpf_access_type type,
				       const struct bpf_insn *si,
				       struct bpf_insn *insn_buf,
6394 6395
				       struct bpf_prog *prog,
				       u32 *target_size)
L
Lawrence Brakmo 已提交
6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442
{
	struct bpf_insn *insn = insn_buf;
	int off;

	switch (si->off) {
	case offsetof(struct bpf_sock_ops, op) ...
	     offsetof(struct bpf_sock_ops, replylong[3]):
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, op) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, op));
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, reply) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, reply));
		BUILD_BUG_ON(FIELD_SIZEOF(struct bpf_sock_ops, replylong) !=
			     FIELD_SIZEOF(struct bpf_sock_ops_kern, replylong));
		off = si->off;
		off -= offsetof(struct bpf_sock_ops, op);
		off += offsetof(struct bpf_sock_ops_kern, op);
		if (type == BPF_WRITE)
			*insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
					      off);
		else
			*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
					      off);
		break;

	case offsetof(struct bpf_sock_ops, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_family));
		break;

	case offsetof(struct bpf_sock_ops, remote_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_daddr));
		break;

	case offsetof(struct bpf_sock_ops, local_ip4):
6443 6444
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_rcv_saddr) != 4);
L
Lawrence Brakmo 已提交
6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_rcv_saddr));
		break;

	case offsetof(struct bpf_sock_ops, remote_ip6[0]) ...
	     offsetof(struct bpf_sock_ops, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_daddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct bpf_sock_ops, remote_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_daddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct bpf_sock_ops, local_ip6[0]) ...
	     offsetof(struct bpf_sock_ops, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct bpf_sock_ops, local_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_rcv_saddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct bpf_sock_ops, remote_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_dport));
#ifndef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
		break;

	case offsetof(struct bpf_sock_ops, local_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_num));
		break;
6521 6522 6523 6524 6525 6526 6527 6528 6529 6530

	case offsetof(struct bpf_sock_ops, is_fullsock):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern,
						is_fullsock),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern,
					       is_fullsock));
		break;

6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556
	case offsetof(struct bpf_sock_ops, state):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_state) != 1);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_state));
		break;

	case offsetof(struct bpf_sock_ops, rtt_min):
		BUILD_BUG_ON(FIELD_SIZEOF(struct tcp_sock, rtt_min) !=
			     sizeof(struct minmax));
		BUILD_BUG_ON(sizeof(struct minmax) <
			     sizeof(struct minmax_sample));

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct bpf_sock_ops_kern, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct bpf_sock_ops_kern, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct tcp_sock, rtt_min) +
				      FIELD_SIZEOF(struct minmax_sample, t));
		break;

6557 6558
/* Helper macro for adding read access to tcp_sock or sock fields. */
#define SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
6559
	do {								      \
6560 6561
		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
						struct bpf_sock_ops_kern,     \
						is_fullsock),		      \
				      si->dst_reg, si->src_reg,		      \
				      offsetof(struct bpf_sock_ops_kern,      \
					       is_fullsock));		      \
		*insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 2);	      \
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
						struct bpf_sock_ops_kern, sk),\
				      si->dst_reg, si->src_reg,		      \
				      offsetof(struct bpf_sock_ops_kern, sk));\
6573 6574 6575 6576
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(OBJ,		      \
						       OBJ_FIELD),	      \
				      si->dst_reg, si->dst_reg,		      \
				      offsetof(OBJ, OBJ_FIELD));	      \
6577 6578
	} while (0)

6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626
/* Helper macro for adding write access to tcp_sock or sock fields.
 * The macro is called with two registers, dst_reg which contains a pointer
 * to ctx (context) and src_reg which contains the value that should be
 * stored. However, we need an additional register since we cannot overwrite
 * dst_reg because it may be used later in the program.
 * Instead we "borrow" one of the other register. We first save its value
 * into a new (temp) field in bpf_sock_ops_kern, use it, and then restore
 * it at the end of the macro.
 */
#define SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ)			      \
	do {								      \
		int reg = BPF_REG_9;					      \
		BUILD_BUG_ON(FIELD_SIZEOF(OBJ, OBJ_FIELD) >		      \
			     FIELD_SIZEOF(struct bpf_sock_ops, BPF_FIELD));   \
		if (si->dst_reg == reg || si->src_reg == reg)		      \
			reg--;						      \
		if (si->dst_reg == reg || si->src_reg == reg)		      \
			reg--;						      \
		*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, reg,		      \
				      offsetof(struct bpf_sock_ops_kern,      \
					       temp));			      \
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
						struct bpf_sock_ops_kern,     \
						is_fullsock),		      \
				      reg, si->dst_reg,			      \
				      offsetof(struct bpf_sock_ops_kern,      \
					       is_fullsock));		      \
		*insn++ = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);		      \
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(			      \
						struct bpf_sock_ops_kern, sk),\
				      reg, si->dst_reg,			      \
				      offsetof(struct bpf_sock_ops_kern, sk));\
		*insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(OBJ, OBJ_FIELD),	      \
				      reg, si->src_reg,			      \
				      offsetof(OBJ, OBJ_FIELD));	      \
		*insn++ = BPF_LDX_MEM(BPF_DW, reg, si->dst_reg,		      \
				      offsetof(struct bpf_sock_ops_kern,      \
					       temp));			      \
	} while (0)

#define SOCK_OPS_GET_OR_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ, TYPE)	      \
	do {								      \
		if (TYPE == BPF_WRITE)					      \
			SOCK_OPS_SET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
		else							      \
			SOCK_OPS_GET_FIELD(BPF_FIELD, OBJ_FIELD, OBJ);	      \
	} while (0)

6627
	case offsetof(struct bpf_sock_ops, snd_cwnd):
6628
		SOCK_OPS_GET_FIELD(snd_cwnd, snd_cwnd, struct tcp_sock);
6629 6630 6631
		break;

	case offsetof(struct bpf_sock_ops, srtt_us):
6632
		SOCK_OPS_GET_FIELD(srtt_us, srtt_us, struct tcp_sock);
6633
		break;
6634 6635 6636 6637 6638

	case offsetof(struct bpf_sock_ops, bpf_sock_ops_cb_flags):
		SOCK_OPS_GET_FIELD(bpf_sock_ops_cb_flags, bpf_sock_ops_cb_flags,
				   struct tcp_sock);
		break;
6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712

	case offsetof(struct bpf_sock_ops, snd_ssthresh):
		SOCK_OPS_GET_FIELD(snd_ssthresh, snd_ssthresh, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, rcv_nxt):
		SOCK_OPS_GET_FIELD(rcv_nxt, rcv_nxt, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, snd_nxt):
		SOCK_OPS_GET_FIELD(snd_nxt, snd_nxt, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, snd_una):
		SOCK_OPS_GET_FIELD(snd_una, snd_una, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, mss_cache):
		SOCK_OPS_GET_FIELD(mss_cache, mss_cache, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, ecn_flags):
		SOCK_OPS_GET_FIELD(ecn_flags, ecn_flags, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, rate_delivered):
		SOCK_OPS_GET_FIELD(rate_delivered, rate_delivered,
				   struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, rate_interval_us):
		SOCK_OPS_GET_FIELD(rate_interval_us, rate_interval_us,
				   struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, packets_out):
		SOCK_OPS_GET_FIELD(packets_out, packets_out, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, retrans_out):
		SOCK_OPS_GET_FIELD(retrans_out, retrans_out, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, total_retrans):
		SOCK_OPS_GET_FIELD(total_retrans, total_retrans,
				   struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, segs_in):
		SOCK_OPS_GET_FIELD(segs_in, segs_in, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, data_segs_in):
		SOCK_OPS_GET_FIELD(data_segs_in, data_segs_in, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, segs_out):
		SOCK_OPS_GET_FIELD(segs_out, segs_out, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, data_segs_out):
		SOCK_OPS_GET_FIELD(data_segs_out, data_segs_out,
				   struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, lost_out):
		SOCK_OPS_GET_FIELD(lost_out, lost_out, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, sacked_out):
		SOCK_OPS_GET_FIELD(sacked_out, sacked_out, struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, sk_txhash):
6713 6714
		SOCK_OPS_GET_OR_SET_FIELD(sk_txhash, sk_txhash,
					  struct sock, type);
6715 6716 6717 6718 6719 6720 6721 6722 6723 6724
		break;

	case offsetof(struct bpf_sock_ops, bytes_received):
		SOCK_OPS_GET_FIELD(bytes_received, bytes_received,
				   struct tcp_sock);
		break;

	case offsetof(struct bpf_sock_ops, bytes_acked):
		SOCK_OPS_GET_FIELD(bytes_acked, bytes_acked, struct tcp_sock);
		break;
6725

L
Lawrence Brakmo 已提交
6726 6727 6728 6729
	}
	return insn - insn_buf;
}

6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754
static u32 sk_skb_convert_ctx_access(enum bpf_access_type type,
				     const struct bpf_insn *si,
				     struct bpf_insn *insn_buf,
				     struct bpf_prog *prog, u32 *target_size)
{
	struct bpf_insn *insn = insn_buf;
	int off;

	switch (si->off) {
	case offsetof(struct __sk_buff, data_end):
		off  = si->off;
		off -= offsetof(struct __sk_buff, data_end);
		off += offsetof(struct sk_buff, cb);
		off += offsetof(struct tcp_skb_cb, bpf.data_end);
		*insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
				      si->src_reg, off);
		break;
	default:
		return bpf_convert_ctx_access(type, si, insn_buf, prog,
					      target_size);
	}

	return insn - insn_buf;
}

6755 6756 6757 6758 6759 6760
static u32 sk_msg_convert_ctx_access(enum bpf_access_type type,
				     const struct bpf_insn *si,
				     struct bpf_insn *insn_buf,
				     struct bpf_prog *prog, u32 *target_size)
{
	struct bpf_insn *insn = insn_buf;
Y
YueHaibing 已提交
6761
#if IS_ENABLED(CONFIG_IPV6)
6762
	int off;
Y
YueHaibing 已提交
6763
#endif
6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775

	switch (si->off) {
	case offsetof(struct sk_msg_md, data):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_buff, data),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, data));
		break;
	case offsetof(struct sk_msg_md, data_end):
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_msg_buff, data_end),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, data_end));
		break;
6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876
	case offsetof(struct sk_msg_md, family):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_family) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_family));
		break;

	case offsetof(struct sk_msg_md, remote_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_daddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_daddr));
		break;

	case offsetof(struct sk_msg_md, local_ip4):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_rcv_saddr) != 4);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
					      struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_rcv_saddr));
		break;

	case offsetof(struct sk_msg_md, remote_ip6[0]) ...
	     offsetof(struct sk_msg_md, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_daddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct sk_msg_md, remote_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_daddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct sk_msg_md, local_ip6[0]) ...
	     offsetof(struct sk_msg_md, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common,
					  skc_v6_rcv_saddr.s6_addr32[0]) != 4);

		off = si->off;
		off -= offsetof(struct sk_msg_md, local_ip6[0]);
		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common,
					       skc_v6_rcv_saddr.s6_addr32[0]) +
				      off);
#else
		*insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
		break;

	case offsetof(struct sk_msg_md, remote_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_dport) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_dport));
#ifndef __BIG_ENDIAN_BITFIELD
		*insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
		break;

	case offsetof(struct sk_msg_md, local_port):
		BUILD_BUG_ON(FIELD_SIZEOF(struct sock_common, skc_num) != 2);

		*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(
						struct sk_msg_buff, sk),
				      si->dst_reg, si->src_reg,
				      offsetof(struct sk_msg_buff, sk));
		*insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
				      offsetof(struct sock_common, skc_num));
		break;
6877 6878 6879 6880 6881
	}

	return insn - insn_buf;
}

6882
const struct bpf_verifier_ops sk_filter_verifier_ops = {
6883 6884
	.get_func_proto		= sk_filter_func_proto,
	.is_valid_access	= sk_filter_is_valid_access,
6885
	.convert_ctx_access	= bpf_convert_ctx_access,
6886
	.gen_ld_abs		= bpf_gen_ld_abs,
6887 6888
};

6889
const struct bpf_prog_ops sk_filter_prog_ops = {
6890
	.test_run		= bpf_prog_test_run_skb,
6891 6892 6893
};

const struct bpf_verifier_ops tc_cls_act_verifier_ops = {
6894 6895
	.get_func_proto		= tc_cls_act_func_proto,
	.is_valid_access	= tc_cls_act_is_valid_access,
6896
	.convert_ctx_access	= tc_cls_act_convert_ctx_access,
6897
	.gen_prologue		= tc_cls_act_prologue,
6898
	.gen_ld_abs		= bpf_gen_ld_abs,
6899 6900 6901
};

const struct bpf_prog_ops tc_cls_act_prog_ops = {
6902
	.test_run		= bpf_prog_test_run_skb,
6903 6904
};

6905
const struct bpf_verifier_ops xdp_verifier_ops = {
6906 6907 6908
	.get_func_proto		= xdp_func_proto,
	.is_valid_access	= xdp_is_valid_access,
	.convert_ctx_access	= xdp_convert_ctx_access,
6909 6910 6911
};

const struct bpf_prog_ops xdp_prog_ops = {
6912
	.test_run		= bpf_prog_test_run_xdp,
6913 6914
};

6915
const struct bpf_verifier_ops cg_skb_verifier_ops = {
6916
	.get_func_proto		= cg_skb_func_proto,
6917
	.is_valid_access	= sk_filter_is_valid_access,
6918
	.convert_ctx_access	= bpf_convert_ctx_access,
6919 6920 6921
};

const struct bpf_prog_ops cg_skb_prog_ops = {
6922
	.test_run		= bpf_prog_test_run_skb,
6923 6924
};

6925 6926
const struct bpf_verifier_ops lwt_in_verifier_ops = {
	.get_func_proto		= lwt_in_func_proto,
6927
	.is_valid_access	= lwt_is_valid_access,
6928
	.convert_ctx_access	= bpf_convert_ctx_access,
6929 6930
};

6931 6932 6933 6934 6935 6936
const struct bpf_prog_ops lwt_in_prog_ops = {
	.test_run		= bpf_prog_test_run_skb,
};

const struct bpf_verifier_ops lwt_out_verifier_ops = {
	.get_func_proto		= lwt_out_func_proto,
6937
	.is_valid_access	= lwt_is_valid_access,
6938
	.convert_ctx_access	= bpf_convert_ctx_access,
6939 6940
};

6941
const struct bpf_prog_ops lwt_out_prog_ops = {
6942
	.test_run		= bpf_prog_test_run_skb,
6943 6944
};

6945
const struct bpf_verifier_ops lwt_xmit_verifier_ops = {
6946 6947
	.get_func_proto		= lwt_xmit_func_proto,
	.is_valid_access	= lwt_is_valid_access,
6948
	.convert_ctx_access	= bpf_convert_ctx_access,
6949
	.gen_prologue		= tc_cls_act_prologue,
6950 6951 6952
};

const struct bpf_prog_ops lwt_xmit_prog_ops = {
6953
	.test_run		= bpf_prog_test_run_skb,
6954 6955
};

6956 6957 6958 6959 6960 6961 6962 6963 6964 6965
const struct bpf_verifier_ops lwt_seg6local_verifier_ops = {
	.get_func_proto		= lwt_seg6local_func_proto,
	.is_valid_access	= lwt_is_valid_access,
	.convert_ctx_access	= bpf_convert_ctx_access,
};

const struct bpf_prog_ops lwt_seg6local_prog_ops = {
	.test_run		= bpf_prog_test_run_skb,
};

6966
const struct bpf_verifier_ops cg_sock_verifier_ops = {
6967
	.get_func_proto		= sock_filter_func_proto,
6968 6969 6970 6971
	.is_valid_access	= sock_filter_is_valid_access,
	.convert_ctx_access	= sock_filter_convert_ctx_access,
};

6972 6973 6974
const struct bpf_prog_ops cg_sock_prog_ops = {
};

A
Andrey Ignatov 已提交
6975 6976 6977 6978 6979 6980 6981 6982 6983
const struct bpf_verifier_ops cg_sock_addr_verifier_ops = {
	.get_func_proto		= sock_addr_func_proto,
	.is_valid_access	= sock_addr_is_valid_access,
	.convert_ctx_access	= sock_addr_convert_ctx_access,
};

const struct bpf_prog_ops cg_sock_addr_prog_ops = {
};

6984
const struct bpf_verifier_ops sock_ops_verifier_ops = {
6985
	.get_func_proto		= sock_ops_func_proto,
L
Lawrence Brakmo 已提交
6986 6987 6988 6989
	.is_valid_access	= sock_ops_is_valid_access,
	.convert_ctx_access	= sock_ops_convert_ctx_access,
};

6990 6991 6992 6993
const struct bpf_prog_ops sock_ops_prog_ops = {
};

const struct bpf_verifier_ops sk_skb_verifier_ops = {
6994 6995
	.get_func_proto		= sk_skb_func_proto,
	.is_valid_access	= sk_skb_is_valid_access,
6996
	.convert_ctx_access	= sk_skb_convert_ctx_access,
6997
	.gen_prologue		= sk_skb_prologue,
6998 6999
};

7000 7001 7002
const struct bpf_prog_ops sk_skb_prog_ops = {
};

7003 7004 7005 7006 7007 7008 7009 7010 7011
const struct bpf_verifier_ops sk_msg_verifier_ops = {
	.get_func_proto		= sk_msg_func_proto,
	.is_valid_access	= sk_msg_is_valid_access,
	.convert_ctx_access	= sk_msg_convert_ctx_access,
};

const struct bpf_prog_ops sk_msg_prog_ops = {
};

7012
int sk_detach_filter(struct sock *sk)
7013 7014 7015 7016
{
	int ret = -ENOENT;
	struct sk_filter *filter;

7017 7018 7019
	if (sock_flag(sk, SOCK_FILTER_LOCKED))
		return -EPERM;

7020 7021
	filter = rcu_dereference_protected(sk->sk_filter,
					   lockdep_sock_is_held(sk));
7022
	if (filter) {
7023
		RCU_INIT_POINTER(sk->sk_filter, NULL);
E
Eric Dumazet 已提交
7024
		sk_filter_uncharge(sk, filter);
7025 7026
		ret = 0;
	}
7027

7028 7029
	return ret;
}
7030
EXPORT_SYMBOL_GPL(sk_detach_filter);
7031

7032 7033
int sk_get_filter(struct sock *sk, struct sock_filter __user *ubuf,
		  unsigned int len)
7034
{
7035
	struct sock_fprog_kern *fprog;
7036
	struct sk_filter *filter;
7037
	int ret = 0;
7038 7039 7040

	lock_sock(sk);
	filter = rcu_dereference_protected(sk->sk_filter,
7041
					   lockdep_sock_is_held(sk));
7042 7043
	if (!filter)
		goto out;
7044 7045

	/* We're copying the filter that has been originally attached,
7046 7047
	 * so no conversion/decode needed anymore. eBPF programs that
	 * have no original program cannot be dumped through this.
7048
	 */
7049
	ret = -EACCES;
7050
	fprog = filter->prog->orig_prog;
7051 7052
	if (!fprog)
		goto out;
7053 7054

	ret = fprog->len;
7055
	if (!len)
7056
		/* User space only enquires number of filter blocks. */
7057
		goto out;
7058

7059
	ret = -EINVAL;
7060
	if (len < fprog->len)
7061 7062 7063
		goto out;

	ret = -EFAULT;
7064
	if (copy_to_user(ubuf, fprog->filter, bpf_classic_proglen(fprog)))
7065
		goto out;
7066

7067 7068 7069 7070
	/* Instead of bytes, the API requests to return the number
	 * of filter blocks.
	 */
	ret = fprog->len;
7071 7072 7073 7074
out:
	release_sock(sk);
	return ret;
}
7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251

#ifdef CONFIG_INET
struct sk_reuseport_kern {
	struct sk_buff *skb;
	struct sock *sk;
	struct sock *selected_sk;
	void *data_end;
	u32 hash;
	u32 reuseport_id;
	bool bind_inany;
};

static void bpf_init_reuseport_kern(struct sk_reuseport_kern *reuse_kern,
				    struct sock_reuseport *reuse,
				    struct sock *sk, struct sk_buff *skb,
				    u32 hash)
{
	reuse_kern->skb = skb;
	reuse_kern->sk = sk;
	reuse_kern->selected_sk = NULL;
	reuse_kern->data_end = skb->data + skb_headlen(skb);
	reuse_kern->hash = hash;
	reuse_kern->reuseport_id = reuse->reuseport_id;
	reuse_kern->bind_inany = reuse->bind_inany;
}

struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,
				  struct bpf_prog *prog, struct sk_buff *skb,
				  u32 hash)
{
	struct sk_reuseport_kern reuse_kern;
	enum sk_action action;

	bpf_init_reuseport_kern(&reuse_kern, reuse, sk, skb, hash);
	action = BPF_PROG_RUN(prog, &reuse_kern);

	if (action == SK_PASS)
		return reuse_kern.selected_sk;
	else
		return ERR_PTR(-ECONNREFUSED);
}

BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern,
	   struct bpf_map *, map, void *, key, u32, flags)
{
	struct sock_reuseport *reuse;
	struct sock *selected_sk;

	selected_sk = map->ops->map_lookup_elem(map, key);
	if (!selected_sk)
		return -ENOENT;

	reuse = rcu_dereference(selected_sk->sk_reuseport_cb);
	if (!reuse)
		/* selected_sk is unhashed (e.g. by close()) after the
		 * above map_lookup_elem().  Treat selected_sk has already
		 * been removed from the map.
		 */
		return -ENOENT;

	if (unlikely(reuse->reuseport_id != reuse_kern->reuseport_id)) {
		struct sock *sk;

		if (unlikely(!reuse_kern->reuseport_id))
			/* There is a small race between adding the
			 * sk to the map and setting the
			 * reuse_kern->reuseport_id.
			 * Treat it as the sk has not been added to
			 * the bpf map yet.
			 */
			return -ENOENT;

		sk = reuse_kern->sk;
		if (sk->sk_protocol != selected_sk->sk_protocol)
			return -EPROTOTYPE;
		else if (sk->sk_family != selected_sk->sk_family)
			return -EAFNOSUPPORT;

		/* Catch all. Likely bound to a different sockaddr. */
		return -EBADFD;
	}

	reuse_kern->selected_sk = selected_sk;

	return 0;
}

static const struct bpf_func_proto sk_select_reuseport_proto = {
	.func           = sk_select_reuseport,
	.gpl_only       = false,
	.ret_type       = RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type      = ARG_CONST_MAP_PTR,
	.arg3_type      = ARG_PTR_TO_MAP_KEY,
	.arg4_type	= ARG_ANYTHING,
};

BPF_CALL_4(sk_reuseport_load_bytes,
	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
	   void *, to, u32, len)
{
	return ____bpf_skb_load_bytes(reuse_kern->skb, offset, to, len);
}

static const struct bpf_func_proto sk_reuseport_load_bytes_proto = {
	.func		= sk_reuseport_load_bytes,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
};

BPF_CALL_5(sk_reuseport_load_bytes_relative,
	   const struct sk_reuseport_kern *, reuse_kern, u32, offset,
	   void *, to, u32, len, u32, start_header)
{
	return ____bpf_skb_load_bytes_relative(reuse_kern->skb, offset, to,
					       len, start_header);
}

static const struct bpf_func_proto sk_reuseport_load_bytes_relative_proto = {
	.func		= sk_reuseport_load_bytes_relative,
	.gpl_only	= false,
	.ret_type	= RET_INTEGER,
	.arg1_type	= ARG_PTR_TO_CTX,
	.arg2_type	= ARG_ANYTHING,
	.arg3_type	= ARG_PTR_TO_UNINIT_MEM,
	.arg4_type	= ARG_CONST_SIZE,
	.arg5_type	= ARG_ANYTHING,
};

static const struct bpf_func_proto *
sk_reuseport_func_proto(enum bpf_func_id func_id,
			const struct bpf_prog *prog)
{
	switch (func_id) {
	case BPF_FUNC_sk_select_reuseport:
		return &sk_select_reuseport_proto;
	case BPF_FUNC_skb_load_bytes:
		return &sk_reuseport_load_bytes_proto;
	case BPF_FUNC_skb_load_bytes_relative:
		return &sk_reuseport_load_bytes_relative_proto;
	default:
		return bpf_base_func_proto(func_id);
	}
}

static bool
sk_reuseport_is_valid_access(int off, int size,
			     enum bpf_access_type type,
			     const struct bpf_prog *prog,
			     struct bpf_insn_access_aux *info)
{
	const u32 size_default = sizeof(__u32);

	if (off < 0 || off >= sizeof(struct sk_reuseport_md) ||
	    off % size || type != BPF_READ)
		return false;

	switch (off) {
	case offsetof(struct sk_reuseport_md, data):
		info->reg_type = PTR_TO_PACKET;
		return size == sizeof(__u64);

	case offsetof(struct sk_reuseport_md, data_end):
		info->reg_type = PTR_TO_PACKET_END;
		return size == sizeof(__u64);

	case offsetof(struct sk_reuseport_md, hash):
		return size == size_default;

	/* Fields that allow narrowing */
	case offsetof(struct sk_reuseport_md, eth_protocol):
		if (size < FIELD_SIZEOF(struct sk_buff, protocol))
			return false;
7252
		/* fall through */
7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305
	case offsetof(struct sk_reuseport_md, ip_protocol):
	case offsetof(struct sk_reuseport_md, bind_inany):
	case offsetof(struct sk_reuseport_md, len):
		bpf_ctx_record_field_size(info, size_default);
		return bpf_ctx_narrow_access_ok(off, size, size_default);

	default:
		return false;
	}
}

#define SK_REUSEPORT_LOAD_FIELD(F) ({					\
	*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_reuseport_kern, F), \
			      si->dst_reg, si->src_reg,			\
			      bpf_target_off(struct sk_reuseport_kern, F, \
					     FIELD_SIZEOF(struct sk_reuseport_kern, F), \
					     target_size));		\
	})

#define SK_REUSEPORT_LOAD_SKB_FIELD(SKB_FIELD)				\
	SOCK_ADDR_LOAD_NESTED_FIELD(struct sk_reuseport_kern,		\
				    struct sk_buff,			\
				    skb,				\
				    SKB_FIELD)

#define SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(SK_FIELD, BPF_SIZE, EXTRA_OFF) \
	SOCK_ADDR_LOAD_NESTED_FIELD_SIZE_OFF(struct sk_reuseport_kern,	\
					     struct sock,		\
					     sk,			\
					     SK_FIELD, BPF_SIZE, EXTRA_OFF)

static u32 sk_reuseport_convert_ctx_access(enum bpf_access_type type,
					   const struct bpf_insn *si,
					   struct bpf_insn *insn_buf,
					   struct bpf_prog *prog,
					   u32 *target_size)
{
	struct bpf_insn *insn = insn_buf;

	switch (si->off) {
	case offsetof(struct sk_reuseport_md, data):
		SK_REUSEPORT_LOAD_SKB_FIELD(data);
		break;

	case offsetof(struct sk_reuseport_md, len):
		SK_REUSEPORT_LOAD_SKB_FIELD(len);
		break;

	case offsetof(struct sk_reuseport_md, eth_protocol):
		SK_REUSEPORT_LOAD_SKB_FIELD(protocol);
		break;

	case offsetof(struct sk_reuseport_md, ip_protocol):
S
Stefan Agner 已提交
7306
		BUILD_BUG_ON(HWEIGHT32(SK_FL_PROTO_MASK) != BITS_PER_BYTE);
7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342
		SK_REUSEPORT_LOAD_SK_FIELD_SIZE_OFF(__sk_flags_offset,
						    BPF_W, 0);
		*insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, SK_FL_PROTO_MASK);
		*insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg,
					SK_FL_PROTO_SHIFT);
		/* SK_FL_PROTO_MASK and SK_FL_PROTO_SHIFT are endian
		 * aware.  No further narrowing or masking is needed.
		 */
		*target_size = 1;
		break;

	case offsetof(struct sk_reuseport_md, data_end):
		SK_REUSEPORT_LOAD_FIELD(data_end);
		break;

	case offsetof(struct sk_reuseport_md, hash):
		SK_REUSEPORT_LOAD_FIELD(hash);
		break;

	case offsetof(struct sk_reuseport_md, bind_inany):
		SK_REUSEPORT_LOAD_FIELD(bind_inany);
		break;
	}

	return insn - insn_buf;
}

const struct bpf_verifier_ops sk_reuseport_verifier_ops = {
	.get_func_proto		= sk_reuseport_func_proto,
	.is_valid_access	= sk_reuseport_is_valid_access,
	.convert_ctx_access	= sk_reuseport_convert_ctx_access,
};

const struct bpf_prog_ops sk_reuseport_prog_ops = {
};
#endif /* CONFIG_INET */