Posts Tagged ‘kernel’

Performance, scalability, and real-time response from the Linux kernel

Monday, July 20th, 2009

The most interesting course, as well as the one I enjoyed most, was on the
performance, scalability and real-time response of the Linux kernel.

Paul McKenney

He opened the course by dropping a question into the unsuspecting audience:
what decades old tech can keep a multi-core busy and yet be easy to program
against. I thought Paul had the idea of a time-sharing machine in his mind, but
the solution was far easier than that: SQL. Given that the frequency increase
of the CPUs is stabilising at naught, we need to find a good way to easily
program against multi-core architectures. Something that rivals the ease of
SQL, where under the hood a lot of stuff is going on, but to the user, it
remains fairly simple. Unlike most of the other people talking about
parallelism, Paul stressed multiple times that if one does not need it, it’s
best to run single threaded. I wholeheartedly agree! On the other hand, if we
parallelise, we should be considering high-level approaches prior to trying to
get the nitty-gritty details right. So, first: get your algorithm in shape. I
think that’s a very good point, given the fact that research papers publishing
tweaks, rather than new algorithms seldom succeed in increasing the performance
with a factor or even a large percentage. Conversely, any performance lost at
the base OS level, cannot be made up by the higher levels, no matter the
algorithm. Context-switches, locks, etc. take a (more-or-less) fixed amount of
time, and that time will be spent anyhow.

The major issue with RT-processes seems that they need to interact with non-RT
processes, I/O (disk, network, etc.). As such, the RT approach has to be
applied across the entire execution stack, if we want to gdet it right.
However, we still need to keep a fair responsiveness for non-RT processes.
Essentially, Paul argues for making tradeoffs, rather that going for the
best-for-a-single-goal apporoach and ignore the rest.

The question raised was why we need to enhance performance. The answer is that
people time is much more costly than machine time these days. So it does no
lomnger pay off to get an engineer trying to enhance the solution. It should be
done automnagically as much as possible. Moreover, general solutions help to
spread the cost over multiple users.

One of the major problem when parallelising programs is that people either do
not grok the issues fully, or try to tackle the problems in the wrong order.
Paul argued that we first need to understand how we can split up the problem
into parts where there is little interaction between the data (as to avoid
excess locking). Only then can we partition the work that is done on that data.
The final step then is to determine which parts can have actual access to the
data, i.e., assign the locks. The matra that was repeated here was that
low-level details really do matter, and that it is important to get them right.
Building on this, the argument was raised what we rely on people who implement
things to have detailed knowledge of the underlying hardware. Unfortunately,
this is not always the case.

The takeaway lesson from the first lecture was this: parallel programming is
bloody hard, because it was designed that way.

Lesson 2 discussed Linux kernel programming environments dealing with: response
times, preemption inside the kernel, non-maskable interrupts, etc. Point made:
if an algorithm runs at a low level, you need interruptible locks. The kernel
comes with a broad aaray of synchronisation primitives, so it is important to
use the right primitives for the right job. For example, use locks that allow
looping in the reader if there are potentially (multiple) writers. Once more,
Paul stressed that synchronisation primitivies are not the first thing to
decide on. We should associate locks and other primitives with each data
partition (that was agreed upon earlier in the design stage). Clearly, it is
not good to have too many data partitions, as that means more locks, and a
higher risk of lock contention. The example used throughout this lesson was
that of a linked list. Should we lock the header? Lock each node? Keep the
locks in the data structure or in some hash array of locks? Key point: provide
protection for each way in which the data can be accessed! A per-cpu locking
mechanism can be used; if done right it scales pretty well.

In lesson 3, Paul tackled the performance and scalability of Linux
applications. Most frameworks (200+) that we once in use have now either faded,
merged, or discontinued. Advice is given not to use or rely on signal handlers.
POSIX primitives were discussed, as were per-thread variables, spinlocks, etc.
Important point was that the use of per-cpu state to lock onto, does not
translate well from kernel to user space. Some remarks were made about the RT
aspects of user-space applications. Should this be enforced? The issue here is
that opening RT behaviour to user-space clears the way for abuse. During the class, he used the (adapted) illustration of the blind philosophers and the elephant:

The five blind penguins and the elephant

