xref: /linux/net/mctp/route.c (revision 25489a4f556414445d342951615178368ee45cde)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Management Component Transport Protocol (MCTP) - routing
4  * implementation.
5  *
6  * This is currently based on a simple routing table, with no dst cache. The
7  * number of routes should stay fairly small, so the lookup cost is small.
8  *
9  * Copyright (c) 2021 Code Construct
10  * Copyright (c) 2021 Google
11  */
12 
13 #include <linux/idr.h>
14 #include <linux/kconfig.h>
15 #include <linux/mctp.h>
16 #include <linux/netdevice.h>
17 #include <linux/rtnetlink.h>
18 #include <linux/skbuff.h>
19 
20 #include <kunit/static_stub.h>
21 
22 #include <uapi/linux/if_arp.h>
23 
24 #include <net/mctp.h>
25 #include <net/mctpdevice.h>
26 #include <net/netlink.h>
27 #include <net/sock.h>
28 
29 #include <trace/events/mctp.h>
30 
31 static const unsigned int mctp_message_maxlen = 64 * 1024;
32 static const unsigned long mctp_key_lifetime = 6 * CONFIG_HZ;
33 
34 static void mctp_flow_prepare_output(struct sk_buff *skb, struct mctp_dev *dev);
35 
36 /* route output callbacks */
37 static int mctp_dst_discard(struct mctp_dst *dst, struct sk_buff *skb)
38 {
39 	kfree_skb(skb);
40 	return 0;
41 }
42 
43 static struct mctp_sock *mctp_lookup_bind(struct net *net, struct sk_buff *skb)
44 {
45 	struct mctp_skb_cb *cb = mctp_cb(skb);
46 	struct mctp_hdr *mh;
47 	struct sock *sk;
48 	u8 type;
49 
50 	WARN_ON(!rcu_read_lock_held());
51 
52 	/* TODO: look up in skb->cb? */
53 	mh = mctp_hdr(skb);
54 
55 	if (!skb_headlen(skb))
56 		return NULL;
57 
58 	type = (*(u8 *)skb->data) & 0x7f;
59 
60 	sk_for_each_rcu(sk, &net->mctp.binds) {
61 		struct mctp_sock *msk = container_of(sk, struct mctp_sock, sk);
62 
63 		if (msk->bind_net != MCTP_NET_ANY && msk->bind_net != cb->net)
64 			continue;
65 
66 		if (msk->bind_type != type)
67 			continue;
68 
69 		if (!mctp_address_matches(msk->bind_addr, mh->dest))
70 			continue;
71 
72 		return msk;
73 	}
74 
75 	return NULL;
76 }
77 
78 /* A note on the key allocations.
79  *
80  * struct net->mctp.keys contains our set of currently-allocated keys for
81  * MCTP tag management. The lookup tuple for these is the peer EID,
82  * local EID and MCTP tag.
83  *
84  * In some cases, the peer EID may be MCTP_EID_ANY: for example, when a
85  * broadcast message is sent, we may receive responses from any peer EID.
86  * Because the broadcast dest address is equivalent to ANY, we create
87  * a key with (local = local-eid, peer = ANY). This allows a match on the
88  * incoming broadcast responses from any peer.
89  *
90  * We perform lookups when packets are received, and when tags are allocated
91  * in two scenarios:
92  *
93  *  - when a packet is sent, with a locally-owned tag: we need to find an
94  *    unused tag value for the (local, peer) EID pair.
95  *
96  *  - when a tag is manually allocated: we need to find an unused tag value
97  *    for the peer EID, but don't have a specific local EID at that stage.
98  *
99  * in the latter case, on successful allocation, we end up with a tag with
100  * (local = ANY, peer = peer-eid).
101  *
102  * So, the key set allows both a local EID of ANY, as well as a peer EID of
103  * ANY in the lookup tuple. Both may be ANY if we prealloc for a broadcast.
104  * The matching (in mctp_key_match()) during lookup allows the match value to
105  * be ANY in either the dest or source addresses.
106  *
107  * When allocating (+ inserting) a tag, we need to check for conflicts amongst
108  * the existing tag set. This requires macthing either exactly on the local
109  * and peer addresses, or either being ANY.
110  */
111 
112 static bool mctp_key_match(struct mctp_sk_key *key, unsigned int net,
113 			   mctp_eid_t local, mctp_eid_t peer, u8 tag)
114 {
115 	if (key->net != net)
116 		return false;
117 
118 	if (!mctp_address_matches(key->local_addr, local))
119 		return false;
120 
121 	if (!mctp_address_matches(key->peer_addr, peer))
122 		return false;
123 
124 	if (key->tag != tag)
125 		return false;
126 
127 	return true;
128 }
129 
130 /* returns a key (with key->lock held, and refcounted), or NULL if no such
131  * key exists.
132  */
133 static struct mctp_sk_key *mctp_lookup_key(struct net *net, struct sk_buff *skb,
134 					   unsigned int netid, mctp_eid_t peer,
135 					   unsigned long *irqflags)
136 	__acquires(&key->lock)
137 {
138 	struct mctp_sk_key *key, *ret;
139 	unsigned long flags;
140 	struct mctp_hdr *mh;
141 	u8 tag;
142 
143 	mh = mctp_hdr(skb);
144 	tag = mh->flags_seq_tag & (MCTP_HDR_TAG_MASK | MCTP_HDR_FLAG_TO);
145 
146 	ret = NULL;
147 	spin_lock_irqsave(&net->mctp.keys_lock, flags);
148 
149 	hlist_for_each_entry(key, &net->mctp.keys, hlist) {
150 		if (!mctp_key_match(key, netid, mh->dest, peer, tag))
151 			continue;
152 
153 		spin_lock(&key->lock);
154 		if (key->valid) {
155 			refcount_inc(&key->refs);
156 			ret = key;
157 			break;
158 		}
159 		spin_unlock(&key->lock);
160 	}
161 
162 	if (ret) {
163 		spin_unlock(&net->mctp.keys_lock);
164 		*irqflags = flags;
165 	} else {
166 		spin_unlock_irqrestore(&net->mctp.keys_lock, flags);
167 	}
168 
169 	return ret;
170 }
171 
172 static struct mctp_sk_key *mctp_key_alloc(struct mctp_sock *msk,
173 					  unsigned int net,
174 					  mctp_eid_t local, mctp_eid_t peer,
175 					  u8 tag, gfp_t gfp)
176 {
177 	struct mctp_sk_key *key;
178 
179 	key = kzalloc(sizeof(*key), gfp);
180 	if (!key)
181 		return NULL;
182 
183 	key->net = net;
184 	key->peer_addr = peer;
185 	key->local_addr = local;
186 	key->tag = tag;
187 	key->sk = &msk->sk;
188 	key->valid = true;
189 	spin_lock_init(&key->lock);
190 	refcount_set(&key->refs, 1);
191 	sock_hold(key->sk);
192 
193 	return key;
194 }
195 
196 void mctp_key_unref(struct mctp_sk_key *key)
197 {
198 	unsigned long flags;
199 
200 	if (!refcount_dec_and_test(&key->refs))
201 		return;
202 
203 	/* even though no refs exist here, the lock allows us to stay
204 	 * consistent with the locking requirement of mctp_dev_release_key
205 	 */
206 	spin_lock_irqsave(&key->lock, flags);
207 	mctp_dev_release_key(key->dev, key);
208 	spin_unlock_irqrestore(&key->lock, flags);
209 
210 	sock_put(key->sk);
211 	kfree(key);
212 }
213 
214 static int mctp_key_add(struct mctp_sk_key *key, struct mctp_sock *msk)
215 {
216 	struct net *net = sock_net(&msk->sk);
217 	struct mctp_sk_key *tmp;
218 	unsigned long flags;
219 	int rc = 0;
220 
221 	spin_lock_irqsave(&net->mctp.keys_lock, flags);
222 
223 	if (sock_flag(&msk->sk, SOCK_DEAD)) {
224 		rc = -EINVAL;
225 		goto out_unlock;
226 	}
227 
228 	hlist_for_each_entry(tmp, &net->mctp.keys, hlist) {
229 		if (mctp_key_match(tmp, key->net, key->local_addr,
230 				   key->peer_addr, key->tag)) {
231 			spin_lock(&tmp->lock);
232 			if (tmp->valid)
233 				rc = -EEXIST;
234 			spin_unlock(&tmp->lock);
235 			if (rc)
236 				break;
237 		}
238 	}
239 
240 	if (!rc) {
241 		refcount_inc(&key->refs);
242 		key->expiry = jiffies + mctp_key_lifetime;
243 		timer_reduce(&msk->key_expiry, key->expiry);
244 
245 		hlist_add_head(&key->hlist, &net->mctp.keys);
246 		hlist_add_head(&key->sklist, &msk->keys);
247 	}
248 
249 out_unlock:
250 	spin_unlock_irqrestore(&net->mctp.keys_lock, flags);
251 
252 	return rc;
253 }
254 
255 /* Helper for mctp_route_input().
256  * We're done with the key; unlock and unref the key.
257  * For the usual case of automatic expiry we remove the key from lists.
258  * In the case that manual allocation is set on a key we release the lock
259  * and local ref, reset reassembly, but don't remove from lists.
260  */
261 static void __mctp_key_done_in(struct mctp_sk_key *key, struct net *net,
262 			       unsigned long flags, unsigned long reason)
263 __releases(&key->lock)
264 {
265 	struct sk_buff *skb;
266 
267 	trace_mctp_key_release(key, reason);
268 	skb = key->reasm_head;
269 	key->reasm_head = NULL;
270 
271 	if (!key->manual_alloc) {
272 		key->reasm_dead = true;
273 		key->valid = false;
274 		mctp_dev_release_key(key->dev, key);
275 	}
276 	spin_unlock_irqrestore(&key->lock, flags);
277 
278 	if (!key->manual_alloc) {
279 		spin_lock_irqsave(&net->mctp.keys_lock, flags);
280 		if (!hlist_unhashed(&key->hlist)) {
281 			hlist_del_init(&key->hlist);
282 			hlist_del_init(&key->sklist);
283 			mctp_key_unref(key);
284 		}
285 		spin_unlock_irqrestore(&net->mctp.keys_lock, flags);
286 	}
287 
288 	/* and one for the local reference */
289 	mctp_key_unref(key);
290 
291 	kfree_skb(skb);
292 }
293 
294 #ifdef CONFIG_MCTP_FLOWS
295 static void mctp_skb_set_flow(struct sk_buff *skb, struct mctp_sk_key *key)
296 {
297 	struct mctp_flow *flow;
298 
299 	flow = skb_ext_add(skb, SKB_EXT_MCTP);
300 	if (!flow)
301 		return;
302 
303 	refcount_inc(&key->refs);
304 	flow->key = key;
305 }
306 
307 static void mctp_flow_prepare_output(struct sk_buff *skb, struct mctp_dev *dev)
308 {
309 	struct mctp_sk_key *key;
310 	struct mctp_flow *flow;
311 
312 	flow = skb_ext_find(skb, SKB_EXT_MCTP);
313 	if (!flow)
314 		return;
315 
316 	key = flow->key;
317 
318 	if (key->dev) {
319 		WARN_ON(key->dev != dev);
320 		return;
321 	}
322 
323 	mctp_dev_set_key(dev, key);
324 }
325 #else
326 static void mctp_skb_set_flow(struct sk_buff *skb, struct mctp_sk_key *key) {}
327 static void mctp_flow_prepare_output(struct sk_buff *skb, struct mctp_dev *dev) {}
328 #endif
329 
330 static int mctp_frag_queue(struct mctp_sk_key *key, struct sk_buff *skb)
331 {
332 	struct mctp_hdr *hdr = mctp_hdr(skb);
333 	u8 exp_seq, this_seq;
334 
335 	this_seq = (hdr->flags_seq_tag >> MCTP_HDR_SEQ_SHIFT)
336 		& MCTP_HDR_SEQ_MASK;
337 
338 	if (!key->reasm_head) {
339 		/* Since we're manipulating the shared frag_list, ensure it isn't
340 		 * shared with any other SKBs.
341 		 */
342 		key->reasm_head = skb_unshare(skb, GFP_ATOMIC);
343 		if (!key->reasm_head)
344 			return -ENOMEM;
345 
346 		key->reasm_tailp = &(skb_shinfo(key->reasm_head)->frag_list);
347 		key->last_seq = this_seq;
348 		return 0;
349 	}
350 
351 	exp_seq = (key->last_seq + 1) & MCTP_HDR_SEQ_MASK;
352 
353 	if (this_seq != exp_seq)
354 		return -EINVAL;
355 
356 	if (key->reasm_head->len + skb->len > mctp_message_maxlen)
357 		return -EINVAL;
358 
359 	skb->next = NULL;
360 	skb->sk = NULL;
361 	*key->reasm_tailp = skb;
362 	key->reasm_tailp = &skb->next;
363 
364 	key->last_seq = this_seq;
365 
366 	key->reasm_head->data_len += skb->len;
367 	key->reasm_head->len += skb->len;
368 	key->reasm_head->truesize += skb->truesize;
369 
370 	return 0;
371 }
372 
373 static int mctp_dst_input(struct mctp_dst *dst, struct sk_buff *skb)
374 {
375 	struct mctp_sk_key *key, *any_key = NULL;
376 	struct net *net = dev_net(skb->dev);
377 	struct mctp_sock *msk;
378 	struct mctp_hdr *mh;
379 	unsigned int netid;
380 	unsigned long f;
381 	u8 tag, flags;
382 	int rc;
383 
384 	msk = NULL;
385 	rc = -EINVAL;
386 
387 	/* We may be receiving a locally-routed packet; drop source sk
388 	 * accounting.
389 	 *
390 	 * From here, we will either queue the skb - either to a frag_queue, or
391 	 * to a receiving socket. When that succeeds, we clear the skb pointer;
392 	 * a non-NULL skb on exit will be otherwise unowned, and hence
393 	 * kfree_skb()-ed.
394 	 */
395 	skb_orphan(skb);
396 
397 	if (skb->pkt_type == PACKET_OUTGOING)
398 		skb->pkt_type = PACKET_LOOPBACK;
399 
400 	/* ensure we have enough data for a header and a type */
401 	if (skb->len < sizeof(struct mctp_hdr) + 1)
402 		goto out;
403 
404 	/* grab header, advance data ptr */
405 	mh = mctp_hdr(skb);
406 	netid = mctp_cb(skb)->net;
407 	skb_pull(skb, sizeof(struct mctp_hdr));
408 
409 	if (mh->ver != 1)
410 		goto out;
411 
412 	flags = mh->flags_seq_tag & (MCTP_HDR_FLAG_SOM | MCTP_HDR_FLAG_EOM);
413 	tag = mh->flags_seq_tag & (MCTP_HDR_TAG_MASK | MCTP_HDR_FLAG_TO);
414 
415 	rcu_read_lock();
416 
417 	/* lookup socket / reasm context, exactly matching (src,dest,tag).
418 	 * we hold a ref on the key, and key->lock held.
419 	 */
420 	key = mctp_lookup_key(net, skb, netid, mh->src, &f);
421 
422 	if (flags & MCTP_HDR_FLAG_SOM) {
423 		if (key) {
424 			msk = container_of(key->sk, struct mctp_sock, sk);
425 		} else {
426 			/* first response to a broadcast? do a more general
427 			 * key lookup to find the socket, but don't use this
428 			 * key for reassembly - we'll create a more specific
429 			 * one for future packets if required (ie, !EOM).
430 			 *
431 			 * this lookup requires key->peer to be MCTP_ADDR_ANY,
432 			 * it doesn't match just any key->peer.
433 			 */
434 			any_key = mctp_lookup_key(net, skb, netid,
435 						  MCTP_ADDR_ANY, &f);
436 			if (any_key) {
437 				msk = container_of(any_key->sk,
438 						   struct mctp_sock, sk);
439 				spin_unlock_irqrestore(&any_key->lock, f);
440 			}
441 		}
442 
443 		if (!key && !msk && (tag & MCTP_HDR_FLAG_TO))
444 			msk = mctp_lookup_bind(net, skb);
445 
446 		if (!msk) {
447 			rc = -ENOENT;
448 			goto out_unlock;
449 		}
450 
451 		/* single-packet message? deliver to socket, clean up any
452 		 * pending key.
453 		 */
454 		if (flags & MCTP_HDR_FLAG_EOM) {
455 			rc = sock_queue_rcv_skb(&msk->sk, skb);
456 			if (!rc)
457 				skb = NULL;
458 			if (key) {
459 				/* we've hit a pending reassembly; not much we
460 				 * can do but drop it
461 				 */
462 				__mctp_key_done_in(key, net, f,
463 						   MCTP_TRACE_KEY_REPLIED);
464 				key = NULL;
465 			}
466 			goto out_unlock;
467 		}
468 
469 		/* broadcast response or a bind() - create a key for further
470 		 * packets for this message
471 		 */
472 		if (!key) {
473 			key = mctp_key_alloc(msk, netid, mh->dest, mh->src,
474 					     tag, GFP_ATOMIC);
475 			if (!key) {
476 				rc = -ENOMEM;
477 				goto out_unlock;
478 			}
479 
480 			/* we can queue without the key lock here, as the
481 			 * key isn't observable yet
482 			 */
483 			mctp_frag_queue(key, skb);
484 
485 			/* if the key_add fails, we've raced with another
486 			 * SOM packet with the same src, dest and tag. There's
487 			 * no way to distinguish future packets, so all we
488 			 * can do is drop; we'll free the skb on exit from
489 			 * this function.
490 			 */
491 			rc = mctp_key_add(key, msk);
492 			if (!rc) {
493 				trace_mctp_key_acquire(key);
494 				skb = NULL;
495 			}
496 
497 			/* we don't need to release key->lock on exit, so
498 			 * clean up here and suppress the unlock via
499 			 * setting to NULL
500 			 */
501 			mctp_key_unref(key);
502 			key = NULL;
503 
504 		} else {
505 			if (key->reasm_head || key->reasm_dead) {
506 				/* duplicate start? drop everything */
507 				__mctp_key_done_in(key, net, f,
508 						   MCTP_TRACE_KEY_INVALIDATED);
509 				rc = -EEXIST;
510 				key = NULL;
511 			} else {
512 				rc = mctp_frag_queue(key, skb);
513 				if (!rc)
514 					skb = NULL;
515 			}
516 		}
517 
518 	} else if (key) {
519 		/* this packet continues a previous message; reassemble
520 		 * using the message-specific key
521 		 */
522 
523 		/* we need to be continuing an existing reassembly... */
524 		if (!key->reasm_head)
525 			rc = -EINVAL;
526 		else
527 			rc = mctp_frag_queue(key, skb);
528 
529 		if (rc)
530 			goto out_unlock;
531 
532 		/* we've queued; the queue owns the skb now */
533 		skb = NULL;
534 
535 		/* end of message? deliver to socket, and we're done with
536 		 * the reassembly/response key
537 		 */
538 		if (flags & MCTP_HDR_FLAG_EOM) {
539 			rc = sock_queue_rcv_skb(key->sk, key->reasm_head);
540 			if (!rc)
541 				key->reasm_head = NULL;
542 			__mctp_key_done_in(key, net, f, MCTP_TRACE_KEY_REPLIED);
543 			key = NULL;
544 		}
545 
546 	} else {
547 		/* not a start, no matching key */
548 		rc = -ENOENT;
549 	}
550 
551 out_unlock:
552 	rcu_read_unlock();
553 	if (key) {
554 		spin_unlock_irqrestore(&key->lock, f);
555 		mctp_key_unref(key);
556 	}
557 	if (any_key)
558 		mctp_key_unref(any_key);
559 out:
560 	kfree_skb(skb);
561 	return rc;
562 }
563 
564 static int mctp_dst_output(struct mctp_dst *dst, struct sk_buff *skb)
565 {
566 	char daddr_buf[MAX_ADDR_LEN];
567 	char *daddr = NULL;
568 	int rc;
569 
570 	skb->protocol = htons(ETH_P_MCTP);
571 	skb->pkt_type = PACKET_OUTGOING;
572 
573 	if (skb->len > dst->mtu) {
574 		kfree_skb(skb);
575 		return -EMSGSIZE;
576 	}
577 
578 	/* direct route; use the hwaddr we stashed in sendmsg */
579 	if (dst->halen) {
580 		if (dst->halen != skb->dev->addr_len) {
581 			/* sanity check, sendmsg should have already caught this */
582 			kfree_skb(skb);
583 			return -EMSGSIZE;
584 		}
585 		daddr = dst->haddr;
586 	} else {
587 		/* If lookup fails let the device handle daddr==NULL */
588 		if (mctp_neigh_lookup(dst->dev, dst->nexthop, daddr_buf) == 0)
589 			daddr = daddr_buf;
590 	}
591 
592 	rc = dev_hard_header(skb, skb->dev, ntohs(skb->protocol),
593 			     daddr, skb->dev->dev_addr, skb->len);
594 	if (rc < 0) {
595 		kfree_skb(skb);
596 		return -EHOSTUNREACH;
597 	}
598 
599 	mctp_flow_prepare_output(skb, dst->dev);
600 
601 	rc = dev_queue_xmit(skb);
602 	if (rc)
603 		rc = net_xmit_errno(rc);
604 
605 	return rc;
606 }
607 
608 /* route alloc/release */
609 static void mctp_route_release(struct mctp_route *rt)
610 {
611 	if (refcount_dec_and_test(&rt->refs)) {
612 		if (rt->dst_type == MCTP_ROUTE_DIRECT)
613 			mctp_dev_put(rt->dev);
614 		kfree_rcu(rt, rcu);
615 	}
616 }
617 
618 /* returns a route with the refcount at 1 */
619 static struct mctp_route *mctp_route_alloc(void)
620 {
621 	struct mctp_route *rt;
622 
623 	rt = kzalloc(sizeof(*rt), GFP_KERNEL);
624 	if (!rt)
625 		return NULL;
626 
627 	INIT_LIST_HEAD(&rt->list);
628 	refcount_set(&rt->refs, 1);
629 	rt->output = mctp_dst_discard;
630 
631 	return rt;
632 }
633 
634 unsigned int mctp_default_net(struct net *net)
635 {
636 	return READ_ONCE(net->mctp.default_net);
637 }
638 
639 int mctp_default_net_set(struct net *net, unsigned int index)
640 {
641 	if (index == 0)
642 		return -EINVAL;
643 	WRITE_ONCE(net->mctp.default_net, index);
644 	return 0;
645 }
646 
647 /* tag management */
648 static void mctp_reserve_tag(struct net *net, struct mctp_sk_key *key,
649 			     struct mctp_sock *msk)
650 {
651 	struct netns_mctp *mns = &net->mctp;
652 
653 	lockdep_assert_held(&mns->keys_lock);
654 
655 	key->expiry = jiffies + mctp_key_lifetime;
656 	timer_reduce(&msk->key_expiry, key->expiry);
657 
658 	/* we hold the net->key_lock here, allowing updates to both
659 	 * then net and sk
660 	 */
661 	hlist_add_head_rcu(&key->hlist, &mns->keys);
662 	hlist_add_head_rcu(&key->sklist, &msk->keys);
663 	refcount_inc(&key->refs);
664 }
665 
666 /* Allocate a locally-owned tag value for (local, peer), and reserve
667  * it for the socket msk
668  */
669 struct mctp_sk_key *mctp_alloc_local_tag(struct mctp_sock *msk,
670 					 unsigned int netid,
671 					 mctp_eid_t local, mctp_eid_t peer,
672 					 bool manual, u8 *tagp)
673 {
674 	struct net *net = sock_net(&msk->sk);
675 	struct netns_mctp *mns = &net->mctp;
676 	struct mctp_sk_key *key, *tmp;
677 	unsigned long flags;
678 	u8 tagbits;
679 
680 	/* for NULL destination EIDs, we may get a response from any peer */
681 	if (peer == MCTP_ADDR_NULL)
682 		peer = MCTP_ADDR_ANY;
683 
684 	/* be optimistic, alloc now */
685 	key = mctp_key_alloc(msk, netid, local, peer, 0, GFP_KERNEL);
686 	if (!key)
687 		return ERR_PTR(-ENOMEM);
688 
689 	/* 8 possible tag values */
690 	tagbits = 0xff;
691 
692 	spin_lock_irqsave(&mns->keys_lock, flags);
693 
694 	/* Walk through the existing keys, looking for potential conflicting
695 	 * tags. If we find a conflict, clear that bit from tagbits
696 	 */
697 	hlist_for_each_entry(tmp, &mns->keys, hlist) {
698 		/* We can check the lookup fields (*_addr, tag) without the
699 		 * lock held, they don't change over the lifetime of the key.
700 		 */
701 
702 		/* tags are net-specific */
703 		if (tmp->net != netid)
704 			continue;
705 
706 		/* if we don't own the tag, it can't conflict */
707 		if (tmp->tag & MCTP_HDR_FLAG_TO)
708 			continue;
709 
710 		/* Since we're avoiding conflicting entries, match peer and
711 		 * local addresses, including with a wildcard on ANY. See
712 		 * 'A note on key allocations' for background.
713 		 */
714 		if (peer != MCTP_ADDR_ANY &&
715 		    !mctp_address_matches(tmp->peer_addr, peer))
716 			continue;
717 
718 		if (local != MCTP_ADDR_ANY &&
719 		    !mctp_address_matches(tmp->local_addr, local))
720 			continue;
721 
722 		spin_lock(&tmp->lock);
723 		/* key must still be valid. If we find a match, clear the
724 		 * potential tag value
725 		 */
726 		if (tmp->valid)
727 			tagbits &= ~(1 << tmp->tag);
728 		spin_unlock(&tmp->lock);
729 
730 		if (!tagbits)
731 			break;
732 	}
733 
734 	if (tagbits) {
735 		key->tag = __ffs(tagbits);
736 		mctp_reserve_tag(net, key, msk);
737 		trace_mctp_key_acquire(key);
738 
739 		key->manual_alloc = manual;
740 		*tagp = key->tag;
741 	}
742 
743 	spin_unlock_irqrestore(&mns->keys_lock, flags);
744 
745 	if (!tagbits) {
746 		mctp_key_unref(key);
747 		return ERR_PTR(-EBUSY);
748 	}
749 
750 	return key;
751 }
752 
753 static struct mctp_sk_key *mctp_lookup_prealloc_tag(struct mctp_sock *msk,
754 						    unsigned int netid,
755 						    mctp_eid_t daddr,
756 						    u8 req_tag, u8 *tagp)
757 {
758 	struct net *net = sock_net(&msk->sk);
759 	struct netns_mctp *mns = &net->mctp;
760 	struct mctp_sk_key *key, *tmp;
761 	unsigned long flags;
762 
763 	req_tag &= ~(MCTP_TAG_PREALLOC | MCTP_TAG_OWNER);
764 	key = NULL;
765 
766 	spin_lock_irqsave(&mns->keys_lock, flags);
767 
768 	hlist_for_each_entry(tmp, &mns->keys, hlist) {
769 		if (tmp->net != netid)
770 			continue;
771 
772 		if (tmp->tag != req_tag)
773 			continue;
774 
775 		if (!mctp_address_matches(tmp->peer_addr, daddr))
776 			continue;
777 
778 		if (!tmp->manual_alloc)
779 			continue;
780 
781 		spin_lock(&tmp->lock);
782 		if (tmp->valid) {
783 			key = tmp;
784 			refcount_inc(&key->refs);
785 			spin_unlock(&tmp->lock);
786 			break;
787 		}
788 		spin_unlock(&tmp->lock);
789 	}
790 	spin_unlock_irqrestore(&mns->keys_lock, flags);
791 
792 	if (!key)
793 		return ERR_PTR(-ENOENT);
794 
795 	if (tagp)
796 		*tagp = key->tag;
797 
798 	return key;
799 }
800 
801 /* routing lookups */
802 static unsigned int mctp_route_netid(struct mctp_route *rt)
803 {
804 	return rt->dst_type == MCTP_ROUTE_DIRECT ?
805 		READ_ONCE(rt->dev->net) : rt->gateway.net;
806 }
807 
808 static bool mctp_rt_match_eid(struct mctp_route *rt,
809 			      unsigned int net, mctp_eid_t eid)
810 {
811 	return mctp_route_netid(rt) == net &&
812 		rt->min <= eid && rt->max >= eid;
813 }
814 
815 /* compares match, used for duplicate prevention */
816 static bool mctp_rt_compare_exact(struct mctp_route *rt1,
817 				  struct mctp_route *rt2)
818 {
819 	ASSERT_RTNL();
820 	return mctp_route_netid(rt1) == mctp_route_netid(rt2) &&
821 		rt1->min == rt2->min &&
822 		rt1->max == rt2->max;
823 }
824 
825 /* must only be called on a direct route, as the final output hop */
826 static void mctp_dst_from_route(struct mctp_dst *dst, mctp_eid_t eid,
827 				unsigned int mtu, struct mctp_route *route)
828 {
829 	mctp_dev_hold(route->dev);
830 	dst->nexthop = eid;
831 	dst->dev = route->dev;
832 	dst->mtu = READ_ONCE(dst->dev->dev->mtu);
833 	if (mtu)
834 		dst->mtu = min(dst->mtu, mtu);
835 	dst->halen = 0;
836 	dst->output = route->output;
837 }
838 
839 int mctp_dst_from_extaddr(struct mctp_dst *dst, struct net *net, int ifindex,
840 			  unsigned char halen, const unsigned char *haddr)
841 {
842 	struct net_device *netdev;
843 	struct mctp_dev *dev;
844 	int rc = -ENOENT;
845 
846 	if (halen > sizeof(dst->haddr))
847 		return -EINVAL;
848 
849 	rcu_read_lock();
850 
851 	netdev = dev_get_by_index_rcu(net, ifindex);
852 	if (!netdev)
853 		goto out_unlock;
854 
855 	if (netdev->addr_len != halen) {
856 		rc = -EINVAL;
857 		goto out_unlock;
858 	}
859 
860 	dev = __mctp_dev_get(netdev);
861 	if (!dev)
862 		goto out_unlock;
863 
864 	dst->dev = dev;
865 	dst->mtu = READ_ONCE(netdev->mtu);
866 	dst->halen = halen;
867 	dst->output = mctp_dst_output;
868 	dst->nexthop = 0;
869 	memcpy(dst->haddr, haddr, halen);
870 
871 	rc = 0;
872 
873 out_unlock:
874 	rcu_read_unlock();
875 	return rc;
876 }
877 
878 void mctp_dst_release(struct mctp_dst *dst)
879 {
880 	mctp_dev_put(dst->dev);
881 }
882 
883 static struct mctp_route *mctp_route_lookup_single(struct net *net,
884 						   unsigned int dnet,
885 						   mctp_eid_t daddr)
886 {
887 	struct mctp_route *rt;
888 
889 	list_for_each_entry_rcu(rt, &net->mctp.routes, list) {
890 		if (mctp_rt_match_eid(rt, dnet, daddr))
891 			return rt;
892 	}
893 
894 	return NULL;
895 }
896 
897 /* populates *dst on successful lookup, if set */
898 int mctp_route_lookup(struct net *net, unsigned int dnet,
899 		      mctp_eid_t daddr, struct mctp_dst *dst)
900 {
901 	const unsigned int max_depth = 32;
902 	unsigned int depth, mtu = 0;
903 	int rc = -EHOSTUNREACH;
904 
905 	rcu_read_lock();
906 
907 	for (depth = 0; depth < max_depth; depth++) {
908 		struct mctp_route *rt;
909 
910 		rt = mctp_route_lookup_single(net, dnet, daddr);
911 		if (!rt)
912 			break;
913 
914 		/* clamp mtu to the smallest in the path, allowing 0
915 		 * to specify no restrictions
916 		 */
917 		if (mtu && rt->mtu)
918 			mtu = min(mtu, rt->mtu);
919 		else
920 			mtu = mtu ?: rt->mtu;
921 
922 		if (rt->dst_type == MCTP_ROUTE_DIRECT) {
923 			if (dst)
924 				mctp_dst_from_route(dst, daddr, mtu, rt);
925 			rc = 0;
926 			break;
927 
928 		} else if (rt->dst_type == MCTP_ROUTE_GATEWAY) {
929 			daddr = rt->gateway.eid;
930 		}
931 	}
932 
933 	rcu_read_unlock();
934 
935 	return rc;
936 }
937 
938 static int mctp_route_lookup_null(struct net *net, struct net_device *dev,
939 				  struct mctp_dst *dst)
940 {
941 	int rc = -EHOSTUNREACH;
942 	struct mctp_route *rt;
943 
944 	rcu_read_lock();
945 
946 	list_for_each_entry_rcu(rt, &net->mctp.routes, list) {
947 		if (rt->dst_type != MCTP_ROUTE_DIRECT || rt->type != RTN_LOCAL)
948 			continue;
949 
950 		if (rt->dev->dev != dev)
951 			continue;
952 
953 		mctp_dst_from_route(dst, 0, 0, rt);
954 		rc = 0;
955 		break;
956 	}
957 
958 	rcu_read_unlock();
959 
960 	return rc;
961 }
962 
963 static int mctp_do_fragment_route(struct mctp_dst *dst, struct sk_buff *skb,
964 				  unsigned int mtu, u8 tag)
965 {
966 	const unsigned int hlen = sizeof(struct mctp_hdr);
967 	struct mctp_hdr *hdr, *hdr2;
968 	unsigned int pos, size, headroom;
969 	struct sk_buff *skb2;
970 	int rc;
971 	u8 seq;
972 
973 	hdr = mctp_hdr(skb);
974 	seq = 0;
975 	rc = 0;
976 
977 	if (mtu < hlen + 1) {
978 		kfree_skb(skb);
979 		return -EMSGSIZE;
980 	}
981 
982 	/* keep same headroom as the original skb */
983 	headroom = skb_headroom(skb);
984 
985 	/* we've got the header */
986 	skb_pull(skb, hlen);
987 
988 	for (pos = 0; pos < skb->len;) {
989 		/* size of message payload */
990 		size = min(mtu - hlen, skb->len - pos);
991 
992 		skb2 = alloc_skb(headroom + hlen + size, GFP_KERNEL);
993 		if (!skb2) {
994 			rc = -ENOMEM;
995 			break;
996 		}
997 
998 		/* generic skb copy */
999 		skb2->protocol = skb->protocol;
1000 		skb2->priority = skb->priority;
1001 		skb2->dev = skb->dev;
1002 		memcpy(skb2->cb, skb->cb, sizeof(skb2->cb));
1003 
1004 		if (skb->sk)
1005 			skb_set_owner_w(skb2, skb->sk);
1006 
1007 		/* establish packet */
1008 		skb_reserve(skb2, headroom);
1009 		skb_reset_network_header(skb2);
1010 		skb_put(skb2, hlen + size);
1011 		skb2->transport_header = skb2->network_header + hlen;
1012 
1013 		/* copy header fields, calculate SOM/EOM flags & seq */
1014 		hdr2 = mctp_hdr(skb2);
1015 		hdr2->ver = hdr->ver;
1016 		hdr2->dest = hdr->dest;
1017 		hdr2->src = hdr->src;
1018 		hdr2->flags_seq_tag = tag &
1019 			(MCTP_HDR_TAG_MASK | MCTP_HDR_FLAG_TO);
1020 
1021 		if (pos == 0)
1022 			hdr2->flags_seq_tag |= MCTP_HDR_FLAG_SOM;
1023 
1024 		if (pos + size == skb->len)
1025 			hdr2->flags_seq_tag |= MCTP_HDR_FLAG_EOM;
1026 
1027 		hdr2->flags_seq_tag |= seq << MCTP_HDR_SEQ_SHIFT;
1028 
1029 		/* copy message payload */
1030 		skb_copy_bits(skb, pos, skb_transport_header(skb2), size);
1031 
1032 		/* we need to copy the extensions, for MCTP flow data */
1033 		skb_ext_copy(skb2, skb);
1034 
1035 		/* do route */
1036 		rc = dst->output(dst, skb2);
1037 		if (rc)
1038 			break;
1039 
1040 		seq = (seq + 1) & MCTP_HDR_SEQ_MASK;
1041 		pos += size;
1042 	}
1043 
1044 	consume_skb(skb);
1045 	return rc;
1046 }
1047 
1048 int mctp_local_output(struct sock *sk, struct mctp_dst *dst,
1049 		      struct sk_buff *skb, mctp_eid_t daddr, u8 req_tag)
1050 {
1051 	struct mctp_sock *msk = container_of(sk, struct mctp_sock, sk);
1052 	struct mctp_sk_key *key;
1053 	struct mctp_hdr *hdr;
1054 	unsigned long flags;
1055 	unsigned int netid;
1056 	unsigned int mtu;
1057 	mctp_eid_t saddr;
1058 	int rc;
1059 	u8 tag;
1060 
1061 	KUNIT_STATIC_STUB_REDIRECT(mctp_local_output, sk, dst, skb, daddr,
1062 				   req_tag);
1063 
1064 	rc = -ENODEV;
1065 
1066 	spin_lock_irqsave(&dst->dev->addrs_lock, flags);
1067 	if (dst->dev->num_addrs == 0) {
1068 		rc = -EHOSTUNREACH;
1069 	} else {
1070 		/* use the outbound interface's first address as our source */
1071 		saddr = dst->dev->addrs[0];
1072 		rc = 0;
1073 	}
1074 	spin_unlock_irqrestore(&dst->dev->addrs_lock, flags);
1075 	netid = READ_ONCE(dst->dev->net);
1076 
1077 	if (rc)
1078 		goto out_release;
1079 
1080 	if (req_tag & MCTP_TAG_OWNER) {
1081 		if (req_tag & MCTP_TAG_PREALLOC)
1082 			key = mctp_lookup_prealloc_tag(msk, netid, daddr,
1083 						       req_tag, &tag);
1084 		else
1085 			key = mctp_alloc_local_tag(msk, netid, saddr, daddr,
1086 						   false, &tag);
1087 
1088 		if (IS_ERR(key)) {
1089 			rc = PTR_ERR(key);
1090 			goto out_release;
1091 		}
1092 		mctp_skb_set_flow(skb, key);
1093 		/* done with the key in this scope */
1094 		mctp_key_unref(key);
1095 		tag |= MCTP_HDR_FLAG_TO;
1096 	} else {
1097 		key = NULL;
1098 		tag = req_tag & MCTP_TAG_MASK;
1099 	}
1100 
1101 	skb->pkt_type = PACKET_OUTGOING;
1102 	skb->protocol = htons(ETH_P_MCTP);
1103 	skb->priority = 0;
1104 	skb_reset_transport_header(skb);
1105 	skb_push(skb, sizeof(struct mctp_hdr));
1106 	skb_reset_network_header(skb);
1107 	skb->dev = dst->dev->dev;
1108 
1109 	/* set up common header fields */
1110 	hdr = mctp_hdr(skb);
1111 	hdr->ver = 1;
1112 	hdr->dest = daddr;
1113 	hdr->src = saddr;
1114 
1115 	mtu = dst->mtu;
1116 
1117 	if (skb->len + sizeof(struct mctp_hdr) <= mtu) {
1118 		hdr->flags_seq_tag = MCTP_HDR_FLAG_SOM |
1119 			MCTP_HDR_FLAG_EOM | tag;
1120 		rc = dst->output(dst, skb);
1121 	} else {
1122 		rc = mctp_do_fragment_route(dst, skb, mtu, tag);
1123 	}
1124 
1125 	/* route output functions consume the skb, even on error */
1126 	skb = NULL;
1127 
1128 out_release:
1129 	kfree_skb(skb);
1130 	return rc;
1131 }
1132 
1133 /* route management */
1134 
1135 /* mctp_route_add(): Add the provided route, previously allocated via
1136  * mctp_route_alloc(). On success, takes ownership of @rt, which includes a
1137  * hold on rt->dev for usage in the route table. On failure a caller will want
1138  * to mctp_route_release().
1139  *
1140  * We expect that the caller has set rt->type, rt->dst_type, rt->min, rt->max,
1141  * rt->mtu and either rt->dev (with a reference held appropriately) or
1142  * rt->gateway. Other fields will be populated.
1143  */
1144 static int mctp_route_add(struct net *net, struct mctp_route *rt)
1145 {
1146 	struct mctp_route *ert;
1147 
1148 	if (!mctp_address_unicast(rt->min) || !mctp_address_unicast(rt->max))
1149 		return -EINVAL;
1150 
1151 	if (rt->dst_type == MCTP_ROUTE_DIRECT && !rt->dev)
1152 		return -EINVAL;
1153 
1154 	if (rt->dst_type == MCTP_ROUTE_GATEWAY && !rt->gateway.eid)
1155 		return -EINVAL;
1156 
1157 	switch (rt->type) {
1158 	case RTN_LOCAL:
1159 		rt->output = mctp_dst_input;
1160 		break;
1161 	case RTN_UNICAST:
1162 		rt->output = mctp_dst_output;
1163 		break;
1164 	default:
1165 		return -EINVAL;
1166 	}
1167 
1168 	ASSERT_RTNL();
1169 
1170 	/* Prevent duplicate identical routes. */
1171 	list_for_each_entry(ert, &net->mctp.routes, list) {
1172 		if (mctp_rt_compare_exact(rt, ert)) {
1173 			return -EEXIST;
1174 		}
1175 	}
1176 
1177 	list_add_rcu(&rt->list, &net->mctp.routes);
1178 
1179 	return 0;
1180 }
1181 
1182 static int mctp_route_remove(struct net *net, unsigned int netid,
1183 			     mctp_eid_t daddr_start, unsigned int daddr_extent,
1184 			     unsigned char type)
1185 {
1186 	struct mctp_route *rt, *tmp;
1187 	mctp_eid_t daddr_end;
1188 	bool dropped;
1189 
1190 	if (daddr_extent > 0xff || daddr_start + daddr_extent >= 255)
1191 		return -EINVAL;
1192 
1193 	daddr_end = daddr_start + daddr_extent;
1194 	dropped = false;
1195 
1196 	ASSERT_RTNL();
1197 
1198 	list_for_each_entry_safe(rt, tmp, &net->mctp.routes, list) {
1199 		if (mctp_route_netid(rt) == netid &&
1200 		    rt->min == daddr_start && rt->max == daddr_end &&
1201 		    rt->type == type) {
1202 			list_del_rcu(&rt->list);
1203 			/* TODO: immediate RTM_DELROUTE */
1204 			mctp_route_release(rt);
1205 			dropped = true;
1206 		}
1207 	}
1208 
1209 	return dropped ? 0 : -ENOENT;
1210 }
1211 
1212 int mctp_route_add_local(struct mctp_dev *mdev, mctp_eid_t addr)
1213 {
1214 	struct mctp_route *rt;
1215 	int rc;
1216 
1217 	rt = mctp_route_alloc();
1218 	if (!rt)
1219 		return -ENOMEM;
1220 
1221 	rt->min = addr;
1222 	rt->max = addr;
1223 	rt->dst_type = MCTP_ROUTE_DIRECT;
1224 	rt->dev = mdev;
1225 	rt->type = RTN_LOCAL;
1226 
1227 	mctp_dev_hold(rt->dev);
1228 
1229 	rc = mctp_route_add(dev_net(mdev->dev), rt);
1230 	if (rc)
1231 		mctp_route_release(rt);
1232 
1233 	return rc;
1234 }
1235 
1236 int mctp_route_remove_local(struct mctp_dev *mdev, mctp_eid_t addr)
1237 {
1238 	return mctp_route_remove(dev_net(mdev->dev), mdev->net,
1239 				 addr, 0, RTN_LOCAL);
1240 }
1241 
1242 /* removes all entries for a given device */
1243 void mctp_route_remove_dev(struct mctp_dev *mdev)
1244 {
1245 	struct net *net = dev_net(mdev->dev);
1246 	struct mctp_route *rt, *tmp;
1247 
1248 	ASSERT_RTNL();
1249 	list_for_each_entry_safe(rt, tmp, &net->mctp.routes, list) {
1250 		if (rt->dst_type == MCTP_ROUTE_DIRECT && rt->dev == mdev) {
1251 			list_del_rcu(&rt->list);
1252 			/* TODO: immediate RTM_DELROUTE */
1253 			mctp_route_release(rt);
1254 		}
1255 	}
1256 }
1257 
1258 /* Incoming packet-handling */
1259 
1260 static int mctp_pkttype_receive(struct sk_buff *skb, struct net_device *dev,
1261 				struct packet_type *pt,
1262 				struct net_device *orig_dev)
1263 {
1264 	struct net *net = dev_net(dev);
1265 	struct mctp_dev *mdev;
1266 	struct mctp_skb_cb *cb;
1267 	struct mctp_dst dst;
1268 	struct mctp_hdr *mh;
1269 	int rc;
1270 
1271 	rcu_read_lock();
1272 	mdev = __mctp_dev_get(dev);
1273 	rcu_read_unlock();
1274 	if (!mdev) {
1275 		/* basic non-data sanity checks */
1276 		goto err_drop;
1277 	}
1278 
1279 	if (!pskb_may_pull(skb, sizeof(struct mctp_hdr)))
1280 		goto err_drop;
1281 
1282 	skb_reset_transport_header(skb);
1283 	skb_reset_network_header(skb);
1284 
1285 	/* We have enough for a header; decode and route */
1286 	mh = mctp_hdr(skb);
1287 	if (mh->ver < MCTP_VER_MIN || mh->ver > MCTP_VER_MAX)
1288 		goto err_drop;
1289 
1290 	/* source must be valid unicast or null; drop reserved ranges and
1291 	 * broadcast
1292 	 */
1293 	if (!(mctp_address_unicast(mh->src) || mctp_address_null(mh->src)))
1294 		goto err_drop;
1295 
1296 	/* dest address: as above, but allow broadcast */
1297 	if (!(mctp_address_unicast(mh->dest) || mctp_address_null(mh->dest) ||
1298 	      mctp_address_broadcast(mh->dest)))
1299 		goto err_drop;
1300 
1301 	/* MCTP drivers must populate halen/haddr */
1302 	if (dev->type == ARPHRD_MCTP) {
1303 		cb = mctp_cb(skb);
1304 	} else {
1305 		cb = __mctp_cb(skb);
1306 		cb->halen = 0;
1307 	}
1308 	cb->net = READ_ONCE(mdev->net);
1309 	cb->ifindex = dev->ifindex;
1310 
1311 	rc = mctp_route_lookup(net, cb->net, mh->dest, &dst);
1312 
1313 	/* NULL EID, but addressed to our physical address */
1314 	if (rc && mh->dest == MCTP_ADDR_NULL && skb->pkt_type == PACKET_HOST)
1315 		rc = mctp_route_lookup_null(net, dev, &dst);
1316 
1317 	if (rc)
1318 		goto err_drop;
1319 
1320 	dst.output(&dst, skb);
1321 	mctp_dst_release(&dst);
1322 	mctp_dev_put(mdev);
1323 
1324 	return NET_RX_SUCCESS;
1325 
1326 err_drop:
1327 	kfree_skb(skb);
1328 	mctp_dev_put(mdev);
1329 	return NET_RX_DROP;
1330 }
1331 
1332 static struct packet_type mctp_packet_type = {
1333 	.type = cpu_to_be16(ETH_P_MCTP),
1334 	.func = mctp_pkttype_receive,
1335 };
1336 
1337 /* netlink interface */
1338 
1339 static const struct nla_policy rta_mctp_policy[RTA_MAX + 1] = {
1340 	[RTA_DST]		= { .type = NLA_U8 },
1341 	[RTA_METRICS]		= { .type = NLA_NESTED },
1342 	[RTA_OIF]		= { .type = NLA_U32 },
1343 	[RTA_GATEWAY]		= NLA_POLICY_EXACT_LEN(sizeof(struct mctp_fq_addr)),
1344 };
1345 
1346 static const struct nla_policy rta_metrics_policy[RTAX_MAX + 1] = {
1347 	[RTAX_MTU]		= { .type = NLA_U32 },
1348 };
1349 
1350 /* base parsing; common to both _lookup and _populate variants.
1351  *
1352  * For gateway routes (which have a RTA_GATEWAY, and no RTA_OIF), we populate
1353  * *gatweayp. for direct routes (RTA_OIF, no RTA_GATEWAY), we populate *mdev.
1354  */
1355 static int mctp_route_nlparse_common(struct net *net, struct nlmsghdr *nlh,
1356 				     struct netlink_ext_ack *extack,
1357 				     struct nlattr **tb, struct rtmsg **rtm,
1358 				     struct mctp_dev **mdev,
1359 				     struct mctp_fq_addr *gatewayp,
1360 				     mctp_eid_t *daddr_start)
1361 {
1362 	struct mctp_fq_addr *gateway = NULL;
1363 	unsigned int ifindex = 0;
1364 	struct net_device *dev;
1365 	int rc;
1366 
1367 	rc = nlmsg_parse(nlh, sizeof(struct rtmsg), tb, RTA_MAX,
1368 			 rta_mctp_policy, extack);
1369 	if (rc < 0) {
1370 		NL_SET_ERR_MSG(extack, "incorrect format");
1371 		return rc;
1372 	}
1373 
1374 	if (!tb[RTA_DST]) {
1375 		NL_SET_ERR_MSG(extack, "dst EID missing");
1376 		return -EINVAL;
1377 	}
1378 	*daddr_start = nla_get_u8(tb[RTA_DST]);
1379 
1380 	if (tb[RTA_OIF])
1381 		ifindex = nla_get_u32(tb[RTA_OIF]);
1382 
1383 	if (tb[RTA_GATEWAY])
1384 		gateway = nla_data(tb[RTA_GATEWAY]);
1385 
1386 	if (ifindex && gateway) {
1387 		NL_SET_ERR_MSG(extack,
1388 			       "cannot specify both ifindex and gateway");
1389 		return -EINVAL;
1390 
1391 	} else if (ifindex) {
1392 		dev = __dev_get_by_index(net, ifindex);
1393 		if (!dev) {
1394 			NL_SET_ERR_MSG(extack, "bad ifindex");
1395 			return -ENODEV;
1396 		}
1397 		*mdev = mctp_dev_get_rtnl(dev);
1398 		if (!*mdev)
1399 			return -ENODEV;
1400 		gatewayp->eid = 0;
1401 
1402 	} else if (gateway) {
1403 		if (!mctp_address_unicast(gateway->eid)) {
1404 			NL_SET_ERR_MSG(extack, "bad gateway");
1405 			return -EINVAL;
1406 		}
1407 
1408 		gatewayp->eid = gateway->eid;
1409 		gatewayp->net = gateway->net != MCTP_NET_ANY ?
1410 			gateway->net :
1411 			READ_ONCE(net->mctp.default_net);
1412 		*mdev = NULL;
1413 
1414 	} else {
1415 		NL_SET_ERR_MSG(extack, "no route output provided");
1416 		return -EINVAL;
1417 	}
1418 
1419 	*rtm = nlmsg_data(nlh);
1420 	if ((*rtm)->rtm_family != AF_MCTP) {
1421 		NL_SET_ERR_MSG(extack, "route family must be AF_MCTP");
1422 		return -EINVAL;
1423 	}
1424 
1425 	if ((*rtm)->rtm_type != RTN_UNICAST) {
1426 		NL_SET_ERR_MSG(extack, "rtm_type must be RTN_UNICAST");
1427 		return -EINVAL;
1428 	}
1429 
1430 	return 0;
1431 }
1432 
1433 /* Route parsing for lookup operations; we only need the "route target"
1434  * components (ie., network and dest-EID range).
1435  */
1436 static int mctp_route_nlparse_lookup(struct net *net, struct nlmsghdr *nlh,
1437 				     struct netlink_ext_ack *extack,
1438 				     unsigned char *type, unsigned int *netid,
1439 				     mctp_eid_t *daddr_start,
1440 				     unsigned int *daddr_extent)
1441 {
1442 	struct nlattr *tb[RTA_MAX + 1];
1443 	struct mctp_fq_addr gw;
1444 	struct mctp_dev *mdev;
1445 	struct rtmsg *rtm;
1446 	int rc;
1447 
1448 	rc = mctp_route_nlparse_common(net, nlh, extack, tb, &rtm,
1449 				       &mdev, &gw, daddr_start);
1450 	if (rc)
1451 		return rc;
1452 
1453 	if (mdev) {
1454 		*netid = mdev->net;
1455 	} else if (gw.eid) {
1456 		*netid = gw.net;
1457 	} else {
1458 		/* bug: _nlparse_common should not allow this */
1459 		return -1;
1460 	}
1461 
1462 	*type = rtm->rtm_type;
1463 	*daddr_extent = rtm->rtm_dst_len;
1464 
1465 	return 0;
1466 }
1467 
1468 /* Full route parse for RTM_NEWROUTE: populate @rt. On success,
1469  * MCTP_ROUTE_DIRECT routes (ie, those with a direct dev) will hold a reference
1470  * to that dev.
1471  */
1472 static int mctp_route_nlparse_populate(struct net *net, struct nlmsghdr *nlh,
1473 				       struct netlink_ext_ack *extack,
1474 				       struct mctp_route *rt)
1475 {
1476 	struct nlattr *tbx[RTAX_MAX + 1];
1477 	struct nlattr *tb[RTA_MAX + 1];
1478 	unsigned int daddr_extent;
1479 	struct mctp_fq_addr gw;
1480 	mctp_eid_t daddr_start;
1481 	struct mctp_dev *dev;
1482 	struct rtmsg *rtm;
1483 	u32 mtu = 0;
1484 	int rc;
1485 
1486 	rc = mctp_route_nlparse_common(net, nlh, extack, tb, &rtm,
1487 				       &dev, &gw, &daddr_start);
1488 	if (rc)
1489 		return rc;
1490 
1491 	daddr_extent = rtm->rtm_dst_len;
1492 
1493 	if (daddr_extent > 0xff || daddr_extent + daddr_start >= 255) {
1494 		NL_SET_ERR_MSG(extack, "invalid eid range");
1495 		return -EINVAL;
1496 	}
1497 
1498 	if (tb[RTA_METRICS]) {
1499 		rc = nla_parse_nested(tbx, RTAX_MAX, tb[RTA_METRICS],
1500 				      rta_metrics_policy, NULL);
1501 		if (rc < 0) {
1502 			NL_SET_ERR_MSG(extack, "incorrect RTA_METRICS format");
1503 			return rc;
1504 		}
1505 		if (tbx[RTAX_MTU])
1506 			mtu = nla_get_u32(tbx[RTAX_MTU]);
1507 	}
1508 
1509 	rt->type = rtm->rtm_type;
1510 	rt->min = daddr_start;
1511 	rt->max = daddr_start + daddr_extent;
1512 	rt->mtu = mtu;
1513 	if (gw.eid) {
1514 		rt->dst_type = MCTP_ROUTE_GATEWAY;
1515 		rt->gateway.eid = gw.eid;
1516 		rt->gateway.net = gw.net;
1517 	} else {
1518 		rt->dst_type = MCTP_ROUTE_DIRECT;
1519 		rt->dev = dev;
1520 		mctp_dev_hold(rt->dev);
1521 	}
1522 
1523 	return 0;
1524 }
1525 
1526 static int mctp_newroute(struct sk_buff *skb, struct nlmsghdr *nlh,
1527 			 struct netlink_ext_ack *extack)
1528 {
1529 	struct net *net = sock_net(skb->sk);
1530 	struct mctp_route *rt;
1531 	int rc;
1532 
1533 	rt = mctp_route_alloc();
1534 	if (!rt)
1535 		return -ENOMEM;
1536 
1537 	rc = mctp_route_nlparse_populate(net, nlh, extack, rt);
1538 	if (rc < 0)
1539 		goto err_free;
1540 
1541 	if (rt->dst_type == MCTP_ROUTE_DIRECT &&
1542 	    rt->dev->dev->flags & IFF_LOOPBACK) {
1543 		NL_SET_ERR_MSG(extack, "no routes to loopback");
1544 		rc = -EINVAL;
1545 		goto err_free;
1546 	}
1547 
1548 	rc = mctp_route_add(net, rt);
1549 	if (!rc)
1550 		return 0;
1551 
1552 err_free:
1553 	mctp_route_release(rt);
1554 	return rc;
1555 }
1556 
1557 static int mctp_delroute(struct sk_buff *skb, struct nlmsghdr *nlh,
1558 			 struct netlink_ext_ack *extack)
1559 {
1560 	struct net *net = sock_net(skb->sk);
1561 	unsigned int netid, daddr_extent;
1562 	unsigned char type = RTN_UNSPEC;
1563 	mctp_eid_t daddr_start;
1564 	int rc;
1565 
1566 	rc = mctp_route_nlparse_lookup(net, nlh, extack, &type, &netid,
1567 				       &daddr_start, &daddr_extent);
1568 	if (rc < 0)
1569 		return rc;
1570 
1571 	/* we only have unicast routes */
1572 	if (type != RTN_UNICAST)
1573 		return -EINVAL;
1574 
1575 	rc = mctp_route_remove(net, netid, daddr_start, daddr_extent, type);
1576 	return rc;
1577 }
1578 
1579 static int mctp_fill_rtinfo(struct sk_buff *skb, struct mctp_route *rt,
1580 			    u32 portid, u32 seq, int event, unsigned int flags)
1581 {
1582 	struct nlmsghdr *nlh;
1583 	struct rtmsg *hdr;
1584 	void *metrics;
1585 
1586 	nlh = nlmsg_put(skb, portid, seq, event, sizeof(*hdr), flags);
1587 	if (!nlh)
1588 		return -EMSGSIZE;
1589 
1590 	hdr = nlmsg_data(nlh);
1591 	hdr->rtm_family = AF_MCTP;
1592 
1593 	/* we use the _len fields as a number of EIDs, rather than
1594 	 * a number of bits in the address
1595 	 */
1596 	hdr->rtm_dst_len = rt->max - rt->min;
1597 	hdr->rtm_src_len = 0;
1598 	hdr->rtm_tos = 0;
1599 	hdr->rtm_table = RT_TABLE_DEFAULT;
1600 	hdr->rtm_protocol = RTPROT_STATIC; /* everything is user-defined */
1601 	hdr->rtm_type = rt->type;
1602 
1603 	if (nla_put_u8(skb, RTA_DST, rt->min))
1604 		goto cancel;
1605 
1606 	metrics = nla_nest_start_noflag(skb, RTA_METRICS);
1607 	if (!metrics)
1608 		goto cancel;
1609 
1610 	if (rt->mtu) {
1611 		if (nla_put_u32(skb, RTAX_MTU, rt->mtu))
1612 			goto cancel;
1613 	}
1614 
1615 	nla_nest_end(skb, metrics);
1616 
1617 	if (rt->dst_type == MCTP_ROUTE_DIRECT) {
1618 		hdr->rtm_scope = RT_SCOPE_LINK;
1619 		if (nla_put_u32(skb, RTA_OIF, rt->dev->dev->ifindex))
1620 			goto cancel;
1621 	} else if (rt->dst_type == MCTP_ROUTE_GATEWAY) {
1622 		hdr->rtm_scope = RT_SCOPE_UNIVERSE;
1623 		if (nla_put(skb, RTA_GATEWAY,
1624 			    sizeof(rt->gateway), &rt->gateway))
1625 			goto cancel;
1626 	}
1627 
1628 	nlmsg_end(skb, nlh);
1629 
1630 	return 0;
1631 
1632 cancel:
1633 	nlmsg_cancel(skb, nlh);
1634 	return -EMSGSIZE;
1635 }
1636 
1637 static int mctp_dump_rtinfo(struct sk_buff *skb, struct netlink_callback *cb)
1638 {
1639 	struct net *net = sock_net(skb->sk);
1640 	struct mctp_route *rt;
1641 	int s_idx, idx;
1642 
1643 	/* TODO: allow filtering on route data, possibly under
1644 	 * cb->strict_check
1645 	 */
1646 
1647 	/* TODO: change to struct overlay */
1648 	s_idx = cb->args[0];
1649 	idx = 0;
1650 
1651 	rcu_read_lock();
1652 	list_for_each_entry_rcu(rt, &net->mctp.routes, list) {
1653 		if (idx++ < s_idx)
1654 			continue;
1655 		if (mctp_fill_rtinfo(skb, rt,
1656 				     NETLINK_CB(cb->skb).portid,
1657 				     cb->nlh->nlmsg_seq,
1658 				     RTM_NEWROUTE, NLM_F_MULTI) < 0)
1659 			break;
1660 	}
1661 
1662 	rcu_read_unlock();
1663 	cb->args[0] = idx;
1664 
1665 	return skb->len;
1666 }
1667 
1668 /* net namespace implementation */
1669 static int __net_init mctp_routes_net_init(struct net *net)
1670 {
1671 	struct netns_mctp *ns = &net->mctp;
1672 
1673 	INIT_LIST_HEAD(&ns->routes);
1674 	INIT_HLIST_HEAD(&ns->binds);
1675 	mutex_init(&ns->bind_lock);
1676 	INIT_HLIST_HEAD(&ns->keys);
1677 	spin_lock_init(&ns->keys_lock);
1678 	WARN_ON(mctp_default_net_set(net, MCTP_INITIAL_DEFAULT_NET));
1679 	return 0;
1680 }
1681 
1682 static void __net_exit mctp_routes_net_exit(struct net *net)
1683 {
1684 	struct mctp_route *rt;
1685 
1686 	rcu_read_lock();
1687 	list_for_each_entry_rcu(rt, &net->mctp.routes, list)
1688 		mctp_route_release(rt);
1689 	rcu_read_unlock();
1690 }
1691 
1692 static struct pernet_operations mctp_net_ops = {
1693 	.init = mctp_routes_net_init,
1694 	.exit = mctp_routes_net_exit,
1695 };
1696 
1697 static const struct rtnl_msg_handler mctp_route_rtnl_msg_handlers[] = {
1698 	{THIS_MODULE, PF_MCTP, RTM_NEWROUTE, mctp_newroute, NULL, 0},
1699 	{THIS_MODULE, PF_MCTP, RTM_DELROUTE, mctp_delroute, NULL, 0},
1700 	{THIS_MODULE, PF_MCTP, RTM_GETROUTE, NULL, mctp_dump_rtinfo, 0},
1701 };
1702 
1703 int __init mctp_routes_init(void)
1704 {
1705 	int err;
1706 
1707 	dev_add_pack(&mctp_packet_type);
1708 
1709 	err = register_pernet_subsys(&mctp_net_ops);
1710 	if (err)
1711 		goto err_pernet;
1712 
1713 	err = rtnl_register_many(mctp_route_rtnl_msg_handlers);
1714 	if (err)
1715 		goto err_rtnl;
1716 
1717 	return 0;
1718 
1719 err_rtnl:
1720 	unregister_pernet_subsys(&mctp_net_ops);
1721 err_pernet:
1722 	dev_remove_pack(&mctp_packet_type);
1723 	return err;
1724 }
1725 
1726 void mctp_routes_exit(void)
1727 {
1728 	rtnl_unregister_many(mctp_route_rtnl_msg_handlers);
1729 	unregister_pernet_subsys(&mctp_net_ops);
1730 	dev_remove_pack(&mctp_packet_type);
1731 }
1732 
1733 #if IS_ENABLED(CONFIG_MCTP_TEST)
1734 #include "test/route-test.c"
1735 #endif
1736