stats.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * Debugging module statistics.
  4. *
  5. * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org>
  6. */
  7. #include <linux/module.h>
  8. #include <uapi/linux/module.h>
  9. #include <linux/string.h>
  10. #include <linux/printk.h>
  11. #include <linux/slab.h>
  12. #include <linux/list.h>
  13. #include <linux/debugfs.h>
  14. #include <linux/rculist.h>
  15. #include <linux/math.h>
  16. #include "internal.h"
  17. /**
  18. * DOC: module debugging statistics overview
  19. *
  20. * Enabling CONFIG_MODULE_STATS enables module debugging statistics which
  21. * are useful to monitor and root cause memory pressure issues with module
  22. * loading. These statistics are useful to allow us to improve production
  23. * workloads.
  24. *
  25. * The current module debugging statistics supported help keep track of module
  26. * loading failures to enable improvements either for kernel module auto-loading
  27. * usage (request_module()) or interactions with userspace. Statistics are
  28. * provided to track all possible failures in the finit_module() path and memory
  29. * wasted in this process space. Each of the failure counters are associated
  30. * to a type of module loading failure which is known to incur a certain amount
  31. * of memory allocation loss. In the worst case loading a module will fail after
  32. * a 3 step memory allocation process:
  33. *
  34. * a) memory allocated with kernel_read_file_from_fd()
  35. * b) module decompression processes the file read from
  36. * kernel_read_file_from_fd(), and vmap() is used to map
  37. * the decompressed module to a new local buffer which represents
  38. * a copy of the decompressed module passed from userspace. The buffer
  39. * from kernel_read_file_from_fd() is freed right away.
  40. * c) layout_and_allocate() allocates space for the final resting
  41. * place where we would keep the module if it were to be processed
  42. * successfully.
  43. *
  44. * If a failure occurs after these three different allocations only one
  45. * counter will be incremented with the summation of the allocated bytes freed
  46. * incurred during this failure. Likewise, if module loading failed only after
  47. * step b) a separate counter is used and incremented for the bytes freed and
  48. * not used during both of those allocations.
  49. *
  50. * Virtual memory space can be limited, for example on x86 virtual memory size
  51. * defaults to 128 MiB. We should strive to limit and avoid wasting virtual
  52. * memory allocations when possible. These module debugging statistics help
  53. * to evaluate how much memory is being wasted on bootup due to module loading
  54. * failures.
  55. *
  56. * All counters are designed to be incremental. Atomic counters are used so to
  57. * remain simple and avoid delays and deadlocks.
  58. */
  59. /**
  60. * DOC: dup_failed_modules - tracks duplicate failed modules
  61. *
  62. * Linked list of modules which failed to be loaded because an already existing
  63. * module with the same name was already being processed or already loaded.
  64. * The finit_module() system call incurs heavy virtual memory allocations. In
  65. * the worst case an finit_module() system call can end up allocating virtual
  66. * memory 3 times:
  67. *
  68. * 1) kernel_read_file_from_fd() call uses vmalloc()
  69. * 2) optional module decompression uses vmap()
  70. * 3) layout_and allocate() can use vzalloc() or an arch specific variation of
  71. * vmalloc to deal with ELF sections requiring special permissions
  72. *
  73. * In practice on a typical boot today most finit_module() calls fail due to
  74. * the module with the same name already being loaded or about to be processed.
  75. * All virtual memory allocated to these failed modules will be freed with
  76. * no functional use.
  77. *
  78. * To help with this the dup_failed_modules allows us to track modules which
  79. * failed to load due to the fact that a module was already loaded or being
  80. * processed. There are only two points at which we can fail such calls,
  81. * we list them below along with the number of virtual memory allocation
  82. * calls:
  83. *
  84. * a) FAIL_DUP_MOD_BECOMING: at the end of early_mod_check() before
  85. * layout_and_allocate().
  86. * - with module decompression: 2 virtual memory allocation calls
  87. * - without module decompression: 1 virtual memory allocation calls
  88. * b) FAIL_DUP_MOD_LOAD: after layout_and_allocate() on add_unformed_module()
  89. * - with module decompression 3 virtual memory allocation calls
  90. * - without module decompression 2 virtual memory allocation calls
  91. *
  92. * We should strive to get this list to be as small as possible. If this list
  93. * is not empty it is a reflection of possible work or optimizations possible
  94. * either in-kernel or in userspace.
  95. */
  96. static LIST_HEAD(dup_failed_modules);
  97. /**
  98. * DOC: module statistics debugfs counters
  99. *
  100. * The total amount of wasted virtual memory allocation space during module
  101. * loading can be computed by adding the total from the summation:
  102. *
  103. * * @invalid_kread_bytes +
  104. * @invalid_decompress_bytes +
  105. * @invalid_becoming_bytes +
  106. * @invalid_mod_bytes
  107. *
  108. * The following debugfs counters are available to inspect module loading
  109. * failures:
  110. *
  111. * * total_mod_size: total bytes ever used by all modules we've dealt with on
  112. * this system
  113. * * total_text_size: total bytes of the .text and .init.text ELF section
  114. * sizes we've dealt with on this system
  115. * * invalid_kread_bytes: bytes allocated and then freed on failures which
  116. * happen due to the initial kernel_read_file_from_fd(). kernel_read_file_from_fd()
  117. * uses vmalloc(). These should typically not happen unless your system is
  118. * under memory pressure.
  119. * * invalid_decompress_bytes: number of bytes allocated and freed due to
  120. * memory allocations in the module decompression path that use vmap().
  121. * These typically should not happen unless your system is under memory
  122. * pressure.
  123. * * invalid_becoming_bytes: total number of bytes allocated and freed used
  124. * to read the kernel module userspace wants us to read before we
  125. * promote it to be processed to be added to our @modules linked list. These
  126. * failures can happen if we had a check in between a successful kernel_read_file_from_fd()
  127. * call and right before we allocate the our private memory for the module
  128. * which would be kept if the module is successfully loaded. The most common
  129. * reason for this failure is when userspace is racing to load a module
  130. * which it does not yet see loaded. The first module to succeed in
  131. * add_unformed_module() will add a module to our &modules list and
  132. * subsequent loads of modules with the same name will error out at the
  133. * end of early_mod_check(). The check for module_patient_check_exists()
  134. * at the end of early_mod_check() prevents duplicate allocations
  135. * on layout_and_allocate() for modules already being processed. These
  136. * duplicate failed modules are non-fatal, however they typically are
  137. * indicative of userspace not seeing a module in userspace loaded yet and
  138. * unnecessarily trying to load a module before the kernel even has a chance
  139. * to begin to process prior requests. Although duplicate failures can be
  140. * non-fatal, we should try to reduce vmalloc() pressure proactively, so
  141. * ideally after boot this will be close to as 0 as possible. If module
  142. * decompression was used we also add to this counter the cost of the
  143. * initial kernel_read_file_from_fd() of the compressed module. If module
  144. * decompression was not used the value represents the total allocated and
  145. * freed bytes in kernel_read_file_from_fd() calls for these type of
  146. * failures. These failures can occur because:
  147. *
  148. * * module_sig_check() - module signature checks
  149. * * elf_validity_cache_copy() - some ELF validation issue
  150. * * early_mod_check():
  151. *
  152. * * blacklisting
  153. * * failed to rewrite section headers
  154. * * version magic
  155. * * live patch requirements didn't check out
  156. * * the module was detected as being already present
  157. *
  158. * * invalid_mod_bytes: these are the total number of bytes allocated and
  159. * freed due to failures after we did all the sanity checks of the module
  160. * which userspace passed to us and after our first check that the module
  161. * is unique. A module can still fail to load if we detect the module is
  162. * loaded after we allocate space for it with layout_and_allocate(), we do
  163. * this check right before processing the module as live and run its
  164. * initialization routines. Note that you have a failure of this type it
  165. * also means the respective kernel_read_file_from_fd() memory space was
  166. * also freed and not used, and so we increment this counter with twice
  167. * the size of the module. Additionally if you used module decompression
  168. * the size of the compressed module is also added to this counter.
  169. *
  170. * * modcount: how many modules we've loaded in our kernel life time
  171. * * failed_kreads: how many modules failed due to failed kernel_read_file_from_fd()
  172. * * failed_decompress: how many failed module decompression attempts we've had.
  173. * These really should not happen unless your compression / decompression
  174. * might be broken.
  175. * * failed_becoming: how many modules failed after we kernel_read_file_from_fd()
  176. * it and before we allocate memory for it with layout_and_allocate(). This
  177. * counter is never incremented if you manage to validate the module and
  178. * call layout_and_allocate() for it.
  179. * * failed_load_modules: how many modules failed once we've allocated our
  180. * private space for our module using layout_and_allocate(). These failures
  181. * should hopefully mostly be dealt with already. Races in theory could
  182. * still exist here, but it would just mean the kernel had started processing
  183. * two threads concurrently up to early_mod_check() and one thread won.
  184. * These failures are good signs the kernel or userspace is doing something
  185. * seriously stupid or that could be improved. We should strive to fix these,
  186. * but it is perhaps not easy to fix them. A recent example are the modules
  187. * requests incurred for frequency modules, a separate module request was
  188. * being issued for each CPU on a system.
  189. */
  190. atomic_long_t total_mod_size;
  191. atomic_long_t total_text_size;
  192. atomic_long_t invalid_kread_bytes;
  193. atomic_long_t invalid_decompress_bytes;
  194. static atomic_long_t invalid_becoming_bytes;
  195. static atomic_long_t invalid_mod_bytes;
  196. atomic_t modcount;
  197. atomic_t failed_kreads;
  198. atomic_t failed_decompress;
  199. static atomic_t failed_becoming;
  200. static atomic_t failed_load_modules;
  201. static const char *mod_fail_to_str(struct mod_fail_load *mod_fail)
  202. {
  203. if (test_bit(FAIL_DUP_MOD_BECOMING, &mod_fail->dup_fail_mask) &&
  204. test_bit(FAIL_DUP_MOD_LOAD, &mod_fail->dup_fail_mask))
  205. return "Becoming & Load";
  206. if (test_bit(FAIL_DUP_MOD_BECOMING, &mod_fail->dup_fail_mask))
  207. return "Becoming";
  208. if (test_bit(FAIL_DUP_MOD_LOAD, &mod_fail->dup_fail_mask))
  209. return "Load";
  210. return "Bug-on-stats";
  211. }
  212. void mod_stat_bump_invalid(struct load_info *info, int flags)
  213. {
  214. atomic_long_add(info->len * 2, &invalid_mod_bytes);
  215. atomic_inc(&failed_load_modules);
  216. #if defined(CONFIG_MODULE_DECOMPRESS)
  217. if (flags & MODULE_INIT_COMPRESSED_FILE)
  218. atomic_long_add(info->compressed_len, &invalid_mod_bytes);
  219. #endif
  220. }
  221. void mod_stat_bump_becoming(struct load_info *info, int flags)
  222. {
  223. atomic_inc(&failed_becoming);
  224. atomic_long_add(info->len, &invalid_becoming_bytes);
  225. #if defined(CONFIG_MODULE_DECOMPRESS)
  226. if (flags & MODULE_INIT_COMPRESSED_FILE)
  227. atomic_long_add(info->compressed_len, &invalid_becoming_bytes);
  228. #endif
  229. }
  230. int try_add_failed_module(const char *name, enum fail_dup_mod_reason reason)
  231. {
  232. struct mod_fail_load *mod_fail;
  233. list_for_each_entry_rcu(mod_fail, &dup_failed_modules, list,
  234. lockdep_is_held(&module_mutex)) {
  235. if (!strcmp(mod_fail->name, name)) {
  236. atomic_long_inc(&mod_fail->count);
  237. __set_bit(reason, &mod_fail->dup_fail_mask);
  238. goto out;
  239. }
  240. }
  241. mod_fail = kzalloc(sizeof(*mod_fail), GFP_KERNEL);
  242. if (!mod_fail)
  243. return -ENOMEM;
  244. memcpy(mod_fail->name, name, strlen(name));
  245. __set_bit(reason, &mod_fail->dup_fail_mask);
  246. atomic_long_inc(&mod_fail->count);
  247. list_add_rcu(&mod_fail->list, &dup_failed_modules);
  248. out:
  249. return 0;
  250. }
  251. /*
  252. * At 64 bytes per module and assuming a 1024 bytes preamble we can fit the
  253. * 112 module prints within 8k.
  254. *
  255. * 1024 + (64*112) = 8k
  256. */
  257. #define MAX_PREAMBLE 1024
  258. #define MAX_FAILED_MOD_PRINT 112
  259. #define MAX_BYTES_PER_MOD 64
  260. static ssize_t read_file_mod_stats(struct file *file, char __user *user_buf,
  261. size_t count, loff_t *ppos)
  262. {
  263. struct mod_fail_load *mod_fail;
  264. unsigned int len, size, count_failed = 0;
  265. char *buf;
  266. int ret;
  267. u32 live_mod_count, fkreads, fdecompress, fbecoming, floads;
  268. unsigned long total_size, text_size, ikread_bytes, ibecoming_bytes,
  269. idecompress_bytes, imod_bytes, total_virtual_lost;
  270. live_mod_count = atomic_read(&modcount);
  271. fkreads = atomic_read(&failed_kreads);
  272. fdecompress = atomic_read(&failed_decompress);
  273. fbecoming = atomic_read(&failed_becoming);
  274. floads = atomic_read(&failed_load_modules);
  275. total_size = atomic_long_read(&total_mod_size);
  276. text_size = atomic_long_read(&total_text_size);
  277. ikread_bytes = atomic_long_read(&invalid_kread_bytes);
  278. idecompress_bytes = atomic_long_read(&invalid_decompress_bytes);
  279. ibecoming_bytes = atomic_long_read(&invalid_becoming_bytes);
  280. imod_bytes = atomic_long_read(&invalid_mod_bytes);
  281. total_virtual_lost = ikread_bytes + idecompress_bytes + ibecoming_bytes + imod_bytes;
  282. size = MAX_PREAMBLE + min((unsigned int)(floads + fbecoming),
  283. (unsigned int)MAX_FAILED_MOD_PRINT) * MAX_BYTES_PER_MOD;
  284. buf = kzalloc(size, GFP_KERNEL);
  285. if (buf == NULL)
  286. return -ENOMEM;
  287. /* The beginning of our debug preamble */
  288. len = scnprintf(buf, size, "%25s\t%u\n", "Mods ever loaded", live_mod_count);
  289. len += scnprintf(buf + len, size - len, "%25s\t%u\n", "Mods failed on kread", fkreads);
  290. len += scnprintf(buf + len, size - len, "%25s\t%u\n", "Mods failed on decompress",
  291. fdecompress);
  292. len += scnprintf(buf + len, size - len, "%25s\t%u\n", "Mods failed on becoming", fbecoming);
  293. len += scnprintf(buf + len, size - len, "%25s\t%u\n", "Mods failed on load", floads);
  294. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Total module size", total_size);
  295. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Total mod text size", text_size);
  296. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Failed kread bytes", ikread_bytes);
  297. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Failed decompress bytes",
  298. idecompress_bytes);
  299. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Failed becoming bytes", ibecoming_bytes);
  300. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Failed kmod bytes", imod_bytes);
  301. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Virtual mem wasted bytes", total_virtual_lost);
  302. if (live_mod_count && total_size) {
  303. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Average mod size",
  304. DIV_ROUND_UP(total_size, live_mod_count));
  305. }
  306. if (live_mod_count && text_size) {
  307. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Average mod text size",
  308. DIV_ROUND_UP(text_size, live_mod_count));
  309. }
  310. /*
  311. * We use WARN_ON_ONCE() for the counters to ensure we always have parity
  312. * for keeping tabs on a type of failure with one type of byte counter.
  313. * The counters for imod_bytes does not increase for fkreads failures
  314. * for example, and so on.
  315. */
  316. WARN_ON_ONCE(ikread_bytes && !fkreads);
  317. if (fkreads && ikread_bytes) {
  318. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Avg fail kread bytes",
  319. DIV_ROUND_UP(ikread_bytes, fkreads));
  320. }
  321. WARN_ON_ONCE(ibecoming_bytes && !fbecoming);
  322. if (fbecoming && ibecoming_bytes) {
  323. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Avg fail becoming bytes",
  324. DIV_ROUND_UP(ibecoming_bytes, fbecoming));
  325. }
  326. WARN_ON_ONCE(idecompress_bytes && !fdecompress);
  327. if (fdecompress && idecompress_bytes) {
  328. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Avg fail decomp bytes",
  329. DIV_ROUND_UP(idecompress_bytes, fdecompress));
  330. }
  331. WARN_ON_ONCE(imod_bytes && !floads);
  332. if (floads && imod_bytes) {
  333. len += scnprintf(buf + len, size - len, "%25s\t%lu\n", "Average fail load bytes",
  334. DIV_ROUND_UP(imod_bytes, floads));
  335. }
  336. /* End of our debug preamble header. */
  337. /* Catch when we've gone beyond our expected preamble */
  338. WARN_ON_ONCE(len >= MAX_PREAMBLE);
  339. if (list_empty(&dup_failed_modules))
  340. goto out;
  341. len += scnprintf(buf + len, size - len, "Duplicate failed modules:\n");
  342. len += scnprintf(buf + len, size - len, "%25s\t%15s\t%25s\n",
  343. "Module-name", "How-many-times", "Reason");
  344. mutex_lock(&module_mutex);
  345. list_for_each_entry_rcu(mod_fail, &dup_failed_modules, list) {
  346. if (WARN_ON_ONCE(++count_failed >= MAX_FAILED_MOD_PRINT))
  347. goto out_unlock;
  348. len += scnprintf(buf + len, size - len, "%25s\t%15lu\t%25s\n", mod_fail->name,
  349. atomic_long_read(&mod_fail->count), mod_fail_to_str(mod_fail));
  350. }
  351. out_unlock:
  352. mutex_unlock(&module_mutex);
  353. out:
  354. ret = simple_read_from_buffer(user_buf, count, ppos, buf, len);
  355. kfree(buf);
  356. return ret;
  357. }
  358. #undef MAX_PREAMBLE
  359. #undef MAX_FAILED_MOD_PRINT
  360. #undef MAX_BYTES_PER_MOD
  361. static const struct file_operations fops_mod_stats = {
  362. .read = read_file_mod_stats,
  363. .open = simple_open,
  364. .owner = THIS_MODULE,
  365. .llseek = default_llseek,
  366. };
  367. #define mod_debug_add_ulong(name) debugfs_create_ulong(#name, 0400, mod_debugfs_root, (unsigned long *) &name.counter)
  368. #define mod_debug_add_atomic(name) debugfs_create_atomic_t(#name, 0400, mod_debugfs_root, &name)
  369. static int __init module_stats_init(void)
  370. {
  371. mod_debug_add_ulong(total_mod_size);
  372. mod_debug_add_ulong(total_text_size);
  373. mod_debug_add_ulong(invalid_kread_bytes);
  374. mod_debug_add_ulong(invalid_decompress_bytes);
  375. mod_debug_add_ulong(invalid_becoming_bytes);
  376. mod_debug_add_ulong(invalid_mod_bytes);
  377. mod_debug_add_atomic(modcount);
  378. mod_debug_add_atomic(failed_kreads);
  379. mod_debug_add_atomic(failed_decompress);
  380. mod_debug_add_atomic(failed_becoming);
  381. mod_debug_add_atomic(failed_load_modules);
  382. debugfs_create_file("stats", 0400, mod_debugfs_root, mod_debugfs_root, &fops_mod_stats);
  383. return 0;
  384. }
  385. #undef mod_debug_add_ulong
  386. #undef mod_debug_add_atomic
  387. module_init(module_stats_init);