Lesson 4 was fully dedicated to real time systems, discussing some of the
implementations in the Linux kernel for dealing with this. Main topics of the
day were timers, high-resolution and others, interrupt handlers that can be
threaded, etc. It was stressed that real time has a broad range of meanings,
going from a few nanoseconds up to 10ms, the latter amounting basically to the
context switch time. Apparently, as a first step, some parts of the kernel can
be preempted, some cannot. The consequence is a reduction of schedular latency,
but nowhere near enough for a RT system at the hiogh end of the scale. Timer
wheels were added to improve locality and queueing, but still certain cascading
operations on this data structure can take a long time. Long enough to warrant
implementing high-resolution timers using RB trees, along with preemptible
spinlocks. Still: greater power means greater responsibility, so care must be
taken. Priority inversion was discussed, and adequaltely illustrated using the
dancing processes.

Real time processes

RCU once more came to the rescue, and it was shown how this can be used in the RT scenario, with priority inversion.

In the final lesson, Paul discussed RT Linux applications.

Real time vs. the Hammer

I guess the above illustration really says it all. The class discussed the
meaning of a hard RT system, and most of use were proven wrong. In some cases
knowing that failure is imminent is more important that guaranteed making the
deadline. (This eems to have some resemblance to writing research papers.) A
combination of an accurate system that is allowed to fail and can indicate it
with a less accurate systemn that guarentees deadline meeting seems to be the
way to go. In any case, maths cannot describe RT systems in practive, and QoS
is more important that hard/soft RT distinction.

RT applications can be divided into three classes: search for life
(medical/industrial control systems), search for death (military) and search
for money (financial). In todays interconnected machine web, the slowest
machine determines the RT nature of the complete system. Multiple serialised
machines have a large impact on this fact. Funny fact: in the Linux kernel,
real time used to mean real life time, rather than deadline meeting. So beware
of the code you rely on!

Using performance counters with multi-threaded applications

Friday, May 23rd, 2008

Since a few years, there is quite good support for using performance counters on Linux machines. Examples are OProfile (which has been included in the kernel since 2.6, I think), Perfctr, and Perfmon (not to be confused with the other Perfmon, which is a SNMP based performance monitoring tool). I think Perfmon is destined to make it to the kernel source tree as well, or so I’ve heard. Yet, I have been using Perfctr since I started my research, so this post is only about that tool.

There has been talk on the Perfctr mailing list (which gets hopelessly spammed these days) for including support for multi-threaded processes, but thus far I’ve seen nothing that does what I want. So, without further ado, here’s how to patch your kernel to support multi-threaded applications.

I assume you know how to install the basic Perfctr driver, and compile your kernel to add support for it. If possible, compile it as a module, as this is easiest if you need to change things (unless you also change stuff in the kernel header files, in which case you probably want to recompile the complete kernel). Let’s further assume your kernel source lives in /usr/src/linux, further referred to as toplevel. I’ll also assume we’re building the Perfctr module here.

The first thing that needs to be done is make sure that child processes set up their kernel data structures such that performance counter data can be stored at context switch (you want to use virtual counters, i.e., per-process counters). Therefore you need to add a function that does exactly this. We’ll call it __vperfctr_set_child_perfctr(struct task_struct*, struct task_struct*). You also want to be able to set up and empty vperfctr structure, by simply allocating space for it. So, add their existance to your toplevel/include/linux/perfctr.h file (which should be there if you patched the kernel and copied the relevant files when installing Perfctr), which should then read:

  1. #ifdef CONFIG_PERFCTR_MODULE
  2. extern struct vperfctr_stub {
  3. struct module *owner;
  4. void (*exit)(struct vperfctr*);
  5. void (*suspend)(struct vperfctr*);
  6. void (*resume)(struct vperfctr*);
  7. void (*sample)(struct vperfctr*);
  8. struct vperfctr* (*get_empty)(void);
  9. void (*set_child_perfctr) (struct task_struct*, struct task_struct*);
  10. #ifdef CONFIG_PERFCTR_CPUS_FORBIDDEN_MASK
  11. void (*set_cpus_allowed)(struct task_struct*, struct vperfctr*, cpumask_t);
  12. #endif
  13. } vperfctr_stub;
  14. extern void _vperfctr_exit(struct vperfctr*);
  15. #define _vperfctr_suspend(x) vperfctr_stub.suspend((x))
  16. #define _vperfctr_resume(x) vperfctr_stub.resume((x))
  17. #define _vperfctr_sample(x) vperfctr_stub.sample((x))
  18. #define _vperfctr_get_empty() vperfctr_stub.get_empty()
  19. #define _vperfctr_set_child_perfctr(x,y) vperfctr_stub.set_child_perfctr((x),(y))
  20. #define _vperfctr_set_cpus_allowed(x,y,z) (*vperfctr_stub.set_cpus_allowed)((x),(y),(z))
  21. #else /* !CONFIG_PERFCTR_MODULE */
  22. #define _vperfctr_exit(x) __vperfctr_exit((x))
  23. #define _vperfctr_suspend(x) __vperfctr_suspend((x))
  24. #define _vperfctr_resume(x) __vperfctr_resume((x))
  25. #define _vperfctr_sample(x) __vperfctr_sample((x))
  26. #define _vperfctr_get_empty() __vperfctr_get_empty()
  27. #define _vperfctr_set_child_perfctr(x,y) __vperfctr_set_child_perfctr((x),(y))
  28. #define _vperfctr_set_cpus_allowed(x,y,z) __vperfctr_set_cpus_allowed((x),(y),(z))
  29. #endif /* CONFIG_PERFCTR_MODULE */

