1
0
mirror of https://github.com/bashrc/LKMPG.git synced 2018-06-11 03:06:54 +02:00

Likely and unlikely

This commit is contained in:
Bob Mottram
2017-07-12 18:40:57 +01:00
parent cf687bc069
commit 31a53cee1f
2 changed files with 333 additions and 281 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -4099,6 +4099,22 @@ MODULE_DESCRIPTION("Linux Device Model example");
module_init(devicemodel_init);
module_exit(devicemodel_exit);
#+end_src
* Optimisations
** Likely and Unlikely conditions
Sometimes you might want your code to run as quickly as possible, especially if it's handling an interrupt or doing something which might cause noticible latency. If your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either /true/ or /false/, then you can allow the compiler to optimise for this using the /likely/ and /unlikely/ macros.
For example, when allocating memory you're almost always expecting this to succeed.
#+begin_src C
bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
if (unlikely(!bvl)) {
mempool_free(bio, bio_pool);
bio = NULL;
goto out;
}
#+end_src
When the /unlikely/ macro is used the compiler alters its machine instruction output so that it continues along the false branch and only jumps if the condition is true. That avoids flushing the processor pipeline. The opposite happens if you use the /likely/ macro.
* Common Pitfalls
Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.