af_can.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. // SPDX-License-Identifier: (GPL-2.0 OR BSD-3-Clause)
  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. #include <linux/module.h>
  43. #include <linux/stddef.h>
  44. #include <linux/init.h>
  45. #include <linux/kmod.h>
  46. #include <linux/slab.h>
  47. #include <linux/list.h>
  48. #include <linux/spinlock.h>
  49. #include <linux/rcupdate.h>
  50. #include <linux/uaccess.h>
  51. #include <linux/net.h>
  52. #include <linux/netdevice.h>
  53. #include <linux/socket.h>
  54. #include <linux/if_ether.h>
  55. #include <linux/if_arp.h>
  56. #include <linux/skbuff.h>
  57. #include <linux/can.h>
  58. #include <linux/can/core.h>
  59. #include <linux/can/skb.h>
  60. #include <linux/can/can-ml.h>
  61. #include <linux/ratelimit.h>
  62. #include <net/net_namespace.h>
  63. #include <net/sock.h>
  64. #include "af_can.h"
  65. MODULE_DESCRIPTION("Controller Area Network PF_CAN core");
  66. MODULE_LICENSE("Dual BSD/GPL");
  67. MODULE_AUTHOR("Urs Thuermann <urs.thuermann@volkswagen.de>, "
  68. "Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
  69. MODULE_ALIAS_NETPROTO(PF_CAN);
  70. static int stats_timer __read_mostly = 1;
  71. module_param(stats_timer, int, 0444);
  72. MODULE_PARM_DESC(stats_timer, "enable timer for statistics (default:on)");
  73. static struct kmem_cache *rcv_cache __read_mostly;
  74. /* table of registered CAN protocols */
  75. static const struct can_proto __rcu *proto_tab[CAN_NPROTO] __read_mostly;
  76. static DEFINE_MUTEX(proto_tab_lock);
  77. static atomic_t skbcounter = ATOMIC_INIT(0);
  78. /* af_can socket functions */
  79. void can_sock_destruct(struct sock *sk)
  80. {
  81. skb_queue_purge(&sk->sk_receive_queue);
  82. skb_queue_purge(&sk->sk_error_queue);
  83. }
  84. EXPORT_SYMBOL(can_sock_destruct);
  85. static const struct can_proto *can_get_proto(int protocol)
  86. {
  87. const struct can_proto *cp;
  88. rcu_read_lock();
  89. cp = rcu_dereference(proto_tab[protocol]);
  90. if (cp && !try_module_get(cp->prot->owner))
  91. cp = NULL;
  92. rcu_read_unlock();
  93. return cp;
  94. }
  95. static inline void can_put_proto(const struct can_proto *cp)
  96. {
  97. module_put(cp->prot->owner);
  98. }
  99. static int can_create(struct net *net, struct socket *sock, int protocol,
  100. int kern)
  101. {
  102. struct sock *sk;
  103. const struct can_proto *cp;
  104. int err = 0;
  105. sock->state = SS_UNCONNECTED;
  106. if (protocol < 0 || protocol >= CAN_NPROTO)
  107. return -EINVAL;
  108. cp = can_get_proto(protocol);
  109. #ifdef CONFIG_MODULES
  110. if (!cp) {
  111. /* try to load protocol module if kernel is modular */
  112. err = request_module("can-proto-%d", protocol);
  113. /* In case of error we only print a message but don't
  114. * return the error code immediately. Below we will
  115. * return -EPROTONOSUPPORT
  116. */
  117. if (err)
  118. pr_err_ratelimited("can: request_module (can-proto-%d) failed.\n",
  119. protocol);
  120. cp = can_get_proto(protocol);
  121. }
  122. #endif
  123. /* check for available protocol and correct usage */
  124. if (!cp)
  125. return -EPROTONOSUPPORT;
  126. if (cp->type != sock->type) {
  127. err = -EPROTOTYPE;
  128. goto errout;
  129. }
  130. sock->ops = cp->ops;
  131. sk = sk_alloc(net, PF_CAN, GFP_KERNEL, cp->prot, kern);
  132. if (!sk) {
  133. err = -ENOMEM;
  134. goto errout;
  135. }
  136. sock_init_data(sock, sk);
  137. sk->sk_destruct = can_sock_destruct;
  138. if (sk->sk_prot->init)
  139. err = sk->sk_prot->init(sk);
  140. if (err) {
  141. /* release sk on errors */
  142. sock_orphan(sk);
  143. sock_put(sk);
  144. sock->sk = NULL;
  145. } else {
  146. sock_prot_inuse_add(net, sk->sk_prot, 1);
  147. }
  148. errout:
  149. can_put_proto(cp);
  150. return err;
  151. }
  152. /* af_can tx path */
  153. /**
  154. * can_send - transmit a CAN frame (optional with local loopback)
  155. * @skb: pointer to socket buffer with CAN frame in data section
  156. * @loop: loopback for listeners on local CAN sockets (recommended default!)
  157. *
  158. * Due to the loopback this routine must not be called from hardirq context.
  159. *
  160. * Return:
  161. * 0 on success
  162. * -ENETDOWN when the selected interface is down
  163. * -ENOBUFS on full driver queue (see net_xmit_errno())
  164. * -ENOMEM when local loopback failed at calling skb_clone()
  165. * -EPERM when trying to send on a non-CAN interface
  166. * -EMSGSIZE CAN frame size is bigger than CAN interface MTU
  167. * -EINVAL when the skb->data does not contain a valid CAN frame
  168. */
  169. int can_send(struct sk_buff *skb, int loop)
  170. {
  171. struct sk_buff *newskb = NULL;
  172. struct can_pkg_stats *pkg_stats = dev_net(skb->dev)->can.pkg_stats;
  173. int err = -EINVAL;
  174. if (can_is_canxl_skb(skb)) {
  175. skb->protocol = htons(ETH_P_CANXL);
  176. } else if (can_is_can_skb(skb)) {
  177. skb->protocol = htons(ETH_P_CAN);
  178. } else if (can_is_canfd_skb(skb)) {
  179. struct canfd_frame *cfd = (struct canfd_frame *)skb->data;
  180. skb->protocol = htons(ETH_P_CANFD);
  181. /* set CAN FD flag for CAN FD frames by default */
  182. cfd->flags |= CANFD_FDF;
  183. } else {
  184. goto inval_skb;
  185. }
  186. /* Make sure the CAN frame can pass the selected CAN netdevice. */
  187. if (unlikely(skb->len > READ_ONCE(skb->dev->mtu))) {
  188. err = -EMSGSIZE;
  189. goto inval_skb;
  190. }
  191. if (unlikely(skb->dev->type != ARPHRD_CAN)) {
  192. err = -EPERM;
  193. goto inval_skb;
  194. }
  195. if (unlikely(!(skb->dev->flags & IFF_UP))) {
  196. err = -ENETDOWN;
  197. goto inval_skb;
  198. }
  199. skb->ip_summed = CHECKSUM_UNNECESSARY;
  200. skb_reset_mac_header(skb);
  201. skb_reset_network_header(skb);
  202. skb_reset_transport_header(skb);
  203. if (loop) {
  204. /* local loopback of sent CAN frames */
  205. /* indication for the CAN driver: do loopback */
  206. skb->pkt_type = PACKET_LOOPBACK;
  207. /* The reference to the originating sock may be required
  208. * by the receiving socket to check whether the frame is
  209. * its own. Example: can_raw sockopt CAN_RAW_RECV_OWN_MSGS
  210. * Therefore we have to ensure that skb->sk remains the
  211. * reference to the originating sock by restoring skb->sk
  212. * after each skb_clone() or skb_orphan() usage.
  213. */
  214. if (!(skb->dev->flags & IFF_ECHO)) {
  215. /* If the interface is not capable to do loopback
  216. * itself, we do it here.
  217. */
  218. newskb = skb_clone(skb, GFP_ATOMIC);
  219. if (!newskb) {
  220. kfree_skb(skb);
  221. return -ENOMEM;
  222. }
  223. can_skb_set_owner(newskb, skb->sk);
  224. newskb->ip_summed = CHECKSUM_UNNECESSARY;
  225. newskb->pkt_type = PACKET_BROADCAST;
  226. }
  227. } else {
  228. /* indication for the CAN driver: no loopback required */
  229. skb->pkt_type = PACKET_HOST;
  230. }
  231. /* send to netdevice */
  232. err = dev_queue_xmit(skb);
  233. if (err > 0)
  234. err = net_xmit_errno(err);
  235. if (err) {
  236. kfree_skb(newskb);
  237. return err;
  238. }
  239. if (newskb)
  240. netif_rx(newskb);
  241. /* update statistics */
  242. atomic_long_inc(&pkg_stats->tx_frames);
  243. atomic_long_inc(&pkg_stats->tx_frames_delta);
  244. return 0;
  245. inval_skb:
  246. kfree_skb(skb);
  247. return err;
  248. }
  249. EXPORT_SYMBOL(can_send);
  250. /* af_can rx path */
  251. static struct can_dev_rcv_lists *can_dev_rcv_lists_find(struct net *net,
  252. struct net_device *dev)
  253. {
  254. if (dev) {
  255. struct can_ml_priv *can_ml = can_get_ml_priv(dev);
  256. return &can_ml->dev_rcv_lists;
  257. } else {
  258. return net->can.rx_alldev_list;
  259. }
  260. }
  261. /**
  262. * effhash - hash function for 29 bit CAN identifier reduction
  263. * @can_id: 29 bit CAN identifier
  264. *
  265. * Description:
  266. * To reduce the linear traversal in one linked list of _single_ EFF CAN
  267. * frame subscriptions the 29 bit identifier is mapped to 10 bits.
  268. * (see CAN_EFF_RCV_HASH_BITS definition)
  269. *
  270. * Return:
  271. * Hash value from 0x000 - 0x3FF ( enforced by CAN_EFF_RCV_HASH_BITS mask )
  272. */
  273. static unsigned int effhash(canid_t can_id)
  274. {
  275. unsigned int hash;
  276. hash = can_id;
  277. hash ^= can_id >> CAN_EFF_RCV_HASH_BITS;
  278. hash ^= can_id >> (2 * CAN_EFF_RCV_HASH_BITS);
  279. return hash & ((1 << CAN_EFF_RCV_HASH_BITS) - 1);
  280. }
  281. /**
  282. * can_rcv_list_find - determine optimal filterlist inside device filter struct
  283. * @can_id: pointer to CAN identifier of a given can_filter
  284. * @mask: pointer to CAN mask of a given can_filter
  285. * @dev_rcv_lists: pointer to the device filter struct
  286. *
  287. * Description:
  288. * Returns the optimal filterlist to reduce the filter handling in the
  289. * receive path. This function is called by service functions that need
  290. * to register or unregister a can_filter in the filter lists.
  291. *
  292. * A filter matches in general, when
  293. *
  294. * <received_can_id> & mask == can_id & mask
  295. *
  296. * so every bit set in the mask (even CAN_EFF_FLAG, CAN_RTR_FLAG) describe
  297. * relevant bits for the filter.
  298. *
  299. * The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
  300. * filter for error messages (CAN_ERR_FLAG bit set in mask). For error msg
  301. * frames there is a special filterlist and a special rx path filter handling.
  302. *
  303. * Return:
  304. * Pointer to optimal filterlist for the given can_id/mask pair.
  305. * Consistency checked mask.
  306. * Reduced can_id to have a preprocessed filter compare value.
  307. */
  308. static struct hlist_head *can_rcv_list_find(canid_t *can_id, canid_t *mask,
  309. struct can_dev_rcv_lists *dev_rcv_lists)
  310. {
  311. canid_t inv = *can_id & CAN_INV_FILTER; /* save flag before masking */
  312. /* filter for error message frames in extra filterlist */
  313. if (*mask & CAN_ERR_FLAG) {
  314. /* clear CAN_ERR_FLAG in filter entry */
  315. *mask &= CAN_ERR_MASK;
  316. return &dev_rcv_lists->rx[RX_ERR];
  317. }
  318. /* with cleared CAN_ERR_FLAG we have a simple mask/value filterpair */
  319. #define CAN_EFF_RTR_FLAGS (CAN_EFF_FLAG | CAN_RTR_FLAG)
  320. /* ensure valid values in can_mask for 'SFF only' frame filtering */
  321. if ((*mask & CAN_EFF_FLAG) && !(*can_id & CAN_EFF_FLAG))
  322. *mask &= (CAN_SFF_MASK | CAN_EFF_RTR_FLAGS);
  323. /* reduce condition testing at receive time */
  324. *can_id &= *mask;
  325. /* inverse can_id/can_mask filter */
  326. if (inv)
  327. return &dev_rcv_lists->rx[RX_INV];
  328. /* mask == 0 => no condition testing at receive time */
  329. if (!(*mask))
  330. return &dev_rcv_lists->rx[RX_ALL];
  331. /* extra filterlists for the subscription of a single non-RTR can_id */
  332. if (((*mask & CAN_EFF_RTR_FLAGS) == CAN_EFF_RTR_FLAGS) &&
  333. !(*can_id & CAN_RTR_FLAG)) {
  334. if (*can_id & CAN_EFF_FLAG) {
  335. if (*mask == (CAN_EFF_MASK | CAN_EFF_RTR_FLAGS))
  336. return &dev_rcv_lists->rx_eff[effhash(*can_id)];
  337. } else {
  338. if (*mask == (CAN_SFF_MASK | CAN_EFF_RTR_FLAGS))
  339. return &dev_rcv_lists->rx_sff[*can_id];
  340. }
  341. }
  342. /* default: filter via can_id/can_mask */
  343. return &dev_rcv_lists->rx[RX_FIL];
  344. }
  345. /**
  346. * can_rx_register - subscribe CAN frames from a specific interface
  347. * @net: the applicable net namespace
  348. * @dev: pointer to netdevice (NULL => subscribe from 'all' CAN devices list)
  349. * @can_id: CAN identifier (see description)
  350. * @mask: CAN mask (see description)
  351. * @func: callback function on filter match
  352. * @data: returned parameter for callback function
  353. * @ident: string for calling module identification
  354. * @sk: socket pointer (might be NULL)
  355. *
  356. * Description:
  357. * Invokes the callback function with the received sk_buff and the given
  358. * parameter 'data' on a matching receive filter. A filter matches, when
  359. *
  360. * <received_can_id> & mask == can_id & mask
  361. *
  362. * The filter can be inverted (CAN_INV_FILTER bit set in can_id) or it can
  363. * filter for error message frames (CAN_ERR_FLAG bit set in mask).
  364. *
  365. * The provided pointer to the sk_buff is guaranteed to be valid as long as
  366. * the callback function is running. The callback function must *not* free
  367. * the given sk_buff while processing it's task. When the given sk_buff is
  368. * needed after the end of the callback function it must be cloned inside
  369. * the callback function with skb_clone().
  370. *
  371. * Return:
  372. * 0 on success
  373. * -ENOMEM on missing cache mem to create subscription entry
  374. * -ENODEV unknown device
  375. */
  376. int can_rx_register(struct net *net, struct net_device *dev, canid_t can_id,
  377. canid_t mask, void (*func)(struct sk_buff *, void *),
  378. void *data, char *ident, struct sock *sk)
  379. {
  380. struct receiver *rcv;
  381. struct hlist_head *rcv_list;
  382. struct can_dev_rcv_lists *dev_rcv_lists;
  383. struct can_rcv_lists_stats *rcv_lists_stats = net->can.rcv_lists_stats;
  384. /* insert new receiver (dev,canid,mask) -> (func,data) */
  385. if (dev && (dev->type != ARPHRD_CAN || !can_get_ml_priv(dev)))
  386. return -ENODEV;
  387. if (dev && !net_eq(net, dev_net(dev)))
  388. return -ENODEV;
  389. rcv = kmem_cache_alloc(rcv_cache, GFP_KERNEL);
  390. if (!rcv)
  391. return -ENOMEM;
  392. spin_lock_bh(&net->can.rcvlists_lock);
  393. dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
  394. rcv_list = can_rcv_list_find(&can_id, &mask, dev_rcv_lists);
  395. rcv->can_id = can_id;
  396. rcv->mask = mask;
  397. atomic_long_set(&rcv->matches, 0);
  398. rcv->func = func;
  399. rcv->data = data;
  400. rcv->ident = ident;
  401. rcv->sk = sk;
  402. hlist_add_head_rcu(&rcv->list, rcv_list);
  403. dev_rcv_lists->entries++;
  404. rcv_lists_stats->rcv_entries++;
  405. rcv_lists_stats->rcv_entries_max = max(rcv_lists_stats->rcv_entries_max,
  406. rcv_lists_stats->rcv_entries);
  407. spin_unlock_bh(&net->can.rcvlists_lock);
  408. return 0;
  409. }
  410. EXPORT_SYMBOL(can_rx_register);
  411. /* can_rx_delete_receiver - rcu callback for single receiver entry removal */
  412. static void can_rx_delete_receiver(struct rcu_head *rp)
  413. {
  414. struct receiver *rcv = container_of(rp, struct receiver, rcu);
  415. struct sock *sk = rcv->sk;
  416. kmem_cache_free(rcv_cache, rcv);
  417. if (sk)
  418. sock_put(sk);
  419. }
  420. /**
  421. * can_rx_unregister - unsubscribe CAN frames from a specific interface
  422. * @net: the applicable net namespace
  423. * @dev: pointer to netdevice (NULL => unsubscribe from 'all' CAN devices list)
  424. * @can_id: CAN identifier
  425. * @mask: CAN mask
  426. * @func: callback function on filter match
  427. * @data: returned parameter for callback function
  428. *
  429. * Description:
  430. * Removes subscription entry depending on given (subscription) values.
  431. */
  432. void can_rx_unregister(struct net *net, struct net_device *dev, canid_t can_id,
  433. canid_t mask, void (*func)(struct sk_buff *, void *),
  434. void *data)
  435. {
  436. struct receiver *rcv = NULL;
  437. struct hlist_head *rcv_list;
  438. struct can_rcv_lists_stats *rcv_lists_stats = net->can.rcv_lists_stats;
  439. struct can_dev_rcv_lists *dev_rcv_lists;
  440. if (dev && dev->type != ARPHRD_CAN)
  441. return;
  442. if (dev && !net_eq(net, dev_net(dev)))
  443. return;
  444. spin_lock_bh(&net->can.rcvlists_lock);
  445. dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
  446. rcv_list = can_rcv_list_find(&can_id, &mask, dev_rcv_lists);
  447. /* Search the receiver list for the item to delete. This should
  448. * exist, since no receiver may be unregistered that hasn't
  449. * been registered before.
  450. */
  451. hlist_for_each_entry_rcu(rcv, rcv_list, list) {
  452. if (rcv->can_id == can_id && rcv->mask == mask &&
  453. rcv->func == func && rcv->data == data)
  454. break;
  455. }
  456. /* Check for bugs in CAN protocol implementations using af_can.c:
  457. * 'rcv' will be NULL if no matching list item was found for removal.
  458. * As this case may potentially happen when closing a socket while
  459. * the notifier for removing the CAN netdev is running we just print
  460. * a warning here.
  461. */
  462. if (!rcv) {
  463. pr_warn("can: receive list entry not found for dev %s, id %03X, mask %03X\n",
  464. DNAME(dev), can_id, mask);
  465. goto out;
  466. }
  467. hlist_del_rcu(&rcv->list);
  468. dev_rcv_lists->entries--;
  469. if (rcv_lists_stats->rcv_entries > 0)
  470. rcv_lists_stats->rcv_entries--;
  471. out:
  472. spin_unlock_bh(&net->can.rcvlists_lock);
  473. /* schedule the receiver item for deletion */
  474. if (rcv) {
  475. if (rcv->sk)
  476. sock_hold(rcv->sk);
  477. call_rcu(&rcv->rcu, can_rx_delete_receiver);
  478. }
  479. }
  480. EXPORT_SYMBOL(can_rx_unregister);
  481. static inline void deliver(struct sk_buff *skb, struct receiver *rcv)
  482. {
  483. rcv->func(skb, rcv->data);
  484. atomic_long_inc(&rcv->matches);
  485. }
  486. static int can_rcv_filter(struct can_dev_rcv_lists *dev_rcv_lists, struct sk_buff *skb)
  487. {
  488. struct receiver *rcv;
  489. int matches = 0;
  490. struct can_frame *cf = (struct can_frame *)skb->data;
  491. canid_t can_id = cf->can_id;
  492. if (dev_rcv_lists->entries == 0)
  493. return 0;
  494. if (can_id & CAN_ERR_FLAG) {
  495. /* check for error message frame entries only */
  496. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx[RX_ERR], list) {
  497. if (can_id & rcv->mask) {
  498. deliver(skb, rcv);
  499. matches++;
  500. }
  501. }
  502. return matches;
  503. }
  504. /* check for unfiltered entries */
  505. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx[RX_ALL], list) {
  506. deliver(skb, rcv);
  507. matches++;
  508. }
  509. /* check for can_id/mask entries */
  510. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx[RX_FIL], list) {
  511. if ((can_id & rcv->mask) == rcv->can_id) {
  512. deliver(skb, rcv);
  513. matches++;
  514. }
  515. }
  516. /* check for inverted can_id/mask entries */
  517. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx[RX_INV], list) {
  518. if ((can_id & rcv->mask) != rcv->can_id) {
  519. deliver(skb, rcv);
  520. matches++;
  521. }
  522. }
  523. /* check filterlists for single non-RTR can_ids */
  524. if (can_id & CAN_RTR_FLAG)
  525. return matches;
  526. if (can_id & CAN_EFF_FLAG) {
  527. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx_eff[effhash(can_id)], list) {
  528. if (rcv->can_id == can_id) {
  529. deliver(skb, rcv);
  530. matches++;
  531. }
  532. }
  533. } else {
  534. can_id &= CAN_SFF_MASK;
  535. hlist_for_each_entry_rcu(rcv, &dev_rcv_lists->rx_sff[can_id], list) {
  536. deliver(skb, rcv);
  537. matches++;
  538. }
  539. }
  540. return matches;
  541. }
  542. void can_set_skb_uid(struct sk_buff *skb)
  543. {
  544. /* create non-zero unique skb identifier together with *skb */
  545. while (!(skb->hash))
  546. skb->hash = atomic_inc_return(&skbcounter);
  547. skb->sw_hash = 1;
  548. }
  549. EXPORT_SYMBOL(can_set_skb_uid);
  550. static void can_receive(struct sk_buff *skb, struct net_device *dev)
  551. {
  552. struct can_dev_rcv_lists *dev_rcv_lists;
  553. struct net *net = dev_net(dev);
  554. struct can_pkg_stats *pkg_stats = net->can.pkg_stats;
  555. int matches;
  556. /* update statistics */
  557. atomic_long_inc(&pkg_stats->rx_frames);
  558. atomic_long_inc(&pkg_stats->rx_frames_delta);
  559. can_set_skb_uid(skb);
  560. rcu_read_lock();
  561. /* deliver the packet to sockets listening on all devices */
  562. matches = can_rcv_filter(net->can.rx_alldev_list, skb);
  563. /* find receive list for this device */
  564. dev_rcv_lists = can_dev_rcv_lists_find(net, dev);
  565. matches += can_rcv_filter(dev_rcv_lists, skb);
  566. rcu_read_unlock();
  567. /* consume the skbuff allocated by the netdevice driver */
  568. consume_skb(skb);
  569. if (matches > 0) {
  570. atomic_long_inc(&pkg_stats->matches);
  571. atomic_long_inc(&pkg_stats->matches_delta);
  572. }
  573. }
  574. static int can_rcv(struct sk_buff *skb, struct net_device *dev,
  575. struct packet_type *pt, struct net_device *orig_dev)
  576. {
  577. if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
  578. !can_skb_ext_find(skb) || !can_is_can_skb(skb))) {
  579. pr_warn_once("PF_CAN: dropped non conform CAN skbuff: dev type %d, len %d\n",
  580. dev->type, skb->len);
  581. kfree_skb_reason(skb, SKB_DROP_REASON_CAN_RX_INVALID_FRAME);
  582. return NET_RX_DROP;
  583. }
  584. can_receive(skb, dev);
  585. return NET_RX_SUCCESS;
  586. }
  587. static int canfd_rcv(struct sk_buff *skb, struct net_device *dev,
  588. struct packet_type *pt, struct net_device *orig_dev)
  589. {
  590. if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
  591. !can_skb_ext_find(skb) || !can_is_canfd_skb(skb))) {
  592. pr_warn_once("PF_CAN: dropped non conform CAN FD skbuff: dev type %d, len %d\n",
  593. dev->type, skb->len);
  594. kfree_skb_reason(skb, SKB_DROP_REASON_CANFD_RX_INVALID_FRAME);
  595. return NET_RX_DROP;
  596. }
  597. can_receive(skb, dev);
  598. return NET_RX_SUCCESS;
  599. }
  600. static int canxl_rcv(struct sk_buff *skb, struct net_device *dev,
  601. struct packet_type *pt, struct net_device *orig_dev)
  602. {
  603. if (unlikely(dev->type != ARPHRD_CAN || !can_get_ml_priv(dev) ||
  604. !can_skb_ext_find(skb) || !can_is_canxl_skb(skb))) {
  605. pr_warn_once("PF_CAN: dropped non conform CAN XL skbuff: dev type %d, len %d\n",
  606. dev->type, skb->len);
  607. kfree_skb_reason(skb, SKB_DROP_REASON_CANXL_RX_INVALID_FRAME);
  608. return NET_RX_DROP;
  609. }
  610. can_receive(skb, dev);
  611. return NET_RX_SUCCESS;
  612. }
  613. /* af_can protocol functions */
  614. /**
  615. * can_proto_register - register CAN transport protocol
  616. * @cp: pointer to CAN protocol structure
  617. *
  618. * Return:
  619. * 0 on success
  620. * -EINVAL invalid (out of range) protocol number
  621. * -EBUSY protocol already in use
  622. * -ENOBUF if proto_register() fails
  623. */
  624. int can_proto_register(const struct can_proto *cp)
  625. {
  626. int proto = cp->protocol;
  627. int err = 0;
  628. if (proto < 0 || proto >= CAN_NPROTO) {
  629. pr_err("can: protocol number %d out of range\n", proto);
  630. return -EINVAL;
  631. }
  632. err = proto_register(cp->prot, 0);
  633. if (err < 0)
  634. return err;
  635. mutex_lock(&proto_tab_lock);
  636. if (rcu_access_pointer(proto_tab[proto])) {
  637. pr_err("can: protocol %d already registered\n", proto);
  638. err = -EBUSY;
  639. } else {
  640. RCU_INIT_POINTER(proto_tab[proto], cp);
  641. }
  642. mutex_unlock(&proto_tab_lock);
  643. if (err < 0)
  644. proto_unregister(cp->prot);
  645. return err;
  646. }
  647. EXPORT_SYMBOL(can_proto_register);
  648. /**
  649. * can_proto_unregister - unregister CAN transport protocol
  650. * @cp: pointer to CAN protocol structure
  651. */
  652. void can_proto_unregister(const struct can_proto *cp)
  653. {
  654. int proto = cp->protocol;
  655. mutex_lock(&proto_tab_lock);
  656. BUG_ON(rcu_access_pointer(proto_tab[proto]) != cp);
  657. RCU_INIT_POINTER(proto_tab[proto], NULL);
  658. mutex_unlock(&proto_tab_lock);
  659. synchronize_rcu();
  660. proto_unregister(cp->prot);
  661. }
  662. EXPORT_SYMBOL(can_proto_unregister);
  663. static int can_pernet_init(struct net *net)
  664. {
  665. spin_lock_init(&net->can.rcvlists_lock);
  666. net->can.rx_alldev_list = kzalloc_obj(*net->can.rx_alldev_list);
  667. if (!net->can.rx_alldev_list)
  668. goto out;
  669. net->can.pkg_stats = kzalloc_obj(*net->can.pkg_stats);
  670. if (!net->can.pkg_stats)
  671. goto out_free_rx_alldev_list;
  672. net->can.rcv_lists_stats = kzalloc_obj(*net->can.rcv_lists_stats);
  673. if (!net->can.rcv_lists_stats)
  674. goto out_free_pkg_stats;
  675. if (IS_ENABLED(CONFIG_PROC_FS)) {
  676. /* the statistics are updated every second (timer triggered) */
  677. if (stats_timer) {
  678. timer_setup(&net->can.stattimer, can_stat_update,
  679. 0);
  680. mod_timer(&net->can.stattimer,
  681. round_jiffies(jiffies + HZ));
  682. }
  683. net->can.pkg_stats->jiffies_init = jiffies;
  684. can_init_proc(net);
  685. }
  686. return 0;
  687. out_free_pkg_stats:
  688. kfree(net->can.pkg_stats);
  689. out_free_rx_alldev_list:
  690. kfree(net->can.rx_alldev_list);
  691. out:
  692. return -ENOMEM;
  693. }
  694. static void can_pernet_exit(struct net *net)
  695. {
  696. if (IS_ENABLED(CONFIG_PROC_FS)) {
  697. can_remove_proc(net);
  698. if (stats_timer)
  699. timer_delete_sync(&net->can.stattimer);
  700. }
  701. kfree(net->can.rx_alldev_list);
  702. kfree(net->can.pkg_stats);
  703. kfree(net->can.rcv_lists_stats);
  704. }
  705. /* af_can module init/exit functions */
  706. static struct packet_type can_packet __read_mostly = {
  707. .type = cpu_to_be16(ETH_P_CAN),
  708. .func = can_rcv,
  709. };
  710. static struct packet_type canfd_packet __read_mostly = {
  711. .type = cpu_to_be16(ETH_P_CANFD),
  712. .func = canfd_rcv,
  713. };
  714. static struct packet_type canxl_packet __read_mostly = {
  715. .type = cpu_to_be16(ETH_P_CANXL),
  716. .func = canxl_rcv,
  717. };
  718. static const struct net_proto_family can_family_ops = {
  719. .family = PF_CAN,
  720. .create = can_create,
  721. .owner = THIS_MODULE,
  722. };
  723. static struct pernet_operations can_pernet_ops __read_mostly = {
  724. .init = can_pernet_init,
  725. .exit = can_pernet_exit,
  726. };
  727. static __init int can_init(void)
  728. {
  729. int err;
  730. /* check for correct padding to be able to use the structs similarly */
  731. BUILD_BUG_ON(offsetof(struct can_frame, len) !=
  732. offsetof(struct canfd_frame, len) ||
  733. offsetof(struct can_frame, len) !=
  734. offsetof(struct canxl_frame, flags) ||
  735. offsetof(struct can_frame, data) !=
  736. offsetof(struct canfd_frame, data));
  737. pr_info("can: controller area network core\n");
  738. rcv_cache = kmem_cache_create("can_receiver", sizeof(struct receiver),
  739. 0, 0, NULL);
  740. if (!rcv_cache)
  741. return -ENOMEM;
  742. err = register_pernet_subsys(&can_pernet_ops);
  743. if (err)
  744. goto out_pernet;
  745. /* protocol register */
  746. err = sock_register(&can_family_ops);
  747. if (err)
  748. goto out_sock;
  749. dev_add_pack(&can_packet);
  750. dev_add_pack(&canfd_packet);
  751. dev_add_pack(&canxl_packet);
  752. return 0;
  753. out_sock:
  754. unregister_pernet_subsys(&can_pernet_ops);
  755. out_pernet:
  756. kmem_cache_destroy(rcv_cache);
  757. return err;
  758. }
  759. static __exit void can_exit(void)
  760. {
  761. /* protocol unregister */
  762. dev_remove_pack(&canxl_packet);
  763. dev_remove_pack(&canfd_packet);
  764. dev_remove_pack(&can_packet);
  765. sock_unregister(PF_CAN);
  766. unregister_pernet_subsys(&can_pernet_ops);
  767. rcu_barrier(); /* Wait for completion of call_rcu()'s */
  768. kmem_cache_destroy(rcv_cache);
  769. }
  770. module_init(can_init);
  771. module_exit(can_exit);