kservice.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2006-03-16 Bernard the first version
  9. * 2006-05-25 Bernard rewrite vsprintf
  10. * 2006-08-10 Bernard add rt_show_version
  11. * 2010-03-17 Bernard remove rt_strlcpy function
  12. * fix gcc compiling issue.
  13. * 2010-04-15 Bernard remove weak definition on ICCM16C compiler
  14. * 2012-07-18 Arda add the alignment display for signed integer
  15. * 2012-11-23 Bernard fix IAR compiler error.
  16. * 2012-12-22 Bernard fix rt_kprintf issue, which found by Grissiom.
  17. * 2013-06-24 Bernard remove rt_kprintf if RT_USING_CONSOLE is not defined.
  18. * 2013-09-24 aozima make sure the device is in STREAM mode when used by rt_kprintf.
  19. * 2015-07-06 Bernard Add rt_assert_handler routine.
  20. * 2021-02-28 Meco Man add RT_KSERVICE_USING_STDLIB
  21. * 2021-12-20 Meco Man implement rt_strcpy()
  22. * 2022-01-07 Gabriel add __on_rt_assert_hook
  23. * 2022-06-04 Meco Man remove strnlen
  24. * 2022-08-24 Yunjie make rt_memset word-independent to adapt to ti c28x (16bit word)
  25. * 2022-08-30 Yunjie make rt_vsnprintf adapt to ti c28x (16bit int)
  26. * 2023-02-02 Bernard add Smart ID for logo version show
  27. * 2023-10-16 Shell Add hook point for rt_malloc services
  28. * 2023-12-10 xqyjlj perf rt_hw_interrupt_disable/enable, fix memheap lock
  29. * 2024-03-10 Meco Man move std libc related functions to rtklibc
  30. */
  31. #include <rtthread.h>
  32. #include <rthw.h>
  33. #define DBG_TAG "kernel.service"
  34. #ifdef RT_DEBUG_DEVICE
  35. #define DBG_LVL DBG_LOG
  36. #else
  37. #define DBG_LVL DBG_WARNING
  38. #endif /* defined (RT_DEBUG_DEVICE) */
  39. #include <rtdbg.h>
  40. #ifdef RT_USING_MODULE
  41. #include <dlmodule.h>
  42. #endif /* RT_USING_MODULE */
  43. #ifdef RT_USING_SMART
  44. #include <lwp.h>
  45. #include <lwp_user_mm.h>
  46. #endif
  47. /**
  48. * @addtogroup KernelService
  49. * @{
  50. */
  51. /* global errno in RT-Thread */
  52. static volatile int __rt_errno;
  53. #if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
  54. static rt_device_t _console_device = RT_NULL;
  55. #endif
  56. rt_weak void rt_hw_us_delay(rt_uint32_t us)
  57. {
  58. (void) us;
  59. LOG_W("rt_hw_us_delay() doesn't support for this board."
  60. "Please consider implementing rt_hw_us_delay() in another file.");
  61. }
  62. rt_weak void rt_hw_cpu_reset(void)
  63. {
  64. LOG_W("rt_hw_cpu_reset() doesn't support for this board."
  65. "Please consider implementing rt_hw_cpu_reset() in another file.");
  66. return;
  67. }
  68. rt_weak void rt_hw_cpu_shutdown(void)
  69. {
  70. rt_base_t level;
  71. LOG_I("CPU shutdown...");
  72. LOG_W("Using default rt_hw_cpu_shutdown()."
  73. "Please consider implementing rt_hw_cpu_reset() in another file.");
  74. level = rt_hw_interrupt_disable();
  75. while (level)
  76. {
  77. RT_ASSERT(RT_NULL);
  78. }
  79. return;
  80. }
  81. rt_weak rt_err_t rt_hw_backtrace_frame_get(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  82. {
  83. RT_UNUSED(thread);
  84. RT_UNUSED(frame);
  85. LOG_W("%s is not implemented", __func__);
  86. return -RT_ENOSYS;
  87. }
  88. rt_weak rt_err_t rt_hw_backtrace_frame_unwind(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  89. {
  90. RT_UNUSED(thread);
  91. RT_UNUSED(frame);
  92. LOG_W("%s is not implemented", __func__);
  93. return -RT_ENOSYS;
  94. }
  95. rt_weak const char *rt_hw_cpu_arch(void)
  96. {
  97. return "unknown";
  98. }
  99. struct _errno_str_t
  100. {
  101. rt_err_t error;
  102. const char *str;
  103. };
  104. static struct _errno_str_t rt_errno_strs[] =
  105. {
  106. {RT_EOK , "OK "},
  107. {RT_ERROR , "ERROR "},
  108. {RT_ETIMEOUT, "ETIMOUT"},
  109. {RT_EFULL , "ERSFULL"},
  110. {RT_EEMPTY , "ERSEPTY"},
  111. {RT_ENOMEM , "ENOMEM "},
  112. {RT_ENOSYS , "ENOSYS "},
  113. {RT_EBUSY , "EBUSY "},
  114. {RT_EIO , "EIO "},
  115. {RT_EINTR , "EINTRPT"},
  116. {RT_EINVAL , "EINVAL "},
  117. {RT_ENOENT , "ENOENT "},
  118. {RT_ENOSPC , "ENOSPC "},
  119. {RT_EPERM , "EPERM "},
  120. {RT_ETRAP , "ETRAP "},
  121. };
  122. /**
  123. * @brief This function return a pointer to a string that contains the
  124. * message of error.
  125. *
  126. * @param error the errorno code
  127. * @return a point to error message string
  128. */
  129. const char *rt_strerror(rt_err_t error)
  130. {
  131. int i = 0;
  132. if (error < 0)
  133. error = -error;
  134. for (i = 0; i < sizeof(rt_errno_strs) / sizeof(rt_errno_strs[0]); i++)
  135. {
  136. if (rt_errno_strs[i].error == error)
  137. return rt_errno_strs[i].str;
  138. }
  139. return "EUNKNOW";
  140. }
  141. RTM_EXPORT(rt_strerror);
  142. /**
  143. * @brief This function gets the global errno for the current thread.
  144. *
  145. * @return errno
  146. */
  147. rt_err_t rt_get_errno(void)
  148. {
  149. rt_thread_t tid = RT_NULL;
  150. if (rt_interrupt_get_nest() != 0)
  151. {
  152. /* it's in interrupt context */
  153. return __rt_errno;
  154. }
  155. tid = rt_thread_self();
  156. if (tid == RT_NULL)
  157. {
  158. return __rt_errno;
  159. }
  160. return tid->error;
  161. }
  162. RTM_EXPORT(rt_get_errno);
  163. /**
  164. * @brief This function sets the global errno for the current thread.
  165. *
  166. * @param error is the errno shall be set.
  167. */
  168. void rt_set_errno(rt_err_t error)
  169. {
  170. rt_thread_t tid = RT_NULL;
  171. if (rt_interrupt_get_nest() != 0)
  172. {
  173. /* it's in interrupt context */
  174. __rt_errno = error;
  175. return;
  176. }
  177. tid = rt_thread_self();
  178. if (tid == RT_NULL)
  179. {
  180. __rt_errno = error;
  181. return;
  182. }
  183. tid->error = error;
  184. }
  185. RTM_EXPORT(rt_set_errno);
  186. /**
  187. * @brief This function returns the address of the current thread errno.
  188. *
  189. * @return The errno address.
  190. */
  191. int *_rt_errno(void)
  192. {
  193. rt_thread_t tid = RT_NULL;
  194. if (rt_interrupt_get_nest() != 0)
  195. {
  196. return (int *)&__rt_errno;
  197. }
  198. tid = rt_thread_self();
  199. if (tid != RT_NULL)
  200. {
  201. return (int *) & (tid->error);
  202. }
  203. return (int *)&__rt_errno;
  204. }
  205. RTM_EXPORT(_rt_errno);
  206. /**
  207. * @brief This function will show the version of rt-thread rtos
  208. */
  209. void rt_show_version(void)
  210. {
  211. rt_kprintf("\n \\ | /\n");
  212. #if defined(RT_USING_SMART)
  213. rt_kprintf("- RT - Thread Smart Operating System\n");
  214. #elif defined(RT_USING_NANO)
  215. rt_kprintf("- RT - Thread Nano Operating System\n");
  216. #else
  217. rt_kprintf("- RT - Thread Operating System\n");
  218. #endif
  219. rt_kprintf(" / | \\ %d.%d.%d build %s %s\n",
  220. (rt_int32_t)RT_VERSION_MAJOR, (rt_int32_t)RT_VERSION_MINOR, (rt_int32_t)RT_VERSION_PATCH, __DATE__, __TIME__);
  221. rt_kprintf(" 2006 - 2024 Copyright by RT-Thread team\n");
  222. }
  223. RTM_EXPORT(rt_show_version);
  224. #ifdef RT_USING_CONSOLE
  225. #ifdef RT_USING_DEVICE
  226. /**
  227. * @brief This function returns the device using in console.
  228. *
  229. * @return Returns the console device pointer or RT_NULL.
  230. */
  231. rt_device_t rt_console_get_device(void)
  232. {
  233. return _console_device;
  234. }
  235. RTM_EXPORT(rt_console_get_device);
  236. /**
  237. * @brief This function will set a device as console device.
  238. * After set a device to console, all output of rt_kprintf will be
  239. * redirected to this new device.
  240. *
  241. * @param name is the name of new console device.
  242. *
  243. * @return the old console device handler on successful, or RT_NULL on failure.
  244. */
  245. rt_device_t rt_console_set_device(const char *name)
  246. {
  247. rt_device_t new_device, old_device;
  248. /* save old device */
  249. old_device = _console_device;
  250. /* find new console device */
  251. new_device = rt_device_find(name);
  252. /* check whether it's a same device */
  253. if (new_device == old_device) return RT_NULL;
  254. if (new_device != RT_NULL)
  255. {
  256. if (_console_device != RT_NULL)
  257. {
  258. /* close old console device */
  259. rt_device_close(_console_device);
  260. }
  261. /* set new console device */
  262. rt_device_open(new_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
  263. _console_device = new_device;
  264. }
  265. return old_device;
  266. }
  267. RTM_EXPORT(rt_console_set_device);
  268. #endif /* RT_USING_DEVICE */
  269. rt_weak void rt_hw_console_output(const char *str)
  270. {
  271. /* empty console output */
  272. RT_UNUSED(str);
  273. }
  274. RTM_EXPORT(rt_hw_console_output);
  275. #ifdef RT_USING_THREADSAFE_PRINTF
  276. /* system console lock */
  277. static struct rt_spinlock _syscon_lock = RT_SPINLOCK_INIT;
  278. /* lock of kprintf buffer */
  279. static struct rt_spinlock _prbuf_lock = RT_SPINLOCK_INIT;
  280. /* current user of system console */
  281. static rt_thread_t _pr_curr_user;
  282. #ifdef RT_USING_DEBUG
  283. static rt_base_t _pr_critical_level;
  284. #endif /* RT_USING_DEBUG */
  285. /* nested level of current user */
  286. static volatile int _pr_curr_user_nested;
  287. rt_thread_t rt_console_current_user(void)
  288. {
  289. return _pr_curr_user;
  290. }
  291. static void _console_take(void)
  292. {
  293. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  294. rt_thread_t self_thread = rt_thread_self();
  295. rt_base_t critical_level;
  296. RT_UNUSED(critical_level);
  297. while (_pr_curr_user != self_thread)
  298. {
  299. if (_pr_curr_user == RT_NULL)
  300. {
  301. /* no preemption is allowed to avoid dead lock */
  302. critical_level = rt_enter_critical();
  303. #ifdef RT_USING_DEBUG
  304. _pr_critical_level = _syscon_lock.critical_level;
  305. _syscon_lock.critical_level = critical_level;
  306. #endif
  307. _pr_curr_user = self_thread;
  308. break;
  309. }
  310. else
  311. {
  312. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  313. rt_thread_yield();
  314. level = rt_spin_lock_irqsave(&_syscon_lock);
  315. }
  316. }
  317. _pr_curr_user_nested++;
  318. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  319. }
  320. static void _console_release(void)
  321. {
  322. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  323. rt_thread_t self_thread = rt_thread_self();
  324. RT_UNUSED(self_thread);
  325. RT_ASSERT(_pr_curr_user == self_thread);
  326. _pr_curr_user_nested--;
  327. if (!_pr_curr_user_nested)
  328. {
  329. _pr_curr_user = RT_NULL;
  330. #ifdef RT_USING_DEBUG
  331. rt_exit_critical_safe(_syscon_lock.critical_level);
  332. _syscon_lock.critical_level = _pr_critical_level;
  333. #else
  334. rt_exit_critical();
  335. #endif
  336. }
  337. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  338. }
  339. #define CONSOLE_TAKE _console_take()
  340. #define CONSOLE_RELEASE _console_release()
  341. #define PRINTF_BUFFER_TAKE rt_ubase_t level = rt_spin_lock_irqsave(&_prbuf_lock)
  342. #define PRINTF_BUFFER_RELEASE rt_spin_unlock_irqrestore(&_prbuf_lock, level)
  343. #else
  344. #define CONSOLE_TAKE
  345. #define CONSOLE_RELEASE
  346. #define PRINTF_BUFFER_TAKE
  347. #define PRINTF_BUFFER_RELEASE
  348. #endif /* RT_USING_THREADSAFE_PRINTF */
  349. /**
  350. * @brief This function will put string to the console.
  351. *
  352. * @param str is the string output to the console.
  353. */
  354. static void _kputs(const char *str, long len)
  355. {
  356. RT_UNUSED(len);
  357. CONSOLE_TAKE;
  358. #ifdef RT_USING_DEVICE
  359. if (_console_device == RT_NULL)
  360. {
  361. rt_hw_console_output(str);
  362. }
  363. else
  364. {
  365. rt_device_write(_console_device, 0, str, len);
  366. }
  367. #else
  368. rt_hw_console_output(str);
  369. #endif /* RT_USING_DEVICE */
  370. CONSOLE_RELEASE;
  371. }
  372. /**
  373. * @brief This function will put string to the console.
  374. *
  375. * @param str is the string output to the console.
  376. */
  377. void rt_kputs(const char *str)
  378. {
  379. if (!str)
  380. {
  381. return;
  382. }
  383. _kputs(str, rt_strlen(str));
  384. }
  385. /**
  386. * @brief This function will print a formatted string on system console.
  387. *
  388. * @param fmt is the format parameters.
  389. *
  390. * @return The number of characters actually written to buffer.
  391. */
  392. rt_weak int rt_kprintf(const char *fmt, ...)
  393. {
  394. va_list args;
  395. rt_size_t length = 0;
  396. static char rt_log_buf[RT_CONSOLEBUF_SIZE];
  397. va_start(args, fmt);
  398. PRINTF_BUFFER_TAKE;
  399. /* the return value of vsnprintf is the number of bytes that would be
  400. * written to buffer had if the size of the buffer been sufficiently
  401. * large excluding the terminating null byte. If the output string
  402. * would be larger than the rt_log_buf, we have to adjust the output
  403. * length. */
  404. length = rt_vsnprintf(rt_log_buf, sizeof(rt_log_buf) - 1, fmt, args);
  405. if (length > RT_CONSOLEBUF_SIZE - 1)
  406. {
  407. length = RT_CONSOLEBUF_SIZE - 1;
  408. }
  409. _kputs(rt_log_buf, length);
  410. PRINTF_BUFFER_RELEASE;
  411. va_end(args);
  412. return length;
  413. }
  414. RTM_EXPORT(rt_kprintf);
  415. #endif /* RT_USING_CONSOLE */
  416. #ifdef __GNUC__
  417. rt_weak rt_err_t rt_backtrace(void)
  418. {
  419. struct rt_hw_backtrace_frame frame = {
  420. .fp = (rt_base_t)__builtin_frame_address(0U),
  421. .pc = ({__label__ pc; pc: (rt_base_t)&&pc;})
  422. };
  423. rt_hw_backtrace_frame_unwind(rt_thread_self(), &frame);
  424. return rt_backtrace_frame(&frame);
  425. }
  426. #else /* otherwise not implemented */
  427. rt_weak rt_err_t rt_backtrace(void)
  428. {
  429. /* LOG_W cannot work under this environment */
  430. rt_kprintf("%s is not implemented\n", __func__);
  431. return -RT_ENOSYS;
  432. }
  433. #endif
  434. rt_err_t rt_backtrace_frame(struct rt_hw_backtrace_frame *frame)
  435. {
  436. long nesting = 0;
  437. rt_kprintf("please use: addr2line -e rtthread.elf -a -f");
  438. while (nesting < RT_BACKTRACE_LEVEL_MAX_NR)
  439. {
  440. rt_kprintf(" 0x%lx", (rt_ubase_t)frame->pc);
  441. if (rt_hw_backtrace_frame_unwind(rt_thread_self(), frame))
  442. {
  443. break;
  444. }
  445. nesting++;
  446. }
  447. rt_kprintf("\n");
  448. return RT_EOK;
  449. }
  450. rt_err_t rt_backtrace_thread(rt_thread_t thread)
  451. {
  452. rt_err_t rc;
  453. struct rt_hw_backtrace_frame frame;
  454. if (thread)
  455. {
  456. rc = rt_hw_backtrace_frame_get(thread, &frame);
  457. if (rc == RT_EOK)
  458. {
  459. rc = rt_backtrace_frame(&frame);
  460. }
  461. }
  462. else
  463. {
  464. rc = -RT_EINVAL;
  465. }
  466. return rc;
  467. }
  468. #if defined(RT_USING_LIBC) && defined(RT_USING_FINSH)
  469. #include <stdlib.h> /* for string service */
  470. static void cmd_backtrace(int argc, char** argv)
  471. {
  472. rt_ubase_t pid;
  473. char *end_ptr;
  474. if (argc != 2)
  475. {
  476. if (argc == 1)
  477. {
  478. rt_kprintf("[INFO] No thread specified\n"
  479. "[HELP] You can use commands like: backtrace %p\n"
  480. "Printing backtrace of calling stack...\n",
  481. rt_thread_self());
  482. rt_backtrace();
  483. return ;
  484. }
  485. else
  486. {
  487. rt_kprintf("please use: backtrace [thread_address]\n");
  488. return;
  489. }
  490. }
  491. pid = strtoul(argv[1], &end_ptr, 0);
  492. if (end_ptr == argv[1])
  493. {
  494. rt_kprintf("Invalid input: %s\n", argv[1]);
  495. return ;
  496. }
  497. if (pid && rt_object_get_type((void *)pid) == RT_Object_Class_Thread)
  498. {
  499. rt_thread_t target = (rt_thread_t)pid;
  500. rt_kprintf("backtrace %s(0x%lx), from %s\n", target->parent.name, pid, argv[1]);
  501. rt_backtrace_thread(target);
  502. }
  503. else
  504. rt_kprintf("Invalid pid: %ld\n", pid);
  505. }
  506. MSH_CMD_EXPORT_ALIAS(cmd_backtrace, backtrace, print backtrace of a thread);
  507. #endif /* RT_USING_LIBC */
  508. #if defined(RT_USING_HEAP) && !defined(RT_USING_USERHEAP)
  509. #ifdef RT_USING_HOOK
  510. static void (*rt_malloc_hook)(void **ptr, rt_size_t size);
  511. static void (*rt_realloc_entry_hook)(void **ptr, rt_size_t size);
  512. static void (*rt_realloc_exit_hook)(void **ptr, rt_size_t size);
  513. static void (*rt_free_hook)(void **ptr);
  514. /**
  515. * @addtogroup Hook
  516. * @{
  517. */
  518. /**
  519. * @brief This function will set a hook function, which will be invoked when a memory
  520. * block is allocated from heap memory.
  521. *
  522. * @param hook the hook function.
  523. */
  524. void rt_malloc_sethook(void (*hook)(void **ptr, rt_size_t size))
  525. {
  526. rt_malloc_hook = hook;
  527. }
  528. /**
  529. * @brief This function will set a hook function, which will be invoked when a memory
  530. * block is allocated from heap memory.
  531. *
  532. * @param hook the hook function.
  533. */
  534. void rt_realloc_set_entry_hook(void (*hook)(void **ptr, rt_size_t size))
  535. {
  536. rt_realloc_entry_hook = hook;
  537. }
  538. /**
  539. * @brief This function will set a hook function, which will be invoked when a memory
  540. * block is allocated from heap memory.
  541. *
  542. * @param hook the hook function.
  543. */
  544. void rt_realloc_set_exit_hook(void (*hook)(void **ptr, rt_size_t size))
  545. {
  546. rt_realloc_exit_hook = hook;
  547. }
  548. /**
  549. * @brief This function will set a hook function, which will be invoked when a memory
  550. * block is released to heap memory.
  551. *
  552. * @param hook the hook function
  553. */
  554. void rt_free_sethook(void (*hook)(void **ptr))
  555. {
  556. rt_free_hook = hook;
  557. }
  558. /**@}*/
  559. #endif /* RT_USING_HOOK */
  560. #if defined(RT_USING_HEAP_ISR)
  561. static struct rt_spinlock _heap_spinlock;
  562. #elif defined(RT_USING_MUTEX)
  563. static struct rt_mutex _lock;
  564. #endif
  565. rt_inline void _heap_lock_init(void)
  566. {
  567. #if defined(RT_USING_HEAP_ISR)
  568. rt_spin_lock_init(&_heap_spinlock);
  569. #elif defined(RT_USING_MUTEX)
  570. rt_mutex_init(&_lock, "heap", RT_IPC_FLAG_PRIO);
  571. #endif
  572. }
  573. rt_inline rt_base_t _heap_lock(void)
  574. {
  575. #if defined(RT_USING_HEAP_ISR)
  576. return rt_spin_lock_irqsave(&_heap_spinlock);
  577. #elif defined(RT_USING_MUTEX)
  578. if (rt_thread_self())
  579. return rt_mutex_take(&_lock, RT_WAITING_FOREVER);
  580. else
  581. return RT_EOK;
  582. #else
  583. rt_enter_critical();
  584. return RT_EOK;
  585. #endif
  586. }
  587. rt_inline void _heap_unlock(rt_base_t level)
  588. {
  589. #if defined(RT_USING_HEAP_ISR)
  590. rt_spin_unlock_irqrestore(&_heap_spinlock, level);
  591. #elif defined(RT_USING_MUTEX)
  592. RT_ASSERT(level == RT_EOK);
  593. if (rt_thread_self())
  594. rt_mutex_release(&_lock);
  595. #else
  596. rt_exit_critical();
  597. #endif
  598. }
  599. #ifdef RT_USING_UTESTCASES
  600. /* export to utest to observe the inner statements */
  601. #ifdef _MSC_VER
  602. #define rt_heap_lock() _heap_lock()
  603. #define rt_heap_unlock() _heap_unlock()
  604. #else
  605. rt_base_t rt_heap_lock(void) __attribute__((alias("_heap_lock")));
  606. void rt_heap_unlock(rt_base_t level) __attribute__((alias("_heap_unlock")));
  607. #endif /* _MSC_VER */
  608. #endif
  609. #if defined(RT_USING_SMALL_MEM_AS_HEAP)
  610. static rt_smem_t system_heap;
  611. rt_inline void _smem_info(rt_size_t *total,
  612. rt_size_t *used, rt_size_t *max_used)
  613. {
  614. if (total)
  615. *total = system_heap->total;
  616. if (used)
  617. *used = system_heap->used;
  618. if (max_used)
  619. *max_used = system_heap->max;
  620. }
  621. #define _MEM_INIT(_name, _start, _size) \
  622. system_heap = rt_smem_init(_name, _start, _size)
  623. #define _MEM_MALLOC(_size) \
  624. rt_smem_alloc(system_heap, _size)
  625. #define _MEM_REALLOC(_ptr, _newsize)\
  626. rt_smem_realloc(system_heap, _ptr, _newsize)
  627. #define _MEM_FREE(_ptr) \
  628. rt_smem_free(_ptr)
  629. #define _MEM_INFO(_total, _used, _max) \
  630. _smem_info(_total, _used, _max)
  631. #elif defined(RT_USING_MEMHEAP_AS_HEAP)
  632. static struct rt_memheap system_heap;
  633. void *_memheap_alloc(struct rt_memheap *heap, rt_size_t size);
  634. void _memheap_free(void *rmem);
  635. void *_memheap_realloc(struct rt_memheap *heap, void *rmem, rt_size_t newsize);
  636. #define _MEM_INIT(_name, _start, _size) \
  637. do {\
  638. rt_memheap_init(&system_heap, _name, _start, _size); \
  639. system_heap.locked = RT_TRUE; \
  640. } while(0)
  641. #define _MEM_MALLOC(_size) \
  642. _memheap_alloc(&system_heap, _size)
  643. #define _MEM_REALLOC(_ptr, _newsize) \
  644. _memheap_realloc(&system_heap, _ptr, _newsize)
  645. #define _MEM_FREE(_ptr) \
  646. _memheap_free(_ptr)
  647. #define _MEM_INFO(_total, _used, _max) \
  648. rt_memheap_info(&system_heap, _total, _used, _max)
  649. #elif defined(RT_USING_SLAB_AS_HEAP)
  650. static rt_slab_t system_heap;
  651. rt_inline void _slab_info(rt_size_t *total,
  652. rt_size_t *used, rt_size_t *max_used)
  653. {
  654. if (total)
  655. *total = system_heap->total;
  656. if (used)
  657. *used = system_heap->used;
  658. if (max_used)
  659. *max_used = system_heap->max;
  660. }
  661. #define _MEM_INIT(_name, _start, _size) \
  662. system_heap = rt_slab_init(_name, _start, _size)
  663. #define _MEM_MALLOC(_size) \
  664. rt_slab_alloc(system_heap, _size)
  665. #define _MEM_REALLOC(_ptr, _newsize) \
  666. rt_slab_realloc(system_heap, _ptr, _newsize)
  667. #define _MEM_FREE(_ptr) \
  668. rt_slab_free(system_heap, _ptr)
  669. #define _MEM_INFO _slab_info
  670. #else
  671. #define _MEM_INIT(...)
  672. #define _MEM_MALLOC(...) RT_NULL
  673. #define _MEM_REALLOC(...) RT_NULL
  674. #define _MEM_FREE(...)
  675. #define _MEM_INFO(...)
  676. #endif
  677. static void _rt_system_heap_init(void *begin_addr, void *end_addr)
  678. {
  679. rt_ubase_t begin_align = RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);
  680. rt_ubase_t end_align = RT_ALIGN_DOWN((rt_ubase_t)end_addr, RT_ALIGN_SIZE);
  681. RT_ASSERT(end_align > begin_align);
  682. /* Initialize system memory heap */
  683. _MEM_INIT("heap", (void *)begin_align, end_align - begin_align);
  684. /* Initialize multi thread contention lock */
  685. _heap_lock_init();
  686. }
  687. /**
  688. * @brief This function will init system heap.
  689. *
  690. * @param begin_addr the beginning address of system page.
  691. *
  692. * @param end_addr the end address of system page.
  693. */
  694. rt_weak void rt_system_heap_init(void *begin_addr, void *end_addr)
  695. {
  696. _rt_system_heap_init(begin_addr, end_addr);
  697. }
  698. /**
  699. * @brief Allocate a block of memory with a minimum of 'size' bytes.
  700. *
  701. * @param size is the minimum size of the requested block in bytes.
  702. *
  703. * @return the pointer to allocated memory or NULL if no free memory was found.
  704. */
  705. rt_weak void *rt_malloc(rt_size_t size)
  706. {
  707. rt_base_t level;
  708. void *ptr;
  709. /* Enter critical zone */
  710. level = _heap_lock();
  711. /* allocate memory block from system heap */
  712. ptr = _MEM_MALLOC(size);
  713. /* Exit critical zone */
  714. _heap_unlock(level);
  715. /* call 'rt_malloc' hook */
  716. RT_OBJECT_HOOK_CALL(rt_malloc_hook, (&ptr, size));
  717. return ptr;
  718. }
  719. RTM_EXPORT(rt_malloc);
  720. /**
  721. * @brief This function will change the size of previously allocated memory block.
  722. *
  723. * @param ptr is the pointer to memory allocated by rt_malloc.
  724. *
  725. * @param newsize is the required new size.
  726. *
  727. * @return the changed memory block address.
  728. */
  729. rt_weak void *rt_realloc(void *ptr, rt_size_t newsize)
  730. {
  731. rt_base_t level;
  732. void *nptr;
  733. /* Entry hook */
  734. RT_OBJECT_HOOK_CALL(rt_realloc_entry_hook, (&ptr, newsize));
  735. /* Enter critical zone */
  736. level = _heap_lock();
  737. /* Change the size of previously allocated memory block */
  738. nptr = _MEM_REALLOC(ptr, newsize);
  739. /* Exit critical zone */
  740. _heap_unlock(level);
  741. /* Exit hook */
  742. RT_OBJECT_HOOK_CALL(rt_realloc_exit_hook, (&nptr, newsize));
  743. return nptr;
  744. }
  745. RTM_EXPORT(rt_realloc);
  746. /**
  747. * @brief This function will contiguously allocate enough space for count objects
  748. * that are size bytes of memory each and returns a pointer to the allocated
  749. * memory.
  750. *
  751. * @note The allocated memory is filled with bytes of value zero.
  752. *
  753. * @param count is the number of objects to allocate.
  754. *
  755. * @param size is the size of one object to allocate.
  756. *
  757. * @return pointer to allocated memory / NULL pointer if there is an error.
  758. */
  759. rt_weak void *rt_calloc(rt_size_t count, rt_size_t size)
  760. {
  761. void *p;
  762. /* allocate 'count' objects of size 'size' */
  763. p = rt_malloc(count * size);
  764. /* zero the memory */
  765. if (p)
  766. {
  767. rt_memset(p, 0, count * size);
  768. }
  769. return p;
  770. }
  771. RTM_EXPORT(rt_calloc);
  772. /**
  773. * @brief This function will release the previously allocated memory block by
  774. * rt_malloc. The released memory block is taken back to system heap.
  775. *
  776. * @param ptr the address of memory which will be released.
  777. */
  778. rt_weak void rt_free(void *ptr)
  779. {
  780. rt_base_t level;
  781. /* call 'rt_free' hook */
  782. RT_OBJECT_HOOK_CALL(rt_free_hook, (&ptr));
  783. /* NULL check */
  784. if (ptr == RT_NULL) return;
  785. /* Enter critical zone */
  786. level = _heap_lock();
  787. _MEM_FREE(ptr);
  788. /* Exit critical zone */
  789. _heap_unlock(level);
  790. }
  791. RTM_EXPORT(rt_free);
  792. /**
  793. * @brief This function will caculate the total memory, the used memory, and
  794. * the max used memory.
  795. *
  796. * @param total is a pointer to get the total size of the memory.
  797. *
  798. * @param used is a pointer to get the size of memory used.
  799. *
  800. * @param max_used is a pointer to get the maximum memory used.
  801. */
  802. rt_weak void rt_memory_info(rt_size_t *total,
  803. rt_size_t *used,
  804. rt_size_t *max_used)
  805. {
  806. rt_base_t level;
  807. /* Enter critical zone */
  808. level = _heap_lock();
  809. _MEM_INFO(total, used, max_used);
  810. /* Exit critical zone */
  811. _heap_unlock(level);
  812. }
  813. RTM_EXPORT(rt_memory_info);
  814. #if defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP)
  815. void *rt_page_alloc(rt_size_t npages)
  816. {
  817. rt_base_t level;
  818. void *ptr;
  819. /* Enter critical zone */
  820. level = _heap_lock();
  821. /* alloc page */
  822. ptr = rt_slab_page_alloc(system_heap, npages);
  823. /* Exit critical zone */
  824. _heap_unlock(level);
  825. return ptr;
  826. }
  827. void rt_page_free(void *addr, rt_size_t npages)
  828. {
  829. rt_base_t level;
  830. /* Enter critical zone */
  831. level = _heap_lock();
  832. /* free page */
  833. rt_slab_page_free(system_heap, addr, npages);
  834. /* Exit critical zone */
  835. _heap_unlock(level);
  836. }
  837. #endif
  838. /**
  839. * @brief This function allocates a memory block, which address is aligned to the
  840. * specified alignment size.
  841. *
  842. * @param size is the allocated memory block size.
  843. *
  844. * @param align is the alignment size.
  845. *
  846. * @return The memory block address was returned successfully, otherwise it was
  847. * returned empty RT_NULL.
  848. */
  849. rt_weak void *rt_malloc_align(rt_size_t size, rt_size_t align)
  850. {
  851. void *ptr = RT_NULL;
  852. void *align_ptr = RT_NULL;
  853. int uintptr_size = 0;
  854. rt_size_t align_size = 0;
  855. /* sizeof pointer */
  856. uintptr_size = sizeof(void*);
  857. uintptr_size -= 1;
  858. /* align the alignment size to uintptr size byte */
  859. align = ((align + uintptr_size) & ~uintptr_size);
  860. /* get total aligned size */
  861. align_size = ((size + uintptr_size) & ~uintptr_size) + align;
  862. /* allocate memory block from heap */
  863. ptr = rt_malloc(align_size);
  864. if (ptr != RT_NULL)
  865. {
  866. /* the allocated memory block is aligned */
  867. if (((rt_ubase_t)ptr & (align - 1)) == 0)
  868. {
  869. align_ptr = (void *)((rt_ubase_t)ptr + align);
  870. }
  871. else
  872. {
  873. align_ptr = (void *)(((rt_ubase_t)ptr + (align - 1)) & ~(align - 1));
  874. }
  875. /* set the pointer before alignment pointer to the real pointer */
  876. *((rt_ubase_t *)((rt_ubase_t)align_ptr - sizeof(void *))) = (rt_ubase_t)ptr;
  877. ptr = align_ptr;
  878. }
  879. return ptr;
  880. }
  881. RTM_EXPORT(rt_malloc_align);
  882. /**
  883. * @brief This function release the memory block, which is allocated by
  884. * rt_malloc_align function and address is aligned.
  885. *
  886. * @param ptr is the memory block pointer.
  887. */
  888. rt_weak void rt_free_align(void *ptr)
  889. {
  890. void *real_ptr = RT_NULL;
  891. /* NULL check */
  892. if (ptr == RT_NULL) return;
  893. real_ptr = (void *) * (rt_ubase_t *)((rt_ubase_t)ptr - sizeof(void *));
  894. rt_free(real_ptr);
  895. }
  896. RTM_EXPORT(rt_free_align);
  897. #endif /* RT_USING_HEAP */
  898. #ifndef RT_USING_CPU_FFS
  899. #ifdef RT_USING_TINY_FFS
  900. const rt_uint8_t __lowest_bit_bitmap[] =
  901. {
  902. /* 0 - 7 */ 0, 1, 2, 27, 3, 24, 28, 32,
  903. /* 8 - 15 */ 4, 17, 25, 31, 29, 12, 32, 14,
  904. /* 16 - 23 */ 5, 8, 18, 32, 26, 23, 32, 16,
  905. /* 24 - 31 */ 30, 11, 13, 7, 32, 22, 15, 10,
  906. /* 32 - 36 */ 6, 21, 9, 20, 19
  907. };
  908. /**
  909. * @brief This function finds the first bit set (beginning with the least significant bit)
  910. * in value and return the index of that bit.
  911. *
  912. * Bits are numbered starting at 1 (the least significant bit). A return value of
  913. * zero from any of these functions means that the argument was zero.
  914. *
  915. * @param value is the value to find the first bit set in.
  916. *
  917. * @return return the index of the first bit set. If value is 0, then this function
  918. * shall return 0.
  919. */
  920. int __rt_ffs(int value)
  921. {
  922. return __lowest_bit_bitmap[(rt_uint32_t)(value & (value - 1) ^ value) % 37];
  923. }
  924. #else
  925. const rt_uint8_t __lowest_bit_bitmap[] =
  926. {
  927. /* 00 */ 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  928. /* 10 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  929. /* 20 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  930. /* 30 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  931. /* 40 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  932. /* 50 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  933. /* 60 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  934. /* 70 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  935. /* 80 */ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  936. /* 90 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  937. /* A0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  938. /* B0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  939. /* C0 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  940. /* D0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  941. /* E0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  942. /* F0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
  943. };
  944. /**
  945. * @brief This function finds the first bit set (beginning with the least significant bit)
  946. * in value and return the index of that bit.
  947. *
  948. * Bits are numbered starting at 1 (the least significant bit). A return value of
  949. * zero from any of these functions means that the argument was zero.
  950. *
  951. * @param value is the value to find the first bit set in.
  952. *
  953. * @return Return the index of the first bit set. If value is 0, then this function
  954. * shall return 0.
  955. */
  956. int __rt_ffs(int value)
  957. {
  958. if (value == 0)
  959. {
  960. return 0;
  961. }
  962. if (value & 0xff)
  963. {
  964. return __lowest_bit_bitmap[value & 0xff] + 1;
  965. }
  966. if (value & 0xff00)
  967. {
  968. return __lowest_bit_bitmap[(value & 0xff00) >> 8] + 9;
  969. }
  970. if (value & 0xff0000)
  971. {
  972. return __lowest_bit_bitmap[(value & 0xff0000) >> 16] + 17;
  973. }
  974. return __lowest_bit_bitmap[(value & 0xff000000) >> 24] + 25;
  975. }
  976. #endif /* RT_USING_TINY_FFS */
  977. #endif /* RT_USING_CPU_FFS */
  978. #ifdef RT_USING_DEBUG
  979. /* RT_ASSERT(EX)'s hook */
  980. void (*rt_assert_hook)(const char *ex, const char *func, rt_size_t line);
  981. /**
  982. * This function will set a hook function to RT_ASSERT(EX). It will run when the expression is false.
  983. *
  984. * @param hook is the hook function.
  985. */
  986. void rt_assert_set_hook(void (*hook)(const char *ex, const char *func, rt_size_t line))
  987. {
  988. rt_assert_hook = hook;
  989. }
  990. /**
  991. * The RT_ASSERT function.
  992. *
  993. * @param ex_string is the assertion condition string.
  994. *
  995. * @param func is the function name when assertion.
  996. *
  997. * @param line is the file line number when assertion.
  998. */
  999. void rt_assert_handler(const char *ex_string, const char *func, rt_size_t line)
  1000. {
  1001. volatile char dummy = 0;
  1002. if (rt_assert_hook == RT_NULL)
  1003. {
  1004. #ifdef RT_USING_MODULE
  1005. if (dlmodule_self())
  1006. {
  1007. /* close assertion module */
  1008. dlmodule_exit(-1);
  1009. }
  1010. else
  1011. #endif /*RT_USING_MODULE*/
  1012. {
  1013. rt_kprintf("(%s) assertion failed at function:%s, line number:%d \n", ex_string, func, line);
  1014. rt_backtrace();
  1015. while (dummy == 0);
  1016. }
  1017. }
  1018. else
  1019. {
  1020. rt_assert_hook(ex_string, func, line);
  1021. }
  1022. }
  1023. RTM_EXPORT(rt_assert_handler);
  1024. #endif /* RT_USING_DEBUG */
  1025. /**@}*/