GNU Linux-libre 4.14.290-gnu1
[releases.git] / net / can / af_can.c
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, S_IRUGO);
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
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
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
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
124 static inline void can_put_proto(const struct can_proto *cp)
125 {
126         module_put(cp->prot->owner);
127 }
128
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  */
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
325 static struct 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 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  */
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  */
384 static struct hlist_head *find_rcv_list(canid_t *can_id, canid_t *mask,
385                                         struct 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  */
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 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  */
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  */
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 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
613 static inline void deliver(struct sk_buff *skb, struct receiver *r)
614 {
615         r->func(skb, r->data);
616         r->matches++;
617 }
618
619 static int can_rcv_filter(struct 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
684 static void can_receive(struct sk_buff *skb, struct net_device *dev)
685 {
686         struct 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
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                 pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d\n",
727                              dev->type, skb->len);
728                 goto free_skb;
729         }
730
731         /* This check is made separately since cfd->len would be uninitialized if skb->len = 0. */
732         if (unlikely(cfd->len > CAN_MAX_DLEN)) {
733                 pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d, datalen %d\n",
734                              dev->type, skb->len, cfd->len);
735                 goto free_skb;
736         }
737
738         can_receive(skb, dev);
739         return NET_RX_SUCCESS;
740
741 free_skb:
742         kfree_skb(skb);
743         return NET_RX_DROP;
744 }
745
746 static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
747                    struct packet_type *pt, struct net_device *orig_dev)
748 {
749         struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
750
751         if (unlikely(dev->type != ARPHRD_CAN || skb->len != CANFD_MTU)) {
752                 pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d\n",
753                              dev->type, skb->len);
754                 goto free_skb;
755         }
756
757         /* This check is made separately since cfd->len would be uninitialized if skb->len = 0. */
758         if (unlikely(cfd->len > CANFD_MAX_DLEN)) {
759                 pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d, datalen %d\n",
760                              dev->type, skb->len, cfd->len);
761                 goto free_skb;
762         }
763
764         can_receive(skb, dev);
765         return NET_RX_SUCCESS;
766
767 free_skb:
768         kfree_skb(skb);
769         return NET_RX_DROP;
770 }
771
772 /*
773  * af_can protocol functions
774  */
775
776 /**
777  * can_proto_register - register CAN transport protocol
778  * @cp: pointer to CAN protocol structure
779  *
780  * Return:
781  *  0 on success
782  *  -EINVAL invalid (out of range) protocol number
783  *  -EBUSY  protocol already in use
784  *  -ENOBUF if proto_register() fails
785  */
786 int can_proto_register(const struct can_proto *cp)
787 {
788         int proto = cp->protocol;
789         int err = 0;
790
791         if (proto < 0 || proto >= CAN_NPROTO) {
792                 pr_err("can: protocol number %d out of range\n", proto);
793                 return -EINVAL;
794         }
795
796         err = proto_register(cp->prot, 0);
797         if (err < 0)
798                 return err;
799
800         mutex_lock(&proto_tab_lock);
801
802         if (rcu_access_pointer(proto_tab[proto])) {
803                 pr_err("can: protocol %d already registered\n", proto);
804                 err = -EBUSY;
805         } else
806                 RCU_INIT_POINTER(proto_tab[proto], cp);
807
808         mutex_unlock(&proto_tab_lock);
809
810         if (err < 0)
811                 proto_unregister(cp->prot);
812
813         return err;
814 }
815 EXPORT_SYMBOL(can_proto_register);
816
817 /**
818  * can_proto_unregister - unregister CAN transport protocol
819  * @cp: pointer to CAN protocol structure
820  */
821 void can_proto_unregister(const struct can_proto *cp)
822 {
823         int proto = cp->protocol;
824
825         mutex_lock(&proto_tab_lock);
826         BUG_ON(rcu_access_pointer(proto_tab[proto]) != cp);
827         RCU_INIT_POINTER(proto_tab[proto], NULL);
828         mutex_unlock(&proto_tab_lock);
829
830         synchronize_rcu();
831
832         proto_unregister(cp->prot);
833 }
834 EXPORT_SYMBOL(can_proto_unregister);
835
836 /*
837  * af_can notifier to create/remove CAN netdevice specific structs
838  */
839 static int can_notifier(struct notifier_block *nb, unsigned long msg,
840                         void *ptr)
841 {
842         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
843         struct dev_rcv_lists *d;
844
845         if (dev->type != ARPHRD_CAN)
846                 return NOTIFY_DONE;
847
848         switch (msg) {
849
850         case NETDEV_REGISTER:
851
852                 /* create new dev_rcv_lists for this device */
853                 d = kzalloc(sizeof(*d), GFP_KERNEL);
854                 if (!d)
855                         return NOTIFY_DONE;
856                 BUG_ON(dev->ml_priv);
857                 dev->ml_priv = d;
858
859                 break;
860
861         case NETDEV_UNREGISTER:
862                 spin_lock(&dev_net(dev)->can.can_rcvlists_lock);
863
864                 d = dev->ml_priv;
865                 if (d) {
866                         if (d->entries)
867                                 d->remove_on_zero_entries = 1;
868                         else {
869                                 kfree(d);
870                                 dev->ml_priv = NULL;
871                         }
872                 } else
873                         pr_err("can: notifier: receive list not found for dev "
874                                "%s\n", dev->name);
875
876                 spin_unlock(&dev_net(dev)->can.can_rcvlists_lock);
877
878                 break;
879         }
880
881         return NOTIFY_DONE;
882 }
883
884 static int can_pernet_init(struct net *net)
885 {
886         spin_lock_init(&net->can.can_rcvlists_lock);
887         net->can.can_rx_alldev_list =
888                 kzalloc(sizeof(struct dev_rcv_lists), GFP_KERNEL);
889         if (!net->can.can_rx_alldev_list)
890                 goto out;
891         net->can.can_stats = kzalloc(sizeof(struct s_stats), GFP_KERNEL);
892         if (!net->can.can_stats)
893                 goto out_free_alldev_list;
894         net->can.can_pstats = kzalloc(sizeof(struct s_pstats), GFP_KERNEL);
895         if (!net->can.can_pstats)
896                 goto out_free_can_stats;
897
898         if (IS_ENABLED(CONFIG_PROC_FS)) {
899                 /* the statistics are updated every second (timer triggered) */
900                 if (stats_timer) {
901                         setup_timer(&net->can.can_stattimer, can_stat_update,
902                                     (unsigned long)net);
903                         mod_timer(&net->can.can_stattimer,
904                                   round_jiffies(jiffies + HZ));
905                 }
906                 net->can.can_stats->jiffies_init = jiffies;
907                 can_init_proc(net);
908         }
909
910         return 0;
911
912  out_free_can_stats:
913         kfree(net->can.can_stats);
914  out_free_alldev_list:
915         kfree(net->can.can_rx_alldev_list);
916  out:
917         return -ENOMEM;
918 }
919
920 static void can_pernet_exit(struct net *net)
921 {
922         struct net_device *dev;
923
924         if (IS_ENABLED(CONFIG_PROC_FS)) {
925                 can_remove_proc(net);
926                 if (stats_timer)
927                         del_timer_sync(&net->can.can_stattimer);
928         }
929
930         /* remove created dev_rcv_lists from still registered CAN devices */
931         rcu_read_lock();
932         for_each_netdev_rcu(net, dev) {
933                 if (dev->type == ARPHRD_CAN && dev->ml_priv) {
934                         struct dev_rcv_lists *d = dev->ml_priv;
935
936                         BUG_ON(d->entries);
937                         kfree(d);
938                         dev->ml_priv = NULL;
939                 }
940         }
941         rcu_read_unlock();
942
943         kfree(net->can.can_rx_alldev_list);
944         kfree(net->can.can_stats);
945         kfree(net->can.can_pstats);
946 }
947
948 /*
949  * af_can module init/exit functions
950  */
951
952 static struct packet_type can_packet __read_mostly = {
953         .type = cpu_to_be16(ETH_P_CAN),
954         .func = can_rcv,
955 };
956
957 static struct packet_type canfd_packet __read_mostly = {
958         .type = cpu_to_be16(ETH_P_CANFD),
959         .func = canfd_rcv,
960 };
961
962 static const struct net_proto_family can_family_ops = {
963         .family = PF_CAN,
964         .create = can_create,
965         .owner  = THIS_MODULE,
966 };
967
968 /* notifier block for netdevice event */
969 static struct notifier_block can_netdev_notifier __read_mostly = {
970         .notifier_call = can_notifier,
971 };
972
973 static struct pernet_operations can_pernet_ops __read_mostly = {
974         .init = can_pernet_init,
975         .exit = can_pernet_exit,
976 };
977
978 static __init int can_init(void)
979 {
980         int err;
981
982         /* check for correct padding to be able to use the structs similarly */
983         BUILD_BUG_ON(offsetof(struct can_frame, can_dlc) !=
984                      offsetof(struct canfd_frame, len) ||
985                      offsetof(struct can_frame, data) !=
986                      offsetof(struct canfd_frame, data));
987
988         pr_info("can: controller area network core (" CAN_VERSION_STRING ")\n");
989
990         rcv_cache = kmem_cache_create("can_receiver", sizeof(struct receiver),
991                                       0, 0, NULL);
992         if (!rcv_cache)
993                 return -ENOMEM;
994
995         err = register_pernet_subsys(&can_pernet_ops);
996         if (err)
997                 goto out_pernet;
998
999         /* protocol register */
1000         err = sock_register(&can_family_ops);
1001         if (err)
1002                 goto out_sock;
1003         err = register_netdevice_notifier(&can_netdev_notifier);
1004         if (err)
1005                 goto out_notifier;
1006
1007         dev_add_pack(&can_packet);
1008         dev_add_pack(&canfd_packet);
1009
1010         return 0;
1011
1012 out_notifier:
1013         sock_unregister(PF_CAN);
1014 out_sock:
1015         unregister_pernet_subsys(&can_pernet_ops);
1016 out_pernet:
1017         kmem_cache_destroy(rcv_cache);
1018
1019         return err;
1020 }
1021
1022 static __exit void can_exit(void)
1023 {
1024         /* protocol unregister */
1025         dev_remove_pack(&canfd_packet);
1026         dev_remove_pack(&can_packet);
1027         unregister_netdevice_notifier(&can_netdev_notifier);
1028         sock_unregister(PF_CAN);
1029
1030         unregister_pernet_subsys(&can_pernet_ops);
1031
1032         rcu_barrier(); /* Wait for completion of call_rcu()'s */
1033
1034         kmem_cache_destroy(rcv_cache);
1035 }
1036
1037 module_init(can_init);
1038 module_exit(can_exit);