af_can.c 25 KB

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