In the same file you should add some code to the perfctr_copy_task(struct task_struct *, struct pt_regs *) function. Otherwise it only contains a comment stating that nothing should be done until inheritance is implemented and sets the vperfctr structure to NULL. The code for that function should become the following:

  1. static inline void perfctr_copy_task(struct task_struct *child, struct pt_regs *regs) {
  2. if(current->thread.perfctr != NULL) {
  3. child->thread.perfctr = _vperfctr_get_empty();
  4. if(!child->thread.perfctr) {
  5. printk(“PERFCTR::error activating child perfctr\n”);
  6. }
  7. else {
  8. _vperfctr_set_child_perfctr(current, child);
  9. }
  10. }
  11. else {
  12. child->thread.perfctr = NULL;
  13. }
  14. }

The above will get a new structure set up (through __vperfctr_get_empty) and copy the existing settings (i.e., for the control registers etc.) to that structure (through __vperfctr_set_child_perfctr). Before we can use these functions, we need to define them, which is done in toplevel/drivers/perfctr/virtual.c.

  1. struct vperfctr* __vperfctr_get_empty(void) {
  2. return get_empty_vperfctr();
  3. }
  4. void __vperfctr_set_child_perfctr(struct task_struct* parent, struct task_struct* child) {
  5. int err;
  6. struct vperfctr* parent_perfctr = parent->thread.perfctr;
  7. struct vperfctr* child_perfctr = child->thread.perfctr;
  8. if(!child_perfctr) { /* check should have been done before! */
  9. return;
  10. }
  11. child_perfctr->owner = child;
  12. memcpy(&(child_perfctr->cpu_state.control), &(parent_perfctr->cpu_state.control), sizeof(parent_perfctr->cpu_state.control));
  13. child_perfctr->si_signo = parent_perfctr->si_signo;
  14. #ifdef CONFIG_SMP
  15. child_perfctr->sampling_timer = parent_perfctr->sampling_timer;
  16. #endif
  17. err = perfctr_cpu_update_control(&child_perfctr->cpu_state, 0);
  18. if(err < 0) {
  19. printk(“perfctr::error::__vperfctr_set_child cstatus < 0 “);
  20. }
  21. }

I think the Perfctr patch uses p->thread as the first argument, so change this accordingly.

Now, to get the counter values assembled in one central spot, I’m using a second module that accumulates these values. Upon exit, each thread will pass on their values to that module through a hook. The code has protection for usage on multicore processors, through a spin_lock.

Here’s the code you should add to toplevel/drivers/perfctr/virtual.c to be able to access the accumulating module through the hook.

  • void (*__read_counter_update)(int nrctrs, int* events, long long* counters_values) = NULL;
  • int __vperfctr_set_read_counter_hook(void f_address(int, int*, long long*)) {
  • __read_counter_update = f_address;
  • return 0;
  • }
  • EXPORT_SYMBOL(__vperfctr_set_read_counter_hook);
  • int __vperfctr_unset_read_counter_hook(void f_address(int, int*, long long*)) {
  • __read_counter_update = NULL;
  • return 0;
  • }
  • EXPORT_SYMBOL(__vperfctr_unset_read_counter_hook);
  • static void vperfctr_unlink(struct task_struct *owner, struct vperfctr *perfctr) {
  • /* this synchronises with vperfctr_ioctl() */
  • spin_lock(&perfctr->owner_lock);
  • perfctr->owner = NULL;
  • spin_unlock(&perfctr->owner_lock);
  • /* perfctr suspend+detach must be atomic wrt process suspend */
  • /* this also synchronises with perfctr_set_cpus_allowed() */
  • vperfctr_task_lock(owner);
  • if( IS_RUNNING(perfctr) &&owner == current )
  • vperfctr_suspend(perfctr);
  • owner->thread.perfctr = NULL;
  • vperfctr_task_unlock(owner);
  • if(__read_counter_update) {
  • int nractrs = perfctr_cstatus_nractrs(perfctr->cpu_state.cstatus);
  • long long counters [nractrs+1];
  • int events[nractrs+1];
  • int i = 0;
  • for(i = 0; i < nractrs; i++) {
  • events[i] = perfctr->cpu_state.control.evntsel[i];
  • counters[i] = perfctr->cpu_state.pmc[i].sum;
  • }
  • events[nractrs] = -1;
  • counters[nractrs] = perfctr->cpu_state.tsc_sum;
  • __read_counter_update(nractrs, events, counters);
  • }
  • perfctr->cpu_state.cstatus = 0;
  • vperfctr_clear_iresume_cstatus(perfctr);
  • put_vperfctr(perfctr);
  • }
  • The final piece then is the read_counter module where the data is accumulated.

    1. #include >linux/version.h<
    2. #include >linux/vermagic.h<
    3. #include >linux/init.h<
    4. #include >linux/module.h<
    5. #include >linux/kernel.h<
    6. #include >linux/fs.h<
    7. #include >linux/major.h<
    8. #include >linux/errno.h<
    9. #include >asm/uaccess.h<
    10. #include >asm/io.h<
    11. #include >linux/spinlock.h<
    12. MODULE_INFO(vermagic, VERMAGIC_STRING);
    13. #define READ_COUNTERS_DEV 120 /* major number */
    14. #undef unix
    15. struct module __this_module
    16. __attribute__((section(“.gnu.linkonce.this_module”))) = {
    17. .name = __stringify(read_counters),
    18. .init = init_module,
    19. #ifdef CONFIG_MODULE_UNLOAD
    20. .exit = cleanup_module,
    21. #endif
    22. struct counter_info_s {
    23. long long ctrs[9];
    24. int nractrs;
    25. int events[9];
    26. spinlock_t lock;
    27. static struct counter_info_s counters;
    28. void __read_counters_update(int nractrs, int* events, long long* cntrs) {
    29. int i = 0;
    30. spin_lock(&counters.lock);
    31. counters.nractrs = nractrs;
    32. for(i = 0; i < nractrs; ++i) {
    33. counters.ctrs[i] += cntrs[i];
    34. }
    35. spin_unlock(&counters.lock);
    36. }
    37. static int read_counters_open(struct inode* inode, struct file* file) {
    38. printk(“read_counters OPEN\n”);
    39. return 0;
    40. }
    41. static int read_counters_close(struct file* file) {
    42. printk(“read_counters CLOSE\n”);
    43. return 0;
    44. }
    45. static ssize_t read_counters_read(struct file* file, char* buf, size_t count, loff_t *ppos) {
    46. int i = 0;
    47. int res = 0;
    48. res = copy_to_user((void*) buf, (void*) &counters, count);
    49. if(!res) {
    50. /* we reset the counters values at this point */
    51. for(i = 0; i <= counters.nractrs; ++i) {
    52. counters.ctrs[i] = 0;
    53. }
    54. return 0;
    55. }
    56. return -EFAULT;
    57. }
    58. static ssize_t read_counters_write(struct file* file, const char* buf, size_t count, loff_t* ppos) {
    59. return 0;
    60. }
    61. static int read_counters_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) {
    62. int i;
    63. int res;
    64. /* we have the following legal actions that can be asked
    65. * read: reads the counters
    66. * reset: sets the captured values to zero
    67. *
    68. * cmd is encoded to contain both the desired action (first byte)
    69. * as well as the length of the buffer (last 3 bytes)
    70. */
    71. int action = cmd & 0xff0000;
    72. int count = cmd & 0×0000ff;
    73. switch(action) {
    74. case 0: /* reset */
    75. spin_lock(&counters.lock);
    76. for(i = 0; i <= counters.nractrs; i++) {
    77. counters.ctrs[i] = 0;
    78. counters.events[i] = 0;
    79. }
    80. spin_unlock(&counters.lock);
    81. break;
    82. case 1: /* read */
    83. spin_lock(&counters.lock);
    84. {
    85. char tmp [(counters.nractrs+1)*sizeof(long long)+sizeof(int)];
    86. long long*tmp_counters = (long long*) (tmp+sizeof(int));
    87. *(int*)tmp = counters.nractrs;
    88. for(i = 0; i <= counters.nractrs; ++i) {
    89. *(tmp_counters+i) = counters.ctrs[i];
    90. }
    91. if(count < (counters.nractrs+1)*sizeof(long long)+sizeof(int)) {
    92. res = -EFAULT;
    93. } else {
    94. /*
    95. * we expect arg to contain the address of a
    96. * structure where the counter values can be dropped
      >li class=”indent5″> */

    97. res = (copy_to_user((void*) arg, tmp, (counters.nractrs+1)*sizeof(long long)+sizeof(int)) ? -EFAULT : 0);
    98. }
    99. }
    100. spin_unlock(&counters.lock);
    101. return res;
    102. break;
    103. }
    104. return -1;
    105. }
    106. static struct file_operations read_counters_fops = {
    107. .read = read_counters_read, /* read */
    108. .write = read_counters_write, /* write */
    109. .ioctl = read_counters_ioctl, /* ioctl */
    110. .open = read_counters_open, /* open */
    111. .flush = read_counters_close, /* close */
    112. };
    113. extern int __vperfctr_set_read_counter_hook(void (*f)(int, int*, long long*));
    114. extern int __vperfctr_unset_read_counter_hook(void);
    115. int init_module(void) {
    116. int i = 0;
    117. /* find a symbol called __vperfctr_set_read_counter_hook */
    118. /* if it doesn’t exist, let insmod handle it! :-) */
    119. __vperfctr_set_read_counter_hook(__read_counters_update);
    120. for(i =0; i < 9; ++i) {
    121. counters.ctrs[i] = 0LL;
    122. counters.events[i] = 0;
    123. }
    124. if(register_chrdev(READ_COUNTERS_DEV, “read_counters”, &read_counters_fops) == -EBUSY) {
    125. printk(“READ_COUNTERS device: unable to connect to major number %d\n”, READ_COUNTERS_DEV);
    126. return -EIO;
    127. }
    128. else {
    129. printk(“READ_COUNTERS device installed.\n”);
    130. }
    131. return 0;
    132. }
    133. void cleanup_module(void) {
    134. __vperfctr_unset_read_counter_hook();
    135. if(unregister_chrdev(READ_COUNTERS_DEV, “read_counters”)) {
    136. printk(“READ_COUNTERS device: unable to release device %d\n”, READ_COUNTERS_DEV);
    137. }
    138. else {
    139. printk(“READ_COUNTERS device driver removed\n”);
    140. }
    141. }
    142. MODULE_LICENSE(“GPL”);

    If you wish to read the data, you must create the device /dev/read_counters with major number 120 and minor number 0. Code that does the reading for you might look like this:

    1. #include <sys/types.h>
    2. #include <sys/stat.h>
    3. #include <fcntl.h>
    4. #include <linux/spinlock.h>
    5. struct counter_info_s {
    6. long long ctrs[9];
    7. int nractrs;
    8. int events[9];
    9. spinlock_t lock;
    10. };
    11. struct counter_info_s counters;
    12. int main() {
    13. int file = open(“/dev/read_counters”, O_RDONLY);
    14. if(file < 0) {
    15. perror(“open”);
    16. exit(-1);
    17. }
    18. if(read(file, (void*) &counters, sizeof(struct counter_info_s), 0)) {
    19. perror(“oops. read error.”);
    20. exit(-1);
    21. }
    22. else {
    23. int i = 0;
    24. printf(“read succesfull\n”);
    25. printf(“counters.nractrs = %d\n”, counters.nractrs);
    26. for(i = 0; i < counters.nractrs; ++i) {
    27. printf(“counters.ctrs[%d] = %lld\n”, i, counters.ctrs[i]);
    28. }
    29. exit(0);
    30. }
    31. }