Linux Kernel – Why No Optimized Functions Like GLIBC

glibclibrarieslinux-kernel

When I try to implement the C string library myself, I found that glibc and the Linux kernel have a different way to implement some functions. For instance, glibc memchr and glibc strchr use some trick to speed up the function but the kernel memchr and the kernel strchr don't. Why aren't the Linux kernel functions optimized like glibc?

Best Answer

The kernel does have optimised versions of some of these functions, in the arch-specific directories; see for example the x86 implementation of memchr (see all the memchr definitions, and all the strchr definitions). The versions you found are the fallback generic versions; you can spot these by looking for the protective check, #ifndef __HAVE_ARCH_MEMCHR for memchr and #ifndef __HAVE_ARCH_STRCHR for strchr.

The C library’s optimised versions do tend to used more sophisticated code, so the above doesn’t explain why the kernel doesn’t go to such great lengths to go fast. If you can find scenarios where the kernel would benefit from a more optimised version of one of these functions, I imagine a patch would be welcome (with appropriate supporting evidence, and as long as the optimised function is still understandable — see this old discussion regarding memcpy). But I suspect the kernel’s uses of these functions often won’t make it worth it; for example memcpy and related functions tend to be used on small buffers in the kernel. And never discount the speed gains from a short function which fits in cache or can be inlined...

In addition, as mentioned by Iwillnotexist Idonotexist, MMX and SSE can’t easily be used in the kernel, and many optimised versions of memory-searching or copying functions rely on those.

In many cases, the version used ends up being the compiler’s built-in version anyway, and these are heavily optimised, much more so than even the C library’s can be (for example, memcpy will often be converted to a register load and store, or even a constant store).

Related Question