dev_can.c 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /*
  2. * Copyright (c) 2006-2025, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2015-05-14 aubrcool@qq.com first version
  9. * 2015-07-06 Bernard code cleanup and remove RT_CAN_USING_LED;
  10. * 2025-09-20 wdfk_prog Implemented non-blocking, ISR-safe send logic unified under rt_device_write.
  11. */
  12. #include <rthw.h>
  13. #include <rtthread.h>
  14. #include <rtdevice.h>
  15. #define CAN_LOCK(can) rt_mutex_take(&(can->lock), RT_WAITING_FOREVER)
  16. #define CAN_UNLOCK(can) rt_mutex_release(&(can->lock))
  17. static rt_err_t rt_can_init(struct rt_device *dev)
  18. {
  19. rt_err_t result = RT_EOK;
  20. struct rt_can_device *can;
  21. RT_ASSERT(dev != RT_NULL);
  22. can = (struct rt_can_device *)dev;
  23. /* initialize rx/tx */
  24. can->can_rx = RT_NULL;
  25. can->can_tx = RT_NULL;
  26. #ifdef RT_CAN_USING_HDR
  27. can->hdr = RT_NULL;
  28. #endif
  29. /* apply configuration */
  30. if (can->ops->configure)
  31. result = can->ops->configure(can, &can->config);
  32. else
  33. result = -RT_ENOSYS;
  34. return result;
  35. }
  36. /**
  37. * @internal
  38. * @brief Handles reading messages from the software RX FIFO into a user buffer.
  39. *
  40. * This function is called by the public `rt_can_read()` API when the device
  41. * is opened with interrupt-driven reception enabled. It safely transfers
  42. * messages from the internal `uselist` to the user-provided buffer.
  43. *
  44. * @param[in] can A pointer to the CAN device.
  45. * @param[out] data A pointer to the destination buffer for the received messages.
  46. * @param[in] msgs The total size in bytes of the destination buffer.
  47. *
  48. * @return The number of bytes actually read from the FIFO.
  49. */
  50. rt_inline rt_ssize_t _can_int_rx(struct rt_can_device *can, struct rt_can_msg *data, rt_ssize_t msgs)
  51. {
  52. rt_ssize_t size;
  53. struct rt_can_rx_fifo *rx_fifo;
  54. RT_ASSERT(can != RT_NULL);
  55. size = msgs;
  56. rx_fifo = (struct rt_can_rx_fifo *) can->can_rx;
  57. RT_ASSERT(rx_fifo != RT_NULL);
  58. /* read from software FIFO */
  59. while (msgs / sizeof(struct rt_can_msg) > 0)
  60. {
  61. rt_base_t level;
  62. #ifdef RT_CAN_USING_HDR
  63. rt_int8_t hdr;
  64. #endif /*RT_CAN_USING_HDR*/
  65. struct rt_can_msg_list *listmsg = RT_NULL;
  66. /* disable interrupt */
  67. level = rt_hw_local_irq_disable();
  68. #ifdef RT_CAN_USING_HDR
  69. hdr = data->hdr_index;
  70. if (hdr >= 0 && can->hdr && hdr < can->config.maxhdr && !rt_list_isempty(&can->hdr[hdr].list))
  71. {
  72. listmsg = rt_list_entry(can->hdr[hdr].list.next, struct rt_can_msg_list, hdrlist);
  73. rt_list_remove(&listmsg->list);
  74. rt_list_remove(&listmsg->hdrlist);
  75. if (can->hdr[hdr].msgs)
  76. {
  77. can->hdr[hdr].msgs--;
  78. }
  79. listmsg->owner = RT_NULL;
  80. }
  81. else if (hdr == -1)
  82. #endif /*RT_CAN_USING_HDR*/
  83. {
  84. if (!rt_list_isempty(&rx_fifo->uselist))
  85. {
  86. listmsg = rt_list_entry(rx_fifo->uselist.next, struct rt_can_msg_list, list);
  87. rt_list_remove(&listmsg->list);
  88. #ifdef RT_CAN_USING_HDR
  89. rt_list_remove(&listmsg->hdrlist);
  90. if (listmsg->owner != RT_NULL && listmsg->owner->msgs)
  91. {
  92. listmsg->owner->msgs--;
  93. }
  94. listmsg->owner = RT_NULL;
  95. #endif /*RT_CAN_USING_HDR*/
  96. }
  97. else
  98. {
  99. /* no data, enable interrupt and break out */
  100. rt_hw_local_irq_enable(level);
  101. break;
  102. }
  103. }
  104. /* enable interrupt */
  105. rt_hw_local_irq_enable(level);
  106. if (listmsg != RT_NULL)
  107. {
  108. rt_memcpy(data, &listmsg->data, sizeof(struct rt_can_msg));
  109. level = rt_hw_local_irq_disable();
  110. rt_list_insert_before(&rx_fifo->freelist, &listmsg->list);
  111. rx_fifo->freenumbers++;
  112. RT_ASSERT(rx_fifo->freenumbers <= can->config.msgboxsz);
  113. rt_hw_local_irq_enable(level);
  114. listmsg = RT_NULL;
  115. }
  116. else
  117. {
  118. break;
  119. }
  120. data ++;
  121. msgs -= sizeof(struct rt_can_msg);
  122. }
  123. return (size - msgs);
  124. }
  125. /**
  126. * @internal
  127. * @brief Handles the blocking (synchronous) transmission of CAN messages.
  128. *
  129. * This function is the core of the blocking send mechanism. It iterates through
  130. * a buffer of messages to be sent. For each message, it:
  131. * 1. Acquires a hardware mailbox resource using a semaphore.
  132. * 2. Submits the message to the low-level driver for transmission.
  133. * 3. Blocks the calling thread by waiting on a completion object.
  134. * 4. Is woken up by the TX complete ISR (`rt_hw_can_isr`) when the transmission is finished.
  135. *
  136. * @note This function will block the calling thread and must not be called from an ISR.
  137. *
  138. * @param[in] can A pointer to the CAN device.
  139. * @param[in] data A pointer to the source buffer of messages to be sent.
  140. * @param[in] msgs The total size in bytes of the source buffer.
  141. *
  142. * @return The number of bytes successfully sent.
  143. */
  144. rt_inline int _can_int_tx(struct rt_can_device *can, const struct rt_can_msg *data, int msgs)
  145. {
  146. int size;
  147. struct rt_can_tx_fifo *tx_fifo;
  148. RT_ASSERT(can != RT_NULL);
  149. size = msgs;
  150. tx_fifo = (struct rt_can_tx_fifo *) can->can_tx;
  151. RT_ASSERT(tx_fifo != RT_NULL);
  152. while (msgs)
  153. {
  154. rt_base_t level;
  155. rt_uint32_t no;
  156. rt_uint32_t result;
  157. struct rt_can_sndbxinx_list *tx_tosnd = RT_NULL;
  158. rt_sem_take(&(tx_fifo->sem), RT_WAITING_FOREVER);
  159. level = rt_hw_local_irq_disable();
  160. tx_tosnd = rt_list_entry(tx_fifo->freelist.next, struct rt_can_sndbxinx_list, list);
  161. RT_ASSERT(tx_tosnd != RT_NULL);
  162. rt_list_remove(&tx_tosnd->list);
  163. rt_hw_local_irq_enable(level);
  164. no = ((rt_ubase_t)tx_tosnd - (rt_ubase_t)tx_fifo->buffer) / sizeof(struct rt_can_sndbxinx_list);
  165. tx_tosnd->result = RT_CAN_SND_RESULT_WAIT;
  166. rt_completion_init(&tx_tosnd->completion);
  167. if (can->ops->sendmsg(can, data, no) != RT_EOK)
  168. {
  169. /* send failed. */
  170. level = rt_hw_local_irq_disable();
  171. rt_list_insert_before(&tx_fifo->freelist, &tx_tosnd->list);
  172. rt_hw_local_irq_enable(level);
  173. rt_sem_release(&(tx_fifo->sem));
  174. goto err_ret;
  175. }
  176. can->status.sndchange |= 1<<no;
  177. if (rt_completion_wait(&(tx_tosnd->completion), RT_CANSND_MSG_TIMEOUT) != RT_EOK)
  178. {
  179. level = rt_hw_local_irq_disable();
  180. rt_list_insert_before(&tx_fifo->freelist, &tx_tosnd->list);
  181. can->status.sndchange &= ~ (1<<no);
  182. rt_hw_local_irq_enable(level);
  183. rt_sem_release(&(tx_fifo->sem));
  184. goto err_ret;
  185. }
  186. level = rt_hw_local_irq_disable();
  187. result = tx_tosnd->result;
  188. if (!rt_list_isempty(&tx_tosnd->list))
  189. {
  190. rt_list_remove(&tx_tosnd->list);
  191. }
  192. rt_list_insert_before(&tx_fifo->freelist, &tx_tosnd->list);
  193. rt_hw_local_irq_enable(level);
  194. rt_sem_release(&(tx_fifo->sem));
  195. if (result == RT_CAN_SND_RESULT_OK)
  196. {
  197. level = rt_hw_local_irq_disable();
  198. can->status.sndpkg++;
  199. rt_hw_local_irq_enable(level);
  200. data ++;
  201. msgs -= sizeof(struct rt_can_msg);
  202. if (!msgs) break;
  203. }
  204. else
  205. {
  206. err_ret:
  207. level = rt_hw_local_irq_disable();
  208. can->status.dropedsndpkg++;
  209. rt_hw_local_irq_enable(level);
  210. break;
  211. }
  212. }
  213. return (size - msgs);
  214. }
  215. /**
  216. * @internal
  217. * @brief Handles blocking transmission in "private mode".
  218. *
  219. * This is a specialized version of `_can_int_tx` where the target hardware mailbox
  220. * for each message is specified by the user in the `priv` field of the `rt_can_msg`
  221. * structure, rather than being acquired dynamically from a pool.
  222. *
  223. * @param[in] can A pointer to the CAN device.
  224. * @param[in] data A pointer to the source buffer of messages.
  225. * @param[in] msgs The total size in bytes of the source buffer.
  226. *
  227. * @return The number of bytes successfully sent.
  228. */
  229. rt_inline int _can_int_tx_priv(struct rt_can_device *can, const struct rt_can_msg *data, int msgs)
  230. {
  231. int size;
  232. rt_base_t level;
  233. rt_uint32_t no, result;
  234. struct rt_can_tx_fifo *tx_fifo;
  235. RT_ASSERT(can != RT_NULL);
  236. size = msgs;
  237. tx_fifo = (struct rt_can_tx_fifo *) can->can_tx;
  238. RT_ASSERT(tx_fifo != RT_NULL);
  239. while (msgs)
  240. {
  241. no = data->priv;
  242. if (no >= can->config.sndboxnumber)
  243. {
  244. break;
  245. }
  246. level = rt_hw_local_irq_disable();
  247. if ((tx_fifo->buffer[no].result != RT_CAN_SND_RESULT_OK))
  248. {
  249. rt_hw_local_irq_enable(level);
  250. rt_completion_wait(&(tx_fifo->buffer[no].completion), RT_WAITING_FOREVER);
  251. continue;
  252. }
  253. tx_fifo->buffer[no].result = RT_CAN_SND_RESULT_WAIT;
  254. rt_hw_local_irq_enable(level);
  255. if (can->ops->sendmsg(can, data, no) != RT_EOK)
  256. {
  257. continue;
  258. }
  259. can->status.sndchange |= 1<<no;
  260. if (rt_completion_wait(&(tx_fifo->buffer[no].completion), RT_CANSND_MSG_TIMEOUT) != RT_EOK)
  261. {
  262. can->status.sndchange &= ~ (1<<no);
  263. continue;
  264. }
  265. result = tx_fifo->buffer[no].result;
  266. if (result == RT_CAN_SND_RESULT_OK)
  267. {
  268. level = rt_hw_local_irq_disable();
  269. can->status.sndpkg++;
  270. rt_hw_local_irq_enable(level);
  271. data ++;
  272. msgs -= sizeof(struct rt_can_msg);
  273. if (!msgs) break;
  274. }
  275. else
  276. {
  277. level = rt_hw_local_irq_disable();
  278. can->status.dropedsndpkg++;
  279. rt_hw_local_irq_enable(level);
  280. break;
  281. }
  282. }
  283. return (size - msgs);
  284. }
  285. /**
  286. * @internal
  287. * @brief Internal implementation of non-blocking CAN transmission.
  288. *
  289. * This function iterates through a buffer of CAN messages and attempts to send each one
  290. * using a non-blocking strategy. It first tries to send directly via hardware (fast path).
  291. * If the hardware is busy, it enqueues the message into a software ring buffer (slow path).
  292. * This function is thread-safe and ISR-safe due to the use of critical sections for
  293. * accessing the shared ring buffer.
  294. *
  295. * @param[in] can A pointer to the CAN device.
  296. * @param[in] pmsg A pointer to the buffer of `rt_can_msg` structures.
  297. * @param[in] size The total size of the buffer in bytes.
  298. *
  299. * @return The number of bytes successfully sent or enqueued for later transmission.
  300. */
  301. static rt_ssize_t _can_nonblocking_tx(struct rt_can_device *can, const struct rt_can_msg *pmsg, rt_size_t size)
  302. {
  303. rt_ssize_t sent_size = 0;
  304. rt_base_t level;
  305. if (can->ops->sendmsg_nonblocking == RT_NULL)
  306. {
  307. return -RT_EINVAL;
  308. }
  309. while (sent_size < size)
  310. {
  311. if (can->ops->sendmsg_nonblocking(can, pmsg) == RT_EOK)
  312. {
  313. pmsg++;
  314. sent_size += sizeof(struct rt_can_msg);
  315. continue;
  316. }
  317. level = rt_hw_local_irq_disable();
  318. if (rt_ringbuffer_space_len(&can->nb_tx_rb) >= sizeof(struct rt_can_msg))
  319. {
  320. rt_ringbuffer_put(&can->nb_tx_rb, (rt_uint8_t *)pmsg, sizeof(struct rt_can_msg));
  321. rt_hw_local_irq_enable(level);
  322. pmsg++;
  323. sent_size += sizeof(struct rt_can_msg);
  324. }
  325. else
  326. {
  327. /* Buffer is full, cannot process this message or subsequent ones. */
  328. can->status.dropedsndpkg += (size - sent_size) / sizeof(struct rt_can_msg);
  329. rt_hw_local_irq_enable(level);
  330. break;
  331. }
  332. }
  333. return sent_size;
  334. }
  335. /**
  336. * @internal
  337. * @brief Opens the CAN device and initializes its resources.
  338. *
  339. * This function is called when `rt_device_open()` is invoked on a CAN device.
  340. * It allocates and initializes software FIFOs for reception and transmission,
  341. * sets up semaphores for the blocking send mechanism, configures the non-blocking
  342. * send buffer, and starts the periodic status timer.
  343. *
  344. * @param[in] dev A pointer to the device to be opened.
  345. * @param[in] oflag The open flags, e.g., `RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_INT_TX`.
  346. *
  347. * @return `RT_EOK` on successful opening, or an error code on failure.
  348. */
  349. static rt_err_t rt_can_open(struct rt_device *dev, rt_uint16_t oflag)
  350. {
  351. struct rt_can_device *can;
  352. char tmpname[16];
  353. RT_ASSERT(dev != RT_NULL);
  354. can = (struct rt_can_device *)dev;
  355. CAN_LOCK(can);
  356. /* get open flags */
  357. dev->open_flag = oflag & 0xff;
  358. if (can->can_rx == RT_NULL)
  359. {
  360. if (oflag & RT_DEVICE_FLAG_INT_RX)
  361. {
  362. int i = 0;
  363. struct rt_can_rx_fifo *rx_fifo;
  364. rx_fifo = (struct rt_can_rx_fifo *) rt_malloc(sizeof(struct rt_can_rx_fifo) +
  365. can->config.msgboxsz * sizeof(struct rt_can_msg_list));
  366. RT_ASSERT(rx_fifo != RT_NULL);
  367. rx_fifo->buffer = (struct rt_can_msg_list *)(rx_fifo + 1);
  368. rt_memset(rx_fifo->buffer, 0, can->config.msgboxsz * sizeof(struct rt_can_msg_list));
  369. rt_list_init(&rx_fifo->freelist);
  370. rt_list_init(&rx_fifo->uselist);
  371. rx_fifo->freenumbers = can->config.msgboxsz;
  372. for (i = 0; i < can->config.msgboxsz; i++)
  373. {
  374. rt_list_insert_before(&rx_fifo->freelist, &rx_fifo->buffer[i].list);
  375. #ifdef RT_CAN_USING_HDR
  376. rt_list_init(&rx_fifo->buffer[i].hdrlist);
  377. rx_fifo->buffer[i].owner = RT_NULL;
  378. #endif
  379. }
  380. can->can_rx = rx_fifo;
  381. dev->open_flag |= RT_DEVICE_FLAG_INT_RX;
  382. /* open can rx interrupt */
  383. can->ops->control(can, RT_DEVICE_CTRL_SET_INT, (void *)RT_DEVICE_FLAG_INT_RX);
  384. }
  385. }
  386. if (can->can_tx == RT_NULL)
  387. {
  388. if (oflag & RT_DEVICE_FLAG_INT_TX)
  389. {
  390. int i = 0;
  391. struct rt_can_tx_fifo *tx_fifo;
  392. tx_fifo = (struct rt_can_tx_fifo *) rt_malloc(sizeof(struct rt_can_tx_fifo) +
  393. can->config.sndboxnumber * sizeof(struct rt_can_sndbxinx_list));
  394. RT_ASSERT(tx_fifo != RT_NULL);
  395. tx_fifo->buffer = (struct rt_can_sndbxinx_list *)(tx_fifo + 1);
  396. rt_memset(tx_fifo->buffer, 0,
  397. can->config.sndboxnumber * sizeof(struct rt_can_sndbxinx_list));
  398. rt_list_init(&tx_fifo->freelist);
  399. for (i = 0; i < can->config.sndboxnumber; i++)
  400. {
  401. rt_list_insert_before(&tx_fifo->freelist, &tx_fifo->buffer[i].list);
  402. rt_completion_init(&(tx_fifo->buffer[i].completion));
  403. tx_fifo->buffer[i].result = RT_CAN_SND_RESULT_OK;
  404. }
  405. rt_sprintf(tmpname, "%stl", dev->parent.name);
  406. rt_sem_init(&(tx_fifo->sem), tmpname, can->config.sndboxnumber, RT_IPC_FLAG_FIFO);
  407. can->can_tx = tx_fifo;
  408. dev->open_flag |= RT_DEVICE_FLAG_INT_TX;
  409. /* open can tx interrupt */
  410. can->ops->control(can, RT_DEVICE_CTRL_SET_INT, (void *)RT_DEVICE_FLAG_INT_TX);
  411. }
  412. }
  413. can->ops->control(can, RT_DEVICE_CTRL_SET_INT, (void *)RT_DEVICE_CAN_INT_ERR);
  414. #ifdef RT_CAN_USING_HDR
  415. if (can->hdr == RT_NULL)
  416. {
  417. int i = 0;
  418. struct rt_can_hdr *phdr;
  419. phdr = (struct rt_can_hdr *) rt_malloc(can->config.maxhdr * sizeof(struct rt_can_hdr));
  420. RT_ASSERT(phdr != RT_NULL);
  421. rt_memset(phdr, 0, can->config.maxhdr * sizeof(struct rt_can_hdr));
  422. for (i = 0; i < can->config.maxhdr; i++)
  423. {
  424. rt_list_init(&phdr[i].list);
  425. }
  426. can->hdr = phdr;
  427. }
  428. #endif
  429. #ifdef RT_CAN_MALLOC_NB_TX_BUFFER
  430. can->nb_tx_rb_pool = (rt_uint8_t *)rt_malloc(RT_CAN_NB_TX_FIFO_SIZE);
  431. RT_ASSERT(can->nb_tx_rb_pool != RT_NULL);
  432. #endif /* RT_CAN_MALLOC_NB_TX_BUFFER */
  433. rt_ringbuffer_init(&can->nb_tx_rb, can->nb_tx_rb_pool, RT_CAN_NB_TX_FIFO_SIZE);
  434. if (!can->timerinitflag)
  435. {
  436. can->timerinitflag = 1;
  437. rt_timer_start(&can->timer);
  438. }
  439. CAN_UNLOCK(can);
  440. return RT_EOK;
  441. }
  442. static rt_err_t rt_can_close(struct rt_device *dev)
  443. {
  444. struct rt_can_device *can;
  445. RT_ASSERT(dev != RT_NULL);
  446. can = (struct rt_can_device *)dev;
  447. CAN_LOCK(can);
  448. /* this device has more reference count */
  449. if (dev->ref_count > 1)
  450. {
  451. CAN_UNLOCK(can);
  452. return RT_EOK;
  453. }
  454. #ifdef RT_CAN_MALLOC_NB_TX_BUFFER
  455. if (can->nb_tx_rb_pool)
  456. {
  457. rt_free(can->nb_tx_rb_pool);
  458. can->nb_tx_rb_pool = RT_NULL;
  459. }
  460. #endif
  461. if (can->timerinitflag)
  462. {
  463. can->timerinitflag = 0;
  464. rt_timer_stop(&can->timer);
  465. }
  466. can->status_indicate.ind = RT_NULL;
  467. can->status_indicate.args = RT_NULL;
  468. #ifdef RT_CAN_USING_HDR
  469. if (can->hdr != RT_NULL)
  470. {
  471. rt_free(can->hdr);
  472. can->hdr = RT_NULL;
  473. }
  474. #endif
  475. if (dev->open_flag & RT_DEVICE_FLAG_INT_RX)
  476. {
  477. struct rt_can_rx_fifo *rx_fifo;
  478. /* clear can rx interrupt */
  479. can->ops->control(can, RT_DEVICE_CTRL_CLR_INT, (void *)RT_DEVICE_FLAG_INT_RX);
  480. rx_fifo = (struct rt_can_rx_fifo *)can->can_rx;
  481. RT_ASSERT(rx_fifo != RT_NULL);
  482. rt_free(rx_fifo);
  483. dev->open_flag &= ~RT_DEVICE_FLAG_INT_RX;
  484. can->can_rx = RT_NULL;
  485. }
  486. if (dev->open_flag & RT_DEVICE_FLAG_INT_TX)
  487. {
  488. struct rt_can_tx_fifo *tx_fifo;
  489. /* clear can tx interrupt */
  490. can->ops->control(can, RT_DEVICE_CTRL_CLR_INT, (void *)RT_DEVICE_FLAG_INT_TX);
  491. tx_fifo = (struct rt_can_tx_fifo *)can->can_tx;
  492. RT_ASSERT(tx_fifo != RT_NULL);
  493. rt_sem_detach(&(tx_fifo->sem));
  494. rt_free(tx_fifo);
  495. dev->open_flag &= ~RT_DEVICE_FLAG_INT_TX;
  496. can->can_tx = RT_NULL;
  497. }
  498. can->ops->control(can, RT_DEVICE_CTRL_CLR_INT, (void *)RT_DEVICE_CAN_INT_ERR);
  499. can->ops->control(can, RT_CAN_CMD_START, RT_FALSE);
  500. CAN_UNLOCK(can);
  501. return RT_EOK;
  502. }
  503. static rt_ssize_t rt_can_read(struct rt_device *dev,
  504. rt_off_t pos,
  505. void *buffer,
  506. rt_size_t size)
  507. {
  508. struct rt_can_device *can;
  509. RT_ASSERT(dev != RT_NULL);
  510. if (size == 0) return -RT_EINVAL;
  511. can = (struct rt_can_device *)dev;
  512. if ((dev->open_flag & RT_DEVICE_FLAG_INT_RX) && (dev->ref_count > 0))
  513. {
  514. return _can_int_rx(can, buffer, size);
  515. }
  516. return -RT_ENOSYS;
  517. }
  518. /**
  519. * @brief Write data to the CAN device.
  520. *
  521. * This function serves as the unified entry point for sending CAN messages.
  522. * It intelligently routes the request to either a blocking or non-blocking
  523. * transmission function based on:
  524. * 1. The calling context (thread or ISR).
  525. * 2. A user-specified flag (`nonblocking`) in the message structure.
  526. *
  527. * @param[in] dev A pointer to the device object.
  528. * @param[in] pos This parameter is ignored for CAN devices.
  529. * @param[in] buffer A pointer to the buffer containing one or more `rt_can_msg` structures.
  530. * @param[in] size The total size of the buffer in bytes. Must be a multiple of `sizeof(struct rt_can_msg)`.
  531. *
  532. * @return The number of bytes successfully written. For non-blocking sends, this means
  533. * the data was either sent directly or enqueued in the buffer.
  534. */
  535. static rt_ssize_t rt_can_write(struct rt_device *dev,
  536. rt_off_t pos,
  537. const void *buffer,
  538. rt_size_t size)
  539. {
  540. struct rt_can_device *can;
  541. const struct rt_can_msg *pmsg;
  542. RT_ASSERT(dev != RT_NULL);
  543. RT_ASSERT(buffer != RT_NULL);
  544. if (size == 0) return -RT_EINVAL;
  545. /* Ensure size is a multiple of the message size for buffer operations */
  546. if (size % sizeof(struct rt_can_msg) != 0)
  547. {
  548. return -RT_EINVAL;
  549. }
  550. can = (struct rt_can_device *)dev;
  551. pmsg = (const struct rt_can_msg *)buffer;
  552. if(dev->ref_count == 0)
  553. {
  554. return -RT_ENOSYS;
  555. }
  556. /*
  557. * Routing to the non-blocking send scenario:
  558. * 1. Called from within an interrupt context.
  559. * 2. Called from a thread, but the user explicitly set the nonblocking flag on the first message.
  560. */
  561. if (rt_interrupt_get_nest() > 0 || pmsg->nonblocking)
  562. {
  563. return _can_nonblocking_tx(can, pmsg, size);
  564. }
  565. if (dev->open_flag & RT_DEVICE_FLAG_INT_TX)
  566. {
  567. if (can->config.privmode)
  568. {
  569. return _can_int_tx_priv(can, buffer, size);
  570. }
  571. else
  572. {
  573. return _can_int_tx(can, buffer, size);
  574. }
  575. }
  576. return -RT_ENOSYS;
  577. }
  578. static rt_err_t rt_can_control(struct rt_device *dev,
  579. int cmd,
  580. void *args)
  581. {
  582. struct rt_can_device *can;
  583. rt_err_t res;
  584. res = RT_EOK;
  585. RT_ASSERT(dev != RT_NULL);
  586. can = (struct rt_can_device *)dev;
  587. switch (cmd)
  588. {
  589. case RT_DEVICE_CTRL_SUSPEND:
  590. /* suspend device */
  591. dev->flag |= RT_DEVICE_FLAG_SUSPENDED;
  592. break;
  593. case RT_DEVICE_CTRL_RESUME:
  594. /* resume device */
  595. dev->flag &= ~RT_DEVICE_FLAG_SUSPENDED;
  596. break;
  597. case RT_DEVICE_CTRL_CONFIG:
  598. /* configure device */
  599. res = can->ops->configure(can, (struct can_configure *)args);
  600. break;
  601. case RT_CAN_CMD_SET_PRIV:
  602. /* configure device */
  603. if ((rt_uint32_t)(rt_ubase_t)args != can->config.privmode)
  604. {
  605. int i;
  606. rt_base_t level;
  607. struct rt_can_tx_fifo *tx_fifo;
  608. res = can->ops->control(can, cmd, args);
  609. if (res != RT_EOK) return res;
  610. tx_fifo = (struct rt_can_tx_fifo *) can->can_tx;
  611. if (can->config.privmode)
  612. {
  613. for (i = 0; i < can->config.sndboxnumber; i++)
  614. {
  615. level = rt_hw_local_irq_disable();
  616. if(rt_list_isempty(&tx_fifo->buffer[i].list))
  617. {
  618. rt_sem_release(&(tx_fifo->sem));
  619. }
  620. else
  621. {
  622. rt_list_remove(&tx_fifo->buffer[i].list);
  623. }
  624. rt_hw_local_irq_enable(level);
  625. }
  626. }
  627. else
  628. {
  629. for (i = 0; i < can->config.sndboxnumber; i++)
  630. {
  631. level = rt_hw_local_irq_disable();
  632. if (tx_fifo->buffer[i].result == RT_CAN_SND_RESULT_OK)
  633. {
  634. rt_list_insert_before(&tx_fifo->freelist, &tx_fifo->buffer[i].list);
  635. }
  636. rt_hw_local_irq_enable(level);
  637. }
  638. }
  639. }
  640. break;
  641. case RT_CAN_CMD_SET_STATUS_IND:
  642. can->status_indicate.ind = ((rt_can_status_ind_type_t)args)->ind;
  643. can->status_indicate.args = ((rt_can_status_ind_type_t)args)->args;
  644. break;
  645. #ifdef RT_CAN_USING_HDR
  646. case RT_CAN_CMD_SET_FILTER:
  647. res = can->ops->control(can, cmd, args);
  648. if (res != RT_EOK || can->hdr == RT_NULL)
  649. {
  650. return res;
  651. }
  652. struct rt_can_filter_config *pfilter;
  653. struct rt_can_filter_item *pitem;
  654. rt_uint32_t count;
  655. rt_base_t level;
  656. pfilter = (struct rt_can_filter_config *)args;
  657. RT_ASSERT(pfilter);
  658. count = pfilter->count;
  659. pitem = pfilter->items;
  660. if (pfilter->actived)
  661. {
  662. while (count)
  663. {
  664. if (pitem->hdr_bank >= can->config.maxhdr || pitem->hdr_bank < 0)
  665. {
  666. count--;
  667. pitem++;
  668. continue;
  669. }
  670. level = rt_hw_local_irq_disable();
  671. if (!can->hdr[pitem->hdr_bank].connected)
  672. {
  673. rt_hw_local_irq_enable(level);
  674. rt_memcpy(&can->hdr[pitem->hdr_bank].filter, pitem,
  675. sizeof(struct rt_can_filter_item));
  676. level = rt_hw_local_irq_disable();
  677. can->hdr[pitem->hdr_bank].connected = 1;
  678. can->hdr[pitem->hdr_bank].msgs = 0;
  679. rt_list_init(&can->hdr[pitem->hdr_bank].list);
  680. }
  681. rt_hw_local_irq_enable(level);
  682. count--;
  683. pitem++;
  684. }
  685. }
  686. else
  687. {
  688. while (count)
  689. {
  690. if (pitem->hdr_bank >= can->config.maxhdr || pitem->hdr_bank < 0)
  691. {
  692. count--;
  693. pitem++;
  694. continue;
  695. }
  696. level = rt_hw_local_irq_disable();
  697. if (can->hdr[pitem->hdr_bank].connected)
  698. {
  699. can->hdr[pitem->hdr_bank].connected = 0;
  700. can->hdr[pitem->hdr_bank].msgs = 0;
  701. if (!rt_list_isempty(&can->hdr[pitem->hdr_bank].list))
  702. {
  703. rt_list_remove(can->hdr[pitem->hdr_bank].list.next);
  704. }
  705. rt_hw_local_irq_enable(level);
  706. rt_memset(&can->hdr[pitem->hdr_bank].filter, 0,
  707. sizeof(struct rt_can_filter_item));
  708. }
  709. else
  710. {
  711. rt_hw_local_irq_enable(level);
  712. }
  713. count--;
  714. pitem++;
  715. }
  716. }
  717. break;
  718. #endif /*RT_CAN_USING_HDR*/
  719. #ifdef RT_CAN_USING_BUS_HOOK
  720. case RT_CAN_CMD_SET_BUS_HOOK:
  721. can->bus_hook = (rt_can_bus_hook) args;
  722. break;
  723. #endif /*RT_CAN_USING_BUS_HOOK*/
  724. default :
  725. /* control device */
  726. if (can->ops->control != RT_NULL)
  727. {
  728. res = can->ops->control(can, cmd, args);
  729. }
  730. else
  731. {
  732. res = -RT_ENOSYS;
  733. }
  734. break;
  735. }
  736. return res;
  737. }
  738. /**
  739. * @internal
  740. * @brief Periodic timer callback for the CAN device.
  741. *
  742. * This function is executed periodically by a system timer. Its main purposes are:
  743. * 1. To query the current status of the CAN controller (e.g., error counters, bus state).
  744. * 2. To invoke a user-registered status indicator callback, if any.
  745. * 3. To call a user-registered bus hook function for periodic tasks, if any.
  746. *
  747. * @param[in] arg The argument passed to the callback, which is a pointer to the `rt_can_device`.
  748. * @return void
  749. */
  750. static void cantimeout(void *arg)
  751. {
  752. rt_can_t can;
  753. can = (rt_can_t)arg;
  754. RT_ASSERT(can);
  755. rt_device_control((rt_device_t)can, RT_CAN_CMD_GET_STATUS, (void *)&can->status);
  756. if (can->status_indicate.ind != RT_NULL)
  757. {
  758. can->status_indicate.ind(can, can->status_indicate.args);
  759. }
  760. #ifdef RT_CAN_USING_BUS_HOOK
  761. if(can->bus_hook)
  762. {
  763. can->bus_hook(can);
  764. }
  765. #endif /*RT_CAN_USING_BUS_HOOK*/
  766. if (can->timerinitflag == 1)
  767. {
  768. can->timerinitflag = 0xFF;
  769. }
  770. }
  771. #ifdef RT_USING_DEVICE_OPS
  772. const static struct rt_device_ops can_device_ops =
  773. {
  774. rt_can_init,
  775. rt_can_open,
  776. rt_can_close,
  777. rt_can_read,
  778. rt_can_write,
  779. rt_can_control
  780. };
  781. #endif
  782. /*
  783. * can register
  784. */
  785. rt_err_t rt_hw_can_register(struct rt_can_device *can,
  786. const char *name,
  787. const struct rt_can_ops *ops,
  788. void *data)
  789. {
  790. struct rt_device *device;
  791. RT_ASSERT(can != RT_NULL);
  792. device = &(can->parent);
  793. device->type = RT_Device_Class_CAN;
  794. device->rx_indicate = RT_NULL;
  795. device->tx_complete = RT_NULL;
  796. #ifdef RT_CAN_USING_HDR
  797. can->hdr = RT_NULL;
  798. #endif
  799. can->can_rx = RT_NULL;
  800. can->can_tx = RT_NULL;
  801. rt_mutex_init(&(can->lock), "can", RT_IPC_FLAG_PRIO);
  802. #ifdef RT_CAN_USING_BUS_HOOK
  803. can->bus_hook = RT_NULL;
  804. #endif /*RT_CAN_USING_BUS_HOOK*/
  805. #ifdef RT_CAN_MALLOC_NB_TX_BUFFER
  806. can->nb_tx_rb_pool = RT_NULL;
  807. #endif
  808. #ifdef RT_USING_DEVICE_OPS
  809. device->ops = &can_device_ops;
  810. #else
  811. device->init = rt_can_init;
  812. device->open = rt_can_open;
  813. device->close = rt_can_close;
  814. device->read = rt_can_read;
  815. device->write = rt_can_write;
  816. device->control = rt_can_control;
  817. #endif
  818. can->ops = ops;
  819. can->status_indicate.ind = RT_NULL;
  820. can->status_indicate.args = RT_NULL;
  821. rt_memset(&can->status, 0, sizeof(can->status));
  822. device->user_data = data;
  823. can->timerinitflag = 0;
  824. rt_timer_init(&can->timer,
  825. name,
  826. cantimeout,
  827. (void *)can,
  828. can->config.ticks,
  829. RT_TIMER_FLAG_PERIODIC);
  830. /* register a character device */
  831. return rt_device_register(device, name, RT_DEVICE_FLAG_RDWR);
  832. }
  833. /* ISR for can interrupt */
  834. /**
  835. * @brief The framework-level ISR handler for CAN devices.
  836. *
  837. * This function is called by the low-level BSP ISR and acts as the central
  838. * dispatcher for all CAN-related interrupt events. It handles both receive
  839. * events and transmission-complete events.
  840. *
  841. * @param[in] can A pointer to the CAN device structure.
  842. * @param[in] event The interrupt event mask, indicating the cause of the interrupt.
  843. * @return void
  844. */
  845. void rt_hw_can_isr(struct rt_can_device *can, int event)
  846. {
  847. switch (event & 0xff)
  848. {
  849. case RT_CAN_EVENT_RXOF_IND:
  850. {
  851. rt_base_t level;
  852. level = rt_hw_local_irq_disable();
  853. can->status.dropedrcvpkg++;
  854. rt_hw_local_irq_enable(level);
  855. }
  856. case RT_CAN_EVENT_RX_IND:
  857. {
  858. struct rt_can_msg tmpmsg;
  859. struct rt_can_rx_fifo *rx_fifo;
  860. struct rt_can_msg_list *listmsg = RT_NULL;
  861. #ifdef RT_CAN_USING_HDR
  862. rt_int8_t hdr;
  863. #endif
  864. int ch = -1;
  865. rt_base_t level;
  866. rt_uint32_t no;
  867. rx_fifo = (struct rt_can_rx_fifo *)can->can_rx;
  868. RT_ASSERT(rx_fifo != RT_NULL);
  869. /* interrupt mode receive */
  870. RT_ASSERT(can->parent.open_flag & RT_DEVICE_FLAG_INT_RX);
  871. no = event >> 8;
  872. ch = can->ops->recvmsg(can, &tmpmsg, no);
  873. if (ch == -1) break;
  874. /* disable interrupt */
  875. level = rt_hw_local_irq_disable();
  876. can->status.rcvpkg++;
  877. can->status.rcvchange = 1;
  878. if (!rt_list_isempty(&rx_fifo->freelist))
  879. {
  880. listmsg = rt_list_entry(rx_fifo->freelist.next, struct rt_can_msg_list, list);
  881. rt_list_remove(&listmsg->list);
  882. #ifdef RT_CAN_USING_HDR
  883. rt_list_remove(&listmsg->hdrlist);
  884. if (listmsg->owner != RT_NULL && listmsg->owner->msgs)
  885. {
  886. listmsg->owner->msgs--;
  887. }
  888. listmsg->owner = RT_NULL;
  889. #endif /*RT_CAN_USING_HDR*/
  890. RT_ASSERT(rx_fifo->freenumbers > 0);
  891. rx_fifo->freenumbers--;
  892. }
  893. else if (!rt_list_isempty(&rx_fifo->uselist))
  894. {
  895. listmsg = rt_list_entry(rx_fifo->uselist.next, struct rt_can_msg_list, list);
  896. can->status.dropedrcvpkg++;
  897. rt_list_remove(&listmsg->list);
  898. #ifdef RT_CAN_USING_HDR
  899. rt_list_remove(&listmsg->hdrlist);
  900. if (listmsg->owner != RT_NULL && listmsg->owner->msgs)
  901. {
  902. listmsg->owner->msgs--;
  903. }
  904. listmsg->owner = RT_NULL;
  905. #endif
  906. }
  907. /* enable interrupt */
  908. rt_hw_local_irq_enable(level);
  909. if (listmsg != RT_NULL)
  910. {
  911. rt_memcpy(&listmsg->data, &tmpmsg, sizeof(struct rt_can_msg));
  912. level = rt_hw_local_irq_disable();
  913. rt_list_insert_before(&rx_fifo->uselist, &listmsg->list);
  914. #ifdef RT_CAN_USING_HDR
  915. hdr = tmpmsg.hdr_index;
  916. if (can->hdr != RT_NULL)
  917. {
  918. RT_ASSERT(hdr < can->config.maxhdr && hdr >= 0);
  919. if (can->hdr[hdr].connected)
  920. {
  921. rt_list_insert_before(&can->hdr[hdr].list, &listmsg->hdrlist);
  922. listmsg->owner = &can->hdr[hdr];
  923. can->hdr[hdr].msgs++;
  924. }
  925. }
  926. #endif
  927. rt_hw_local_irq_enable(level);
  928. }
  929. /* invoke callback */
  930. #ifdef RT_CAN_USING_HDR
  931. if (can->hdr != RT_NULL && can->hdr[hdr].connected && can->hdr[hdr].filter.ind)
  932. {
  933. rt_size_t rx_length;
  934. RT_ASSERT(hdr < can->config.maxhdr && hdr >= 0);
  935. level = rt_hw_local_irq_disable();
  936. rx_length = can->hdr[hdr].msgs * sizeof(struct rt_can_msg);
  937. rt_hw_local_irq_enable(level);
  938. if (rx_length)
  939. {
  940. can->hdr[hdr].filter.ind(&can->parent, can->hdr[hdr].filter.args, hdr, rx_length);
  941. }
  942. }
  943. else
  944. #endif
  945. {
  946. if (can->parent.rx_indicate != RT_NULL)
  947. {
  948. rt_size_t rx_length;
  949. level = rt_hw_local_irq_disable();
  950. /* get rx length */
  951. rx_length = rt_list_len(&rx_fifo->uselist)* sizeof(struct rt_can_msg);
  952. rt_hw_local_irq_enable(level);
  953. if (rx_length)
  954. {
  955. can->parent.rx_indicate(&can->parent, rx_length);
  956. }
  957. }
  958. }
  959. break;
  960. }
  961. case RT_CAN_EVENT_TX_DONE:
  962. case RT_CAN_EVENT_TX_FAIL:
  963. {
  964. struct rt_can_tx_fifo *tx_fifo;
  965. rt_uint32_t no;
  966. no = event >> 8;
  967. tx_fifo = (struct rt_can_tx_fifo *) can->can_tx;
  968. RT_ASSERT(tx_fifo != RT_NULL);
  969. if (can->status.sndchange&(1<<no))
  970. {
  971. if ((event & 0xff) == RT_CAN_EVENT_TX_DONE)
  972. {
  973. tx_fifo->buffer[no].result = RT_CAN_SND_RESULT_OK;
  974. }
  975. else
  976. {
  977. tx_fifo->buffer[no].result = RT_CAN_SND_RESULT_ERR;
  978. }
  979. rt_completion_done(&(tx_fifo->buffer[no].completion));
  980. }
  981. if (can->ops->sendmsg_nonblocking != RT_NULL)
  982. {
  983. while (RT_TRUE)
  984. {
  985. struct rt_can_msg msg_to_send;
  986. rt_base_t level;
  987. rt_bool_t msg_was_present = RT_FALSE;
  988. level = rt_hw_local_irq_disable();
  989. if (rt_ringbuffer_data_len(&can->nb_tx_rb) >= sizeof(struct rt_can_msg))
  990. {
  991. rt_ringbuffer_get(&can->nb_tx_rb, (rt_uint8_t *)&msg_to_send, sizeof(struct rt_can_msg));
  992. msg_was_present = RT_TRUE;
  993. }
  994. rt_hw_local_irq_enable(level);
  995. if (!msg_was_present)
  996. {
  997. break;
  998. }
  999. if (can->ops->sendmsg_nonblocking(can, &msg_to_send) != RT_EOK)
  1000. {
  1001. level = rt_hw_local_irq_disable();
  1002. rt_ringbuffer_put_force(&can->nb_tx_rb, (rt_uint8_t *)&msg_to_send, sizeof(struct rt_can_msg));
  1003. rt_hw_local_irq_enable(level);
  1004. break;
  1005. }
  1006. }
  1007. }
  1008. break;
  1009. }
  1010. }
  1011. }
  1012. #ifdef RT_USING_FINSH
  1013. #include <finsh.h>
  1014. int cmd_canstat(int argc, void **argv)
  1015. {
  1016. static const char *ErrCode[] =
  1017. {
  1018. "No Error!",
  1019. "Warning !",
  1020. "Passive !",
  1021. "Bus Off !"
  1022. };
  1023. if (argc >= 2)
  1024. {
  1025. struct rt_can_status status;
  1026. rt_device_t candev = rt_device_find(argv[1]);
  1027. if (!candev)
  1028. {
  1029. rt_kprintf(" Can't find can device %s\n", argv[1]);
  1030. return -1;
  1031. }
  1032. rt_kprintf(" Found can device: %s...", argv[1]);
  1033. rt_device_control(candev, RT_CAN_CMD_GET_STATUS, &status);
  1034. rt_kprintf("\n Receive...error..count: %010ld. Send.....error....count: %010ld.",
  1035. status.rcverrcnt, status.snderrcnt);
  1036. rt_kprintf("\n Bit..pad..error..count: %010ld. Format...error....count: %010ld",
  1037. status.bitpaderrcnt, status.formaterrcnt);
  1038. rt_kprintf("\n Ack.......error..count: %010ld. Bit......error....count: %010ld.",
  1039. status.ackerrcnt, status.biterrcnt);
  1040. rt_kprintf("\n CRC.......error..count: %010ld. Error.code.[%010ld]: ",
  1041. status.crcerrcnt, status.errcode);
  1042. switch (status.errcode)
  1043. {
  1044. case 0:
  1045. rt_kprintf("%s.", ErrCode[0]);
  1046. break;
  1047. case 1:
  1048. rt_kprintf("%s.", ErrCode[1]);
  1049. break;
  1050. case 2:
  1051. case 3:
  1052. rt_kprintf("%s.", ErrCode[2]);
  1053. break;
  1054. case 4:
  1055. case 5:
  1056. case 6:
  1057. case 7:
  1058. rt_kprintf("%s.", ErrCode[3]);
  1059. break;
  1060. }
  1061. rt_kprintf("\n Total.receive.packages: %010ld. Dropped.receive.packages: %010ld.",
  1062. status.rcvpkg, status.dropedrcvpkg);
  1063. rt_kprintf("\n Total..send...packages: %010ld. Dropped...send..packages: %010ld.\n",
  1064. status.sndpkg + status.dropedsndpkg, status.dropedsndpkg);
  1065. }
  1066. else
  1067. {
  1068. rt_kprintf(" Invalid Call %s\n", argv[0]);
  1069. rt_kprintf(" Please using %s cannamex .Here canname is driver name and x is candrive number.\n", argv[0]);
  1070. }
  1071. return 0;
  1072. }
  1073. MSH_CMD_EXPORT_ALIAS(cmd_canstat, canstat, stat can device status);
  1074. #endif