dev_can.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. can->status.sndchange |= 1<<no;
  168. if (can->ops->sendmsg(can, data, no) != RT_EOK)
  169. {
  170. /* send failed. */
  171. level = rt_hw_local_irq_disable();
  172. rt_list_insert_before(&tx_fifo->freelist, &tx_tosnd->list);
  173. rt_hw_local_irq_enable(level);
  174. rt_sem_release(&(tx_fifo->sem));
  175. goto err_ret;
  176. }
  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. can->status.sndchange |= 1<<no;
  256. if (can->ops->sendmsg(can, data, no) != RT_EOK)
  257. {
  258. continue;
  259. }
  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. rt_bool_t is_rxof_event = RT_FALSE;
  848. switch (event & 0xff)
  849. {
  850. case RT_CAN_EVENT_RXOF_IND:
  851. {
  852. rt_base_t level;
  853. is_rxof_event = RT_TRUE;
  854. level = rt_hw_local_irq_disable();
  855. can->status.dropedrcvpkg++;
  856. rt_hw_local_irq_enable(level);
  857. }
  858. /* FALLTHROUGH: RX overflow still tries to fetch one pending frame into software FIFO. */
  859. case RT_CAN_EVENT_RX_IND:
  860. {
  861. struct rt_can_msg tmpmsg;
  862. struct rt_can_rx_fifo *rx_fifo;
  863. struct rt_can_msg_list *listmsg = RT_NULL;
  864. #ifdef RT_CAN_USING_HDR
  865. rt_int8_t hdr;
  866. #endif
  867. int ch = -1;
  868. rt_base_t level;
  869. rt_uint32_t no;
  870. rx_fifo = (struct rt_can_rx_fifo *)can->can_rx;
  871. RT_ASSERT(rx_fifo != RT_NULL);
  872. /* interrupt mode receive */
  873. RT_ASSERT(can->parent.open_flag & RT_DEVICE_FLAG_INT_RX);
  874. no = event >> 8;
  875. ch = can->ops->recvmsg(can, &tmpmsg, no);
  876. if (ch == -1) break;
  877. /* disable interrupt */
  878. level = rt_hw_local_irq_disable();
  879. can->status.rcvpkg++;
  880. can->status.rcvchange = 1;
  881. if (!rt_list_isempty(&rx_fifo->freelist))
  882. {
  883. listmsg = rt_list_entry(rx_fifo->freelist.next, struct rt_can_msg_list, list);
  884. rt_list_remove(&listmsg->list);
  885. #ifdef RT_CAN_USING_HDR
  886. rt_list_remove(&listmsg->hdrlist);
  887. if (listmsg->owner != RT_NULL && listmsg->owner->msgs)
  888. {
  889. listmsg->owner->msgs--;
  890. }
  891. listmsg->owner = RT_NULL;
  892. #endif /*RT_CAN_USING_HDR*/
  893. RT_ASSERT(rx_fifo->freenumbers > 0);
  894. rx_fifo->freenumbers--;
  895. }
  896. else if (!rt_list_isempty(&rx_fifo->uselist))
  897. {
  898. listmsg = rt_list_entry(rx_fifo->uselist.next, struct rt_can_msg_list, list);
  899. if (!is_rxof_event)
  900. {
  901. can->status.dropedrcvpkg++;
  902. }
  903. rt_list_remove(&listmsg->list);
  904. #ifdef RT_CAN_USING_HDR
  905. rt_list_remove(&listmsg->hdrlist);
  906. if (listmsg->owner != RT_NULL && listmsg->owner->msgs)
  907. {
  908. listmsg->owner->msgs--;
  909. }
  910. listmsg->owner = RT_NULL;
  911. #endif
  912. }
  913. /* enable interrupt */
  914. rt_hw_local_irq_enable(level);
  915. if (listmsg != RT_NULL)
  916. {
  917. rt_memcpy(&listmsg->data, &tmpmsg, sizeof(struct rt_can_msg));
  918. level = rt_hw_local_irq_disable();
  919. rt_list_insert_before(&rx_fifo->uselist, &listmsg->list);
  920. #ifdef RT_CAN_USING_HDR
  921. hdr = tmpmsg.hdr_index;
  922. if (can->hdr != RT_NULL)
  923. {
  924. RT_ASSERT(hdr < can->config.maxhdr && hdr >= 0);
  925. if (can->hdr[hdr].connected)
  926. {
  927. rt_list_insert_before(&can->hdr[hdr].list, &listmsg->hdrlist);
  928. listmsg->owner = &can->hdr[hdr];
  929. can->hdr[hdr].msgs++;
  930. }
  931. }
  932. #endif
  933. rt_hw_local_irq_enable(level);
  934. }
  935. /* invoke callback */
  936. #ifdef RT_CAN_USING_HDR
  937. if (can->hdr != RT_NULL && can->hdr[hdr].connected && can->hdr[hdr].filter.ind)
  938. {
  939. rt_size_t rx_length;
  940. RT_ASSERT(hdr < can->config.maxhdr && hdr >= 0);
  941. level = rt_hw_local_irq_disable();
  942. rx_length = can->hdr[hdr].msgs * sizeof(struct rt_can_msg);
  943. rt_hw_local_irq_enable(level);
  944. if (rx_length)
  945. {
  946. can->hdr[hdr].filter.ind(&can->parent, can->hdr[hdr].filter.args, hdr, rx_length);
  947. }
  948. }
  949. else
  950. #endif
  951. {
  952. if (can->parent.rx_indicate != RT_NULL)
  953. {
  954. rt_size_t rx_length;
  955. level = rt_hw_local_irq_disable();
  956. /* get rx length */
  957. rx_length = rt_list_len(&rx_fifo->uselist)* sizeof(struct rt_can_msg);
  958. rt_hw_local_irq_enable(level);
  959. if (rx_length)
  960. {
  961. can->parent.rx_indicate(&can->parent, rx_length);
  962. }
  963. }
  964. }
  965. break;
  966. }
  967. case RT_CAN_EVENT_TX_DONE:
  968. case RT_CAN_EVENT_TX_FAIL:
  969. {
  970. struct rt_can_tx_fifo *tx_fifo;
  971. rt_uint32_t no;
  972. no = event >> 8;
  973. tx_fifo = (struct rt_can_tx_fifo *) can->can_tx;
  974. RT_ASSERT(tx_fifo != RT_NULL);
  975. if (can->status.sndchange&(1<<no))
  976. {
  977. if ((event & 0xff) == RT_CAN_EVENT_TX_DONE)
  978. {
  979. tx_fifo->buffer[no].result = RT_CAN_SND_RESULT_OK;
  980. }
  981. else
  982. {
  983. tx_fifo->buffer[no].result = RT_CAN_SND_RESULT_ERR;
  984. }
  985. rt_completion_done(&(tx_fifo->buffer[no].completion));
  986. }
  987. if (can->ops->sendmsg_nonblocking != RT_NULL)
  988. {
  989. while (RT_TRUE)
  990. {
  991. struct rt_can_msg msg_to_send;
  992. rt_base_t level;
  993. rt_bool_t msg_was_present = RT_FALSE;
  994. level = rt_hw_local_irq_disable();
  995. if (rt_ringbuffer_data_len(&can->nb_tx_rb) >= sizeof(struct rt_can_msg))
  996. {
  997. rt_ringbuffer_get(&can->nb_tx_rb, (rt_uint8_t *)&msg_to_send, sizeof(struct rt_can_msg));
  998. msg_was_present = RT_TRUE;
  999. }
  1000. rt_hw_local_irq_enable(level);
  1001. if (!msg_was_present)
  1002. {
  1003. break;
  1004. }
  1005. if (can->ops->sendmsg_nonblocking(can, &msg_to_send) != RT_EOK)
  1006. {
  1007. level = rt_hw_local_irq_disable();
  1008. rt_ringbuffer_put_force(&can->nb_tx_rb, (rt_uint8_t *)&msg_to_send, sizeof(struct rt_can_msg));
  1009. rt_hw_local_irq_enable(level);
  1010. break;
  1011. }
  1012. }
  1013. }
  1014. break;
  1015. }
  1016. }
  1017. }
  1018. #ifdef RT_USING_FINSH
  1019. #include <finsh.h>
  1020. int cmd_canstat(int argc, void **argv)
  1021. {
  1022. static const char *ErrCode[] =
  1023. {
  1024. "No Error!",
  1025. "Warning !",
  1026. "Passive !",
  1027. "Bus Off !"
  1028. };
  1029. if (argc >= 2)
  1030. {
  1031. struct rt_can_status status;
  1032. rt_device_t candev = rt_device_find(argv[1]);
  1033. if (!candev)
  1034. {
  1035. rt_kprintf(" Can't find can device %s\n", argv[1]);
  1036. return -1;
  1037. }
  1038. rt_kprintf(" Found can device: %s...", argv[1]);
  1039. rt_device_control(candev, RT_CAN_CMD_GET_STATUS, &status);
  1040. rt_kprintf("\n Receive...error..count: %010ld. Send.....error....count: %010ld.",
  1041. status.rcverrcnt, status.snderrcnt);
  1042. rt_kprintf("\n Bit..pad..error..count: %010ld. Format...error....count: %010ld",
  1043. status.bitpaderrcnt, status.formaterrcnt);
  1044. rt_kprintf("\n Ack.......error..count: %010ld. Bit......error....count: %010ld.",
  1045. status.ackerrcnt, status.biterrcnt);
  1046. rt_kprintf("\n CRC.......error..count: %010ld. Error.code.[%010ld]: ",
  1047. status.crcerrcnt, status.errcode);
  1048. switch (status.errcode)
  1049. {
  1050. case 0:
  1051. rt_kprintf("%s.", ErrCode[0]);
  1052. break;
  1053. case 1:
  1054. rt_kprintf("%s.", ErrCode[1]);
  1055. break;
  1056. case 2:
  1057. case 3:
  1058. rt_kprintf("%s.", ErrCode[2]);
  1059. break;
  1060. case 4:
  1061. case 5:
  1062. case 6:
  1063. case 7:
  1064. rt_kprintf("%s.", ErrCode[3]);
  1065. break;
  1066. }
  1067. rt_kprintf("\n Total.receive.packages: %010ld. Dropped.receive.packages: %010ld.",
  1068. status.rcvpkg, status.dropedrcvpkg);
  1069. rt_kprintf("\n Total..send...packages: %010ld. Dropped...send..packages: %010ld.\n",
  1070. status.sndpkg + status.dropedsndpkg, status.dropedsndpkg);
  1071. }
  1072. else
  1073. {
  1074. rt_kprintf(" Invalid Call %s\n", argv[0]);
  1075. rt_kprintf(" Please using %s cannamex .Here canname is driver name and x is candrive number.\n", argv[0]);
  1076. }
  1077. return 0;
  1078. }
  1079. MSH_CMD_EXPORT_ALIAS(cmd_canstat, canstat, stat can device status);
  1080. #endif