• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * af_can.c - Protocol family CAN core module
3  *            (used by different CAN protocol modules)
4  *
5  * Copyright (c) 2002-2017 Volkswagen Group Electronic Research
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of Volkswagen nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * Alternatively, provided that this notice is retained in full, this
21  * software may be distributed under the terms of the GNU General
22  * Public License ("GPL") version 2, in which case the provisions of the
23  * GPL apply INSTEAD OF those given above.
24  *
25  * The provided data structures and external interfaces from this code
26  * are not restricted to be used by modules with a GPL compatible license.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
39  * DAMAGE.
40  *
41  */
42 
43 #include <linux/module.h>
44 #include <linux/stddef.h>
45 #include <linux/init.h>
46 #include <linux/kmod.h>
47 #include <linux/slab.h>
48 #include <linux/list.h>
49 #include <linux/spinlock.h>
50 #include <linux/rcupdate.h>
51 #include <linux/uaccess.h>
52 #include <linux/net.h>
53 #include <linux/netdevice.h>
54 #include <linux/socket.h>
55 #include <linux/if_ether.h>
56 #include <linux/if_arp.h>
57 #include <linux/skbuff.h>
58 #include <linux/can.h>
59 #include <linux/can/core.h>
60 #include <linux/can/skb.h>
61 #include <linux/ratelimit.h>
62 #include <net/net_namespace.h>
63 #include <net/sock.h>
64 
65 #include "af_can.h"
66 
67 MODULE_DESCRIPTION("Controller Area Network PF_CAN core");
68 MODULE_LICENSE("Dual BSD/GPL");
69 MODULE_AUTHOR("Urs Thuermann <urs.thuermann@volkswagen.de>, "
70 	      "Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
71 
72 MODULE_ALIAS_NETPROTO(PF_CAN);
73 
74 static int stats_timer __read_mostly = 1;
75 module_param(stats_timer, int, 0444);
76 MODULE_PARM_DESC(stats_timer, "enable timer for statistics (default:on)");
77 
78 static struct kmem_cache *rcv_cache __read_mostly;
79 
80 /* table of registered CAN protocols */
81 static const struct can_proto __rcu *proto_tab[CAN_NPROTO] __read_mostly;
82 static DEFINE_MUTEX(proto_tab_lock);
83 
84 static atomic_t skbcounter = ATOMIC_INIT(0);
85 
86 /*
87  * af_can socket functions
88  */
89 
can_ioctl(struct socket * sock,unsigned int cmd,unsigned long arg)90 int can_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
91 {
92 	struct sock *sk = sock->sk;
93 
94 	switch (cmd) {
95 
96 	case SIOCGSTAMP:
97 		return sock_get_timestamp(sk, (struct timeval __user *)arg);
98 
99 	default:
100 		return -ENOIOCTLCMD;
101 	}
102 }
103 EXPORT_SYMBOL(can_ioctl);
104 
can_sock_destruct(struct sock * sk)105 static void can_sock_destruct(struct sock *sk)
106 {
107 	skb_queue_purge(&sk->sk_receive_queue);
108 	skb_queue_purge(&sk->sk_error_queue);
109 }
110 
can_get_proto(int protocol)111 static const struct can_proto *can_get_proto(int protocol)
112 {
113 	const struct can_proto *cp;
114 
115 	rcu_read_lock();
116 	cp = rcu_dereference(proto_tab[protocol]);
117 	if (cp && !try_module_get(cp->prot->owner))
118 		cp = NULL;
119 	rcu_read_unlock();
120 
121 	return cp;
122 }
123 
can_put_proto(const struct can_proto * cp)124 static inline void can_put_proto(const struct can_proto *cp)
125 {
126 	module_put(cp->prot->owner);
127 }
128 
can_create(struct net * net,struct socket * sock,int protocol,int kern)129 static int can_create(struct net *net, struct socket *sock, int protocol,
130 		      int kern)
131 {
132 	struct sock *sk;
133 	const struct can_proto *cp;
134 	int err = 0;
135 
136 	sock->state = SS_UNCONNECTED;
137 
138 	if (protocol < 0 || protocol >= CAN_NPROTO)
139 		return -EINVAL;
140 
141 	cp = can_get_proto(protocol);
142 
143 #ifdef CONFIG_MODULES
144 	if (!cp) {
145 		/* try to load protocol module if kernel is modular */
146 
147 		err = request_module("can-proto-%d", protocol);
148 
149 		/*
150 		 * In case of error we only print a message but don't
151 		 * return the error code immediately.  Below we will
152 		 * return -EPROTONOSUPPORT
153 		 */
154 		if (err)
155 			printk_ratelimited(KERN_ERR "can: request_module "
156 			       "(can-proto-%d) failed.\n", protocol);
157 
158 		cp = can_get_proto(protocol);
159 	}
160 #endif
161 
162 	/* check for available protocol and correct usage */
163 
164 	if (!cp)
165 		return -EPROTONOSUPPORT;
166 
167 	if (cp->type != sock->type) {
168 		err = -EPROTOTYPE;
169 		goto errout;
170 	}
171 
172 	sock->ops = cp->ops;
173 
174 	sk = sk_alloc(net, PF_CAN, GFP_KERNEL, cp->prot, kern);
175 	if (!sk) {
176 		err = -ENOMEM;
177 		goto errout;
178 	}
179 
180 	sock_init_data(sock, sk);
181 	sk->sk_destruct = can_sock_destruct;
182 
183 	if (sk->sk_prot->init)
184 		err = sk->sk_prot->init(sk);
185 
186 	if (err) {
187 		/* release sk on errors */
188 		sock_orphan(sk);
189 		sock_put(sk);
190 	}
191 
192  errout:
193 	can_put_proto(cp);
194 	return err;
195 }
196 
197 /*
198  * af_can tx path
199  */
200 
201 /**
202  * can_send - transmit a CAN frame (optional with local loopback)
203  * @skb: pointer to socket buffer with CAN frame in data section
204  * @loop: loopback for listeners on local CAN sockets (recommended default!)
205  *
206  * Due to the loopback this routine must not be called from hardirq context.
207  *
208  * Return:
209  *  0 on success
210  *  -ENETDOWN when the selected interface is down
211  *  -ENOBUFS on full driver queue (see net_xmit_errno())
212  *  -ENOMEM when local loopback failed at calling skb_clone()
213  *  -EPERM when trying to send on a non-CAN interface
214  *  -EMSGSIZE CAN frame size is bigger than CAN interface MTU
215  *  -EINVAL when the skb->data does not contain a valid CAN frame
216  */
can_send(struct sk_buff * skb,int loop)217 int can_send(struct sk_buff *skb, int loop)
218 {
219 	struct sk_buff *newskb = NULL;
220 	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
221 	struct s_stats *can_stats = dev_net(skb->dev)->can.can_stats;
222 	int err = -EINVAL;
223 
224 	if (skb->len == CAN_MTU) {
225 		skb->protocol = htons(ETH_P_CAN);
226 		if (unlikely(cfd->len > CAN_MAX_DLEN))
227 			goto inval_skb;
228 	} else if (skb->len == CANFD_MTU) {
229 		skb->protocol = htons(ETH_P_CANFD);
230 		if (unlikely(cfd->len > CANFD_MAX_DLEN))
231 			goto inval_skb;
232 	} else
233 		goto inval_skb;
234 
235 	/*
236 	 * Make sure the CAN frame can pass the selected CAN netdevice.
237 	 * As structs can_frame and canfd_frame are similar, we can provide
238 	 * CAN FD frames to legacy CAN drivers as long as the length is <= 8
239 	 */
240 	if (unlikely(skb->len > skb->dev->mtu && cfd->len > CAN_MAX_DLEN)) {
241 		err = -EMSGSIZE;
242 		goto inval_skb;
243 	}
244 
245 	if (unlikely(skb->dev->type != ARPHRD_CAN)) {
246 		err = -EPERM;
247 		goto inval_skb;
248 	}
249 
250 	if (unlikely(!(skb->dev->flags & IFF_UP))) {
251 		err = -ENETDOWN;
252 		goto inval_skb;
253 	}
254 
255 	skb->ip_summed = CHECKSUM_UNNECESSARY;
256 
257 	skb_reset_mac_header(skb);
258 	skb_reset_network_header(skb);
259 	skb_reset_transport_header(skb);
260 
261 	if (loop) {
262 		/* local loopback of sent CAN frames */
263 
264 		/* indication for the CAN driver: do loopback */
265 		skb->pkt_type = PACKET_LOOPBACK;
266 
267 		/*
268 		 * The reference to the originating sock may be required
269 		 * by the receiving socket to check whether the frame is
270 		 * its own. Example: can_raw sockopt CAN_RAW_RECV_OWN_MSGS
271 		 * Therefore we have to ensure that skb->sk remains the
272 		 * reference to the originating sock by restoring skb->sk
273 		 * after each skb_clone() or skb_orphan() usage.
274 		 */
275 
276 		if (!(skb->dev->flags & IFF_ECHO)) {
277 			/*
278 			 * If the interface is not capable to do loopback
279 			 * itself, we do it here.
280 			 */
281 			newskb = skb_clone(skb, GFP_ATOMIC);
282 			if (!newskb) {
283 				kfree_skb(skb);
284 				return -ENOMEM;
285 			}
286 
287 			can_skb_set_owner(newskb, skb->sk);
288 			newskb->ip_summed = CHECKSUM_UNNECESSARY;
289 			newskb->pkt_type = PACKET_BROADCAST;
290 		}
291 	} else {
292 		/* indication for the CAN driver: no loopback required */
293 		skb->pkt_type = PACKET_HOST;
294 	}
295 
296 	/* send to netdevice */
297 	err = dev_queue_xmit(skb);
298 	if (err > 0)
299 		err = net_xmit_errno(err);
300 
301 	if (err) {
302 		kfree_skb(newskb);
303 		return err;
304 	}
305 
306 	if (newskb)
307 		netif_rx_ni(newskb);
308 
309 	/* update statistics */
310 	can_stats->tx_frames++;
311 	can_stats->tx_frames_delta++;
312 
313 	return 0;
314 
315 inval_skb:
316 	kfree_skb(skb);
317 	return err;
318 }
319 EXPORT_SYMBOL(can_send);
320 
321 /*
322  * af_can rx path
323  */
324 
find_dev_rcv_lists(struct net * net,struct net_device * dev)325 static struct can_dev_rcv_lists *find_dev_rcv_lists(struct net *net,
326 						struct net_device *dev)
327 {
328 	if (!dev)
329 		return net->can.can_rx_alldev_list;
330 	else
331 		return (struct can_dev_rcv_lists *)dev->ml_priv;
332 }
333 
334 /**
335  * effhash - hash function for 29 bit CAN identifier reduction
336  * @can_id: 29 bit CAN identifier
337  *
338  * Description:
339  *  To reduce the linear traversal in one linked list of _single_ EFF CAN
340  *  frame subscriptions the 29 bit identifier is mapped to 10 bits.
341  *  (see CAN_EFF_RCV_HASH_BITS definition)
342  *
343  * Return:
344  *  Hash value from 0x000 - 0x3FF ( enforced by CAN_EFF_RCV_HASH_BITS mask )
345  */
effhash(canid_t can_id)346 static unsigned int effhash(canid_t can_id)
347 {
348 	unsigned int hash;
349 
350 	hash = can_id;
351 	hash ^= can_id >> CAN_EFF_RCV_HASH_BITS;
352 	hash ^= can_id >> (2 * CAN_EFF_RCV_HASH_BITS);
353 
354 	return hash & ((1 << CAN_EFF_RCV_HASH_BITS) - 1);
355 }
356 
357 /**
358  * find_rcv_list - determine optimal filterlist inside device filter struct
359  * @can_id: pointer to CAN identifier of a given can_filter
360  * @mask: pointer to CAN mask of a given can_filter
361  * @d: pointer to the device filter struct
362  *
363  * Description:
364  *  Returns the optimal filterlist to reduce the filter handling in the
365  *  receive path. This function is called by service functions that need
366  *  to register or unregister a can_filter in the filter lists.
367  *
368  *  A filter matches in general, when
369  *
370  *          <received_can_id> & mask == can_id & mask
371  *
372  *  so every bit set in the mask (even CAN_EFF_FLAG, CAN_RTR_FLAG) describe
373  *  relevant bits for the filter.
374  *
375  *  The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
376  *  filter for error messages (CAN_ERR_FLAG bit set in mask). For error msg
377  *  frames there is a special filterlist and a special rx path filter handling.
378  *
379  * Return:
380  *  Pointer to optimal filterlist for the given can_id/mask pair.
381  *  Constistency checked mask.
382  *  Reduced can_id to have a preprocessed filter compare value.
383  */
find_rcv_list(canid_t * can_id,canid_t * mask,struct can_dev_rcv_lists * d)384 static struct hlist_head *find_rcv_list(canid_t *can_id, canid_t *mask,
385 					struct can_dev_rcv_lists *d)
386 {
387 	canid_t inv = *can_id & CAN_INV_FILTER; /* save flag before masking */
388 
389 	/* filter for error message frames in extra filterlist */
390 	if (*mask & CAN_ERR_FLAG) {
391 		/* clear CAN_ERR_FLAG in filter entry */
392 		*mask &= CAN_ERR_MASK;
393 		return &d->rx[RX_ERR];
394 	}
395 
396 	/* with cleared CAN_ERR_FLAG we have a simple mask/value filterpair */
397 
398 #define CAN_EFF_RTR_FLAGS (CAN_EFF_FLAG | CAN_RTR_FLAG)
399 
400 	/* ensure valid values in can_mask for 'SFF only' frame filtering */
401 	if ((*mask & CAN_EFF_FLAG) && !(*can_id & CAN_EFF_FLAG))
402 		*mask &= (CAN_SFF_MASK | CAN_EFF_RTR_FLAGS);
403 
404 	/* reduce condition testing at receive time */
405 	*can_id &= *mask;
406 
407 	/* inverse can_id/can_mask filter */
408 	if (inv)
409 		return &d->rx[RX_INV];
410 
411 	/* mask == 0 => no condition testing at receive time */
412 	if (!(*mask))
413 		return &d->rx[RX_ALL];
414 
415 	/* extra filterlists for the subscription of a single non-RTR can_id */
416 	if (((*mask & CAN_EFF_RTR_FLAGS) == CAN_EFF_RTR_FLAGS) &&
417 	    !(*can_id & CAN_RTR_FLAG)) {
418 
419 		if (*can_id & CAN_EFF_FLAG) {
420 			if (*mask == (CAN_EFF_MASK | CAN_EFF_RTR_FLAGS))
421 				return &d->rx_eff[effhash(*can_id)];
422 		} else {
423 			if (*mask == (CAN_SFF_MASK | CAN_EFF_RTR_FLAGS))
424 				return &d->rx_sff[*can_id];
425 		}
426 	}
427 
428 	/* default: filter via can_id/can_mask */
429 	return &d->rx[RX_FIL];
430 }
431 
432 /**
433  * can_rx_register - subscribe CAN frames from a specific interface
434  * @dev: pointer to netdevice (NULL => subcribe from 'all' CAN devices list)
435  * @can_id: CAN identifier (see description)
436  * @mask: CAN mask (see description)
437  * @func: callback function on filter match
438  * @data: returned parameter for callback function
439  * @ident: string for calling module identification
440  * @sk: socket pointer (might be NULL)
441  *
442  * Description:
443  *  Invokes the callback function with the received sk_buff and the given
444  *  parameter 'data' on a matching receive filter. A filter matches, when
445  *
446  *          <received_can_id> & mask == can_id & mask
447  *
448  *  The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
449  *  filter for error message frames (CAN_ERR_FLAG bit set in mask).
450  *
451  *  The provided pointer to the sk_buff is guaranteed to be valid as long as
452  *  the callback function is running. The callback function must *not* free
453  *  the given sk_buff while processing it's task. When the given sk_buff is
454  *  needed after the end of the callback function it must be cloned inside
455  *  the callback function with skb_clone().
456  *
457  * Return:
458  *  0 on success
459  *  -ENOMEM on missing cache mem to create subscription entry
460  *  -ENODEV unknown device
461  */
can_rx_register(struct net * net,struct net_device * dev,canid_t can_id,canid_t mask,void (* func)(struct sk_buff *,void *),void * data,char * ident,struct sock * sk)462 int can_rx_register(struct net *net, struct net_device *dev, canid_t can_id,
463 		    canid_t mask, void (*func)(struct sk_buff *, void *),
464 		    void *data, char *ident, struct sock *sk)
465 {
466 	struct receiver *r;
467 	struct hlist_head *rl;
468 	struct can_dev_rcv_lists *d;
469 	struct s_pstats *can_pstats = net->can.can_pstats;
470 	int err = 0;
471 
472 	/* insert new receiver  (dev,canid,mask) -> (func,data) */
473 
474 	if (dev && dev->type != ARPHRD_CAN)
475 		return -ENODEV;
476 
477 	if (dev && !net_eq(net, dev_net(dev)))
478 		return -ENODEV;
479 
480 	r = kmem_cache_alloc(rcv_cache, GFP_KERNEL);
481 	if (!r)
482 		return -ENOMEM;
483 
484 	spin_lock(&net->can.can_rcvlists_lock);
485 
486 	d = find_dev_rcv_lists(net, dev);
487 	if (d) {
488 		rl = find_rcv_list(&can_id, &mask, d);
489 
490 		r->can_id  = can_id;
491 		r->mask    = mask;
492 		r->matches = 0;
493 		r->func    = func;
494 		r->data    = data;
495 		r->ident   = ident;
496 		r->sk      = sk;
497 
498 		hlist_add_head_rcu(&r->list, rl);
499 		d->entries++;
500 
501 		can_pstats->rcv_entries++;
502 		if (can_pstats->rcv_entries_max < can_pstats->rcv_entries)
503 			can_pstats->rcv_entries_max = can_pstats->rcv_entries;
504 	} else {
505 		kmem_cache_free(rcv_cache, r);
506 		err = -ENODEV;
507 	}
508 
509 	spin_unlock(&net->can.can_rcvlists_lock);
510 
511 	return err;
512 }
513 EXPORT_SYMBOL(can_rx_register);
514 
515 /*
516  * can_rx_delete_receiver - rcu callback for single receiver entry removal
517  */
can_rx_delete_receiver(struct rcu_head * rp)518 static void can_rx_delete_receiver(struct rcu_head *rp)
519 {
520 	struct receiver *r = container_of(rp, struct receiver, rcu);
521 	struct sock *sk = r->sk;
522 
523 	kmem_cache_free(rcv_cache, r);
524 	if (sk)
525 		sock_put(sk);
526 }
527 
528 /**
529  * can_rx_unregister - unsubscribe CAN frames from a specific interface
530  * @dev: pointer to netdevice (NULL => unsubscribe from 'all' CAN devices list)
531  * @can_id: CAN identifier
532  * @mask: CAN mask
533  * @func: callback function on filter match
534  * @data: returned parameter for callback function
535  *
536  * Description:
537  *  Removes subscription entry depending on given (subscription) values.
538  */
can_rx_unregister(struct net * net,struct net_device * dev,canid_t can_id,canid_t mask,void (* func)(struct sk_buff *,void *),void * data)539 void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
540 		       canid_t mask, void (*func)(struct sk_buff *, void *),
541 		       void *data)
542 {
543 	struct receiver *r = NULL;
544 	struct hlist_head *rl;
545 	struct s_pstats *can_pstats = net->can.can_pstats;
546 	struct can_dev_rcv_lists *d;
547 
548 	if (dev && dev->type != ARPHRD_CAN)
549 		return;
550 
551 	if (dev && !net_eq(net, dev_net(dev)))
552 		return;
553 
554 	spin_lock(&net->can.can_rcvlists_lock);
555 
556 	d = find_dev_rcv_lists(net, dev);
557 	if (!d) {
558 		pr_err("BUG: receive list not found for "
559 		       "dev %s, id %03X, mask %03X\n",
560 		       DNAME(dev), can_id, mask);
561 		goto out;
562 	}
563 
564 	rl = find_rcv_list(&can_id, &mask, d);
565 
566 	/*
567 	 * Search the receiver list for the item to delete.  This should
568 	 * exist, since no receiver may be unregistered that hasn't
569 	 * been registered before.
570 	 */
571 
572 	hlist_for_each_entry_rcu(r, rl, list) {
573 		if (r->can_id == can_id && r->mask == mask &&
574 		    r->func == func && r->data == data)
575 			break;
576 	}
577 
578 	/*
579 	 * Check for bugs in CAN protocol implementations using af_can.c:
580 	 * 'r' will be NULL if no matching list item was found for removal.
581 	 */
582 
583 	if (!r) {
584 		WARN(1, "BUG: receive list entry not found for dev %s, "
585 		     "id %03X, mask %03X\n", DNAME(dev), can_id, mask);
586 		goto out;
587 	}
588 
589 	hlist_del_rcu(&r->list);
590 	d->entries--;
591 
592 	if (can_pstats->rcv_entries > 0)
593 		can_pstats->rcv_entries--;
594 
595 	/* remove device structure requested by NETDEV_UNREGISTER */
596 	if (d->remove_on_zero_entries && !d->entries) {
597 		kfree(d);
598 		dev->ml_priv = NULL;
599 	}
600 
601  out:
602 	spin_unlock(&net->can.can_rcvlists_lock);
603 
604 	/* schedule the receiver item for deletion */
605 	if (r) {
606 		if (r->sk)
607 			sock_hold(r->sk);
608 		call_rcu(&r->rcu, can_rx_delete_receiver);
609 	}
610 }
611 EXPORT_SYMBOL(can_rx_unregister);
612 
deliver(struct sk_buff * skb,struct receiver * r)613 static inline void deliver(struct sk_buff *skb, struct receiver *r)
614 {
615 	r->func(skb, r->data);
616 	r->matches++;
617 }
618 
can_rcv_filter(struct can_dev_rcv_lists * d,struct sk_buff * skb)619 static int can_rcv_filter(struct can_dev_rcv_lists *d, struct sk_buff *skb)
620 {
621 	struct receiver *r;
622 	int matches = 0;
623 	struct can_frame *cf = (struct can_frame *)skb->data;
624 	canid_t can_id = cf->can_id;
625 
626 	if (d->entries == 0)
627 		return 0;
628 
629 	if (can_id & CAN_ERR_FLAG) {
630 		/* check for error message frame entries only */
631 		hlist_for_each_entry_rcu(r, &d->rx[RX_ERR], list) {
632 			if (can_id & r->mask) {
633 				deliver(skb, r);
634 				matches++;
635 			}
636 		}
637 		return matches;
638 	}
639 
640 	/* check for unfiltered entries */
641 	hlist_for_each_entry_rcu(r, &d->rx[RX_ALL], list) {
642 		deliver(skb, r);
643 		matches++;
644 	}
645 
646 	/* check for can_id/mask entries */
647 	hlist_for_each_entry_rcu(r, &d->rx[RX_FIL], list) {
648 		if ((can_id & r->mask) == r->can_id) {
649 			deliver(skb, r);
650 			matches++;
651 		}
652 	}
653 
654 	/* check for inverted can_id/mask entries */
655 	hlist_for_each_entry_rcu(r, &d->rx[RX_INV], list) {
656 		if ((can_id & r->mask) != r->can_id) {
657 			deliver(skb, r);
658 			matches++;
659 		}
660 	}
661 
662 	/* check filterlists for single non-RTR can_ids */
663 	if (can_id & CAN_RTR_FLAG)
664 		return matches;
665 
666 	if (can_id & CAN_EFF_FLAG) {
667 		hlist_for_each_entry_rcu(r, &d->rx_eff[effhash(can_id)], list) {
668 			if (r->can_id == can_id) {
669 				deliver(skb, r);
670 				matches++;
671 			}
672 		}
673 	} else {
674 		can_id &= CAN_SFF_MASK;
675 		hlist_for_each_entry_rcu(r, &d->rx_sff[can_id], list) {
676 			deliver(skb, r);
677 			matches++;
678 		}
679 	}
680 
681 	return matches;
682 }
683 
can_receive(struct sk_buff * skb,struct net_device * dev)684 static void can_receive(struct sk_buff *skb, struct net_device *dev)
685 {
686 	struct can_dev_rcv_lists *d;
687 	struct net *net = dev_net(dev);
688 	struct s_stats *can_stats = net->can.can_stats;
689 	int matches;
690 
691 	/* update statistics */
692 	can_stats->rx_frames++;
693 	can_stats->rx_frames_delta++;
694 
695 	/* create non-zero unique skb identifier together with *skb */
696 	while (!(can_skb_prv(skb)->skbcnt))
697 		can_skb_prv(skb)->skbcnt = atomic_inc_return(&skbcounter);
698 
699 	rcu_read_lock();
700 
701 	/* deliver the packet to sockets listening on all devices */
702 	matches = can_rcv_filter(net->can.can_rx_alldev_list, skb);
703 
704 	/* find receive list for this device */
705 	d = find_dev_rcv_lists(net, dev);
706 	if (d)
707 		matches += can_rcv_filter(d, skb);
708 
709 	rcu_read_unlock();
710 
711 	/* consume the skbuff allocated by the netdevice driver */
712 	consume_skb(skb);
713 
714 	if (matches > 0) {
715 		can_stats->matches++;
716 		can_stats->matches_delta++;
717 	}
718 }
719 
can_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)720 static int can_rcv(struct sk_buff *skb, struct net_device *dev,
721 		   struct packet_type *pt, struct net_device *orig_dev)
722 {
723 	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
724 
725 	if (unlikely(dev->type != ARPHRD_CAN || skb->len != CAN_MTU ||
726 		     cfd->len > CAN_MAX_DLEN)) {
727 		pr_warn_once("PF_CAN: dropped non conform CAN skbuf: dev type %d, len %d, datalen %d\n",
728 			     dev->type, skb->len, cfd->len);
729 		kfree_skb(skb);
730 		return NET_RX_DROP;
731 	}
732 
733 	can_receive(skb, dev);
734 	return NET_RX_SUCCESS;
735 }
736 
canfd_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)737 static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
738 		   struct packet_type *pt, struct net_device *orig_dev)
739 {
740 	struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
741 
742 	if (unlikely(dev->type != ARPHRD_CAN || skb->len != CANFD_MTU ||
743 		     cfd->len > CANFD_MAX_DLEN)) {
744 		pr_warn_once("PF_CAN: dropped non conform CAN FD skbuf: dev type %d, len %d, datalen %d\n",
745 			     dev->type, skb->len, cfd->len);
746 		kfree_skb(skb);
747 		return NET_RX_DROP;
748 	}
749 
750 	can_receive(skb, dev);
751 	return NET_RX_SUCCESS;
752 }
753 
754 /*
755  * af_can protocol functions
756  */
757 
758 /**
759  * can_proto_register - register CAN transport protocol
760  * @cp: pointer to CAN protocol structure
761  *
762  * Return:
763  *  0 on success
764  *  -EINVAL invalid (out of range) protocol number
765  *  -EBUSY  protocol already in use
766  *  -ENOBUF if proto_register() fails
767  */
can_proto_register(const struct can_proto * cp)768 int can_proto_register(const struct can_proto *cp)
769 {
770 	int proto = cp->protocol;
771 	int err = 0;
772 
773 	if (proto < 0 || proto >= CAN_NPROTO) {
774 		pr_err("can: protocol number %d out of range\n", proto);
775 		return -EINVAL;
776 	}
777 
778 	err = proto_register(cp->prot, 0);
779 	if (err < 0)
780 		return err;
781 
782 	mutex_lock(&proto_tab_lock);
783 
784 	if (rcu_access_pointer(proto_tab[proto])) {
785 		pr_err("can: protocol %d already registered\n", proto);
786 		err = -EBUSY;
787 	} else
788 		RCU_INIT_POINTER(proto_tab[proto], cp);
789 
790 	mutex_unlock(&proto_tab_lock);
791 
792 	if (err < 0)
793 		proto_unregister(cp->prot);
794 
795 	return err;
796 }
797 EXPORT_SYMBOL(can_proto_register);
798 
799 /**
800  * can_proto_unregister - unregister CAN transport protocol
801  * @cp: pointer to CAN protocol structure
802  */
can_proto_unregister(const struct can_proto * cp)803 void can_proto_unregister(const struct can_proto *cp)
804 {
805 	int proto = cp->protocol;
806 
807 	mutex_lock(&proto_tab_lock);
808 	BUG_ON(rcu_access_pointer(proto_tab[proto]) != cp);
809 	RCU_INIT_POINTER(proto_tab[proto], NULL);
810 	mutex_unlock(&proto_tab_lock);
811 
812 	synchronize_rcu();
813 
814 	proto_unregister(cp->prot);
815 }
816 EXPORT_SYMBOL(can_proto_unregister);
817 
818 /*
819  * af_can notifier to create/remove CAN netdevice specific structs
820  */
can_notifier(struct notifier_block * nb,unsigned long msg,void * ptr)821 static int can_notifier(struct notifier_block *nb, unsigned long msg,
822 			void *ptr)
823 {
824 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
825 	struct can_dev_rcv_lists *d;
826 
827 	if (dev->type != ARPHRD_CAN)
828 		return NOTIFY_DONE;
829 
830 	switch (msg) {
831 
832 	case NETDEV_REGISTER:
833 
834 		/* create new dev_rcv_lists for this device */
835 		d = kzalloc(sizeof(*d), GFP_KERNEL);
836 		if (!d)
837 			return NOTIFY_DONE;
838 		BUG_ON(dev->ml_priv);
839 		dev->ml_priv = d;
840 
841 		break;
842 
843 	case NETDEV_UNREGISTER:
844 		spin_lock(&dev_net(dev)->can.can_rcvlists_lock);
845 
846 		d = dev->ml_priv;
847 		if (d) {
848 			if (d->entries)
849 				d->remove_on_zero_entries = 1;
850 			else {
851 				kfree(d);
852 				dev->ml_priv = NULL;
853 			}
854 		} else
855 			pr_err("can: notifier: receive list not found for dev "
856 			       "%s\n", dev->name);
857 
858 		spin_unlock(&dev_net(dev)->can.can_rcvlists_lock);
859 
860 		break;
861 	}
862 
863 	return NOTIFY_DONE;
864 }
865 
can_pernet_init(struct net * net)866 static int can_pernet_init(struct net *net)
867 {
868 	spin_lock_init(&net->can.can_rcvlists_lock);
869 	net->can.can_rx_alldev_list =
870 		kzalloc(sizeof(struct can_dev_rcv_lists), GFP_KERNEL);
871 	if (!net->can.can_rx_alldev_list)
872 		goto out;
873 	net->can.can_stats = kzalloc(sizeof(struct s_stats), GFP_KERNEL);
874 	if (!net->can.can_stats)
875 		goto out_free_alldev_list;
876 	net->can.can_pstats = kzalloc(sizeof(struct s_pstats), GFP_KERNEL);
877 	if (!net->can.can_pstats)
878 		goto out_free_can_stats;
879 
880 	if (IS_ENABLED(CONFIG_PROC_FS)) {
881 		/* the statistics are updated every second (timer triggered) */
882 		if (stats_timer) {
883 			timer_setup(&net->can.can_stattimer, can_stat_update,
884 				    0);
885 			mod_timer(&net->can.can_stattimer,
886 				  round_jiffies(jiffies + HZ));
887 		}
888 		net->can.can_stats->jiffies_init = jiffies;
889 		can_init_proc(net);
890 	}
891 
892 	return 0;
893 
894  out_free_can_stats:
895 	kfree(net->can.can_stats);
896  out_free_alldev_list:
897 	kfree(net->can.can_rx_alldev_list);
898  out:
899 	return -ENOMEM;
900 }
901 
can_pernet_exit(struct net * net)902 static void can_pernet_exit(struct net *net)
903 {
904 	struct net_device *dev;
905 
906 	if (IS_ENABLED(CONFIG_PROC_FS)) {
907 		can_remove_proc(net);
908 		if (stats_timer)
909 			del_timer_sync(&net->can.can_stattimer);
910 	}
911 
912 	/* remove created dev_rcv_lists from still registered CAN devices */
913 	rcu_read_lock();
914 	for_each_netdev_rcu(net, dev) {
915 		if (dev->type == ARPHRD_CAN && dev->ml_priv) {
916 			struct can_dev_rcv_lists *d = dev->ml_priv;
917 
918 			BUG_ON(d->entries);
919 			kfree(d);
920 			dev->ml_priv = NULL;
921 		}
922 	}
923 	rcu_read_unlock();
924 
925 	kfree(net->can.can_rx_alldev_list);
926 	kfree(net->can.can_stats);
927 	kfree(net->can.can_pstats);
928 }
929 
930 /*
931  * af_can module init/exit functions
932  */
933 
934 static struct packet_type can_packet __read_mostly = {
935 	.type = cpu_to_be16(ETH_P_CAN),
936 	.func = can_rcv,
937 };
938 
939 static struct packet_type canfd_packet __read_mostly = {
940 	.type = cpu_to_be16(ETH_P_CANFD),
941 	.func = canfd_rcv,
942 };
943 
944 static const struct net_proto_family can_family_ops = {
945 	.family = PF_CAN,
946 	.create = can_create,
947 	.owner  = THIS_MODULE,
948 };
949 
950 /* notifier block for netdevice event */
951 static struct notifier_block can_netdev_notifier __read_mostly = {
952 	.notifier_call = can_notifier,
953 };
954 
955 static struct pernet_operations can_pernet_ops __read_mostly = {
956 	.init = can_pernet_init,
957 	.exit = can_pernet_exit,
958 };
959 
can_init(void)960 static __init int can_init(void)
961 {
962 	int err;
963 
964 	/* check for correct padding to be able to use the structs similarly */
965 	BUILD_BUG_ON(offsetof(struct can_frame, can_dlc) !=
966 		     offsetof(struct canfd_frame, len) ||
967 		     offsetof(struct can_frame, data) !=
968 		     offsetof(struct canfd_frame, data));
969 
970 	pr_info("can: controller area network core (" CAN_VERSION_STRING ")\n");
971 
972 	rcv_cache = kmem_cache_create("can_receiver", sizeof(struct receiver),
973 				      0, 0, NULL);
974 	if (!rcv_cache)
975 		return -ENOMEM;
976 
977 	err = register_pernet_subsys(&can_pernet_ops);
978 	if (err)
979 		goto out_pernet;
980 
981 	/* protocol register */
982 	err = sock_register(&can_family_ops);
983 	if (err)
984 		goto out_sock;
985 	err = register_netdevice_notifier(&can_netdev_notifier);
986 	if (err)
987 		goto out_notifier;
988 
989 	dev_add_pack(&can_packet);
990 	dev_add_pack(&canfd_packet);
991 
992 	return 0;
993 
994 out_notifier:
995 	sock_unregister(PF_CAN);
996 out_sock:
997 	unregister_pernet_subsys(&can_pernet_ops);
998 out_pernet:
999 	kmem_cache_destroy(rcv_cache);
1000 
1001 	return err;
1002 }
1003 
can_exit(void)1004 static __exit void can_exit(void)
1005 {
1006 	/* protocol unregister */
1007 	dev_remove_pack(&canfd_packet);
1008 	dev_remove_pack(&can_packet);
1009 	unregister_netdevice_notifier(&can_netdev_notifier);
1010 	sock_unregister(PF_CAN);
1011 
1012 	unregister_pernet_subsys(&can_pernet_ops);
1013 
1014 	rcu_barrier(); /* Wait for completion of call_rcu()'s */
1015 
1016 	kmem_cache_destroy(rcv_cache);
1017 }
1018 
1019 module_init(can_init);
1020 module_exit(can_exit);
1021