use futex in user space? - linux

I need functionality of do_futex() call in user space outside of lock/unlock context. I.e., I do not need a mutex, but the exact semantics of the kernel call do_futex.
It would seem it should be available in user space, since the intent was to minimize the number of system calls, but I can't link with it.
Or is there a syscall?
Update:
I'm currently using syscall(__NR_futex, ...) to run do_futex(). But
I have to include to get __NR_futex, which is ugly
I have to include to get FUTEX_WAIT and FUTEX_WAKE, but I still don't get EWOULDBLOCK, or the maximum number of threads for WAKE
Is there a coherent wrapper?

As it's said on http://locklessinc.com/articles/obscure_synch/:
Finally, in order to block on a kernel wait-list, we need to use the Futex system call, which unfortunately isn't exposed by linux/futex.h.
And they define their own simple wrapper:
#include <linux/futex.h>
#include <sys/syscall.h>
static long sys_futex(void *addr1, int op, int val1, struct timespec *timeout,
void *addr2, int val3) {
return syscall(SYS_futex, addr1, op, val1, timeout, addr2, val3);
}

futex(2) system call is probably what you are looking for.
man 2 futex
Also, on side note, man syscalls gives list of all system calls.

Related

Can I block a new process execution using Kprobe?

Kprobe has a pre-handler function vaguely documented as followed:
User's pre-handler (kp->pre_handler)::
#include <linux/kprobes.h>
#include <linux/ptrace.h>
int pre_handler(struct kprobe *p, struct pt_regs *regs);
Called with p pointing to the kprobe associated with the breakpoint,
and regs pointing to the struct containing the registers saved when
the breakpoint was hit. Return 0 here unless you're a Kprobes geek.
I was wondering if one can use this function (or any other Kprobe feature) to prevent a process from being executed \ forked.
As documented in the kernel documentation, you can change the execution path by changing the appropriate register (e.g., IP register in x86):
Changing Execution Path
-----------------------
Since kprobes can probe into a running kernel code, it can change the
register set, including instruction pointer. This operation requires
maximum care, such as keeping the stack frame, recovering the execution
path etc. Since it operates on a running kernel and needs deep knowledge
of computer architecture and concurrent computing, you can easily shoot
your foot.
If you change the instruction pointer (and set up other related
registers) in pre_handler, you must return !0 so that kprobes stops
single stepping and just returns to the given address.
This also means post_handler should not be called anymore.
Note that this operation may be harder on some architectures which use
TOC (Table of Contents) for function call, since you have to setup a new
TOC for your function in your module, and recover the old one after
returning from it.
So you might be able to block a process' execution by jumping over some code. I wouldn't recommend it; you're more likely to cause a kernel crash than to succeed in stopping the execution of a new process.
seccomp-bpf is probably better suited for your use case. This StackOverflow answer gives you all the information you need to leverage seccomp-bpf.

get pthread_t from thread id

I am unable to find a function to convert a thread id (pid_t) into a pthread_t which would allow me to call pthread_cancel() or pthread_kill().
Even if pthreads doesn't provide one is there a Linux specific function?
I don't think such a function exists but I would be happy to be corrected.
Background
I am well aware that it is usually preferable to have threads manage their own lifetimes via condition variables and the like.
This use is for testing purposes. I am trying to find a way to test how an application behaves when one of its threads 'dies'. So I'm really looking for a way to kill a thread. Using syscall(tgkill()) kills the process, so instead I provided a means for a tester to give the process the id of the thread to kill. I now need to turn that id into a pthread_t so that I can then:
use pthread_kill(tid,0) to check for its existence followed by
calling pthread_kill() or pthread_cancel() as appropriate.
This is probably taking testing to an unnecessary extreme. If I really want to do that some kind of mock pthreads implementation might be better.
Indeed if you really want robust isolation you are typically better off using processes rather than threads.
I don't think such a function exists but I would be happy to be corrected.
As a workaround I can create a table mapping &pthread_t to pid_t and ensure that I always invoke pthread_create() via a wrapper that adds an entry to this table. This works very well and allows me to convert an OS thread id to a pthread_t which I can then terminate using pthread_cancel(). Here is a snippet of the mechanism:
typedef void* (*threadFunc)(void*);
static void* start_thread(void* arg)
{
threadFunc threadRoutine = routine_to_start;
record_thread_start(pthread_self(),syscall(SYS_gettid));
routine_to_start = NULL; //let creating thread know its safe to continue
return threadRoutine(arg);
}
Sensible conversion requires there to be a 1:1 mapping between pthread_t and pid_t tid, which is the case with NPTL, but hasn't always been the case, and won't be the case on every pthread platform. That said...
Two options:
A) override the actual pthread_create, using LD_PRELOAD and dlsym, and keep track of each pthread_t and their corresponding pid_t there. To get the thread pid_t you can either take advantage of the pthread private headers to de-opaque the pthread_t and access the pid_t inside there, or if you want to stick to documented APIs pthread_sigqueue each pthread_t thread as it is created and have a sigaction signal handler call gettid and pass you back the thread pid_t, with appropriate synchronisation between your new pthread_create and the signal handler[1].
B) You can read the all of the thread pid_t from /proc/<process pid_t>/task/. Then use the SYS_rt_tgsigqueueinfo[2] syscall to implement a new function thread_sigqueue, a pid_t variant of pthread_sigqueue so that you can signal the pid_t thread, and from the sigaction signal handler call pthread_self passing out the value with suitable synchronization, etc.
Notes:
1 - I think it's worth writing 2 executeOnThread variants (one for pthread_t and one for pid_t style thread ids) that take a std::function<void()> (for C++), or a void(*)(void*) function pointer and void* parameter (for C), and SIGUSR1 that thread to execute the passed function in a sigaction that you also setup to perform relevant synchronization with the calling thread. It's handy to be able to use the thread-dependent APIs like pthread_self, gettid, backtrace, getrusage, etc. without devising a custom execution scheme each time.
2 - SYS_rt_tgsigqueueinfo is a low level syscall meant for implementing sigqueue/pthread_sigqueue, rather than application use, but is still a documented API, and we're using it to implement another variant of sigqueue, so fair game IMHO.

Alternate to setpriority(PRIO_PROCESS, thread_id, priority)

Given - Thread id of a thread.
Requirement - Set Linux priority of the thread id.
Constraint - Cant use setpriority()
I have tried to use below
pthread_setschedprio(pthread_t thread, int prio);
pthread_setschedparam(pthread_t thread, int policy,
const struct sched_param *param);
Both the above APIs use pthread_t as an argument. I am not able to construct (typecast) pthread_t from thread id. I understand converting this is not possible due to different types.
Is there a way to still accomplish this ?
Some aspects of the pthread_setschedprio interface are available for plain thread IDs with the sched_setparam function (declared in <thread.h>). The sched_setparam manual page says that the process is affected (which is the POSIX-mandated behavior), but on Linux, it's actually the thread of that ID.
Keep in mind that calling sched_setparam directly may break the behavior expected from PI mutexes and other synchronization primitives because the direct call does not perform the additional bookkeeping performed by the pthread_* functions.

How to run hrtimer handler in softirq context?

I have found this tutorial about hrtimer:
http://www.ibm.com/developerworks/linux/library/l-timers-list/
I believe the way it uses will run the callback handler in hardirq context,right? But it also said "One interesting aspect is the ability to define the execution context of the callback function (such as in softirq or hardiirq context)"
I have checked the hrtimer.h file but it's really not that intuitive. Does anyone know how to run it in softirq context? Is it similiar to run it in hardirq?
Thanks,
This information is regarding an old kernel - in recent releases this feature have been removed to reduce the code complexity and avoid bugs. Now hrtimer always runs in hardirq context with disabled IRQs.
One possible approach is to use a tasklet_hrtimer
#include <linux/interrupt.h>
struct tasklet_hrtimer mytimer;
enum hrtimer_restart callback(struct hrtimer *t) {
struct tasklet_hrtimer *mytime=container_of(t,struct tasklet_hrtimer,timer);
...
}
...
tasklet_hrtimer_init(&mytimer,callback,clock,mode);
tasklet_hrtimer_start(&mytimer,time,mode);
...
In the example above you should replace clock, mode and time with appropriate values.
If you want to pass data to your callback, then you have to embed the tasklet_hrtimer variable in some struct of yours and use the container_of trick to get to your data.
Not quite apparently, your struct will contain a tasklet_hrtimer, which will contain a hrtimer struct. When you get a pointer to the inner most element and you know that it have a fixed offset from the parent element, you can get to the parent.

pthread concepts in linux

I have some questions about pthreads in linux:
Is it the case that pthread_t is it a datatype similar to int and char indicating we are defining a thread?
If so, how much size does it take? 2 bytes or 4 bytes?
Does the compiler allocate memory to pthread_t thread1 immediately after that statement or does it wait until it a pthread_create() call?
How does one set the thread attributes, and what is their typical use?
Can one only pass more than one argument in the pthread_create() call? If so, how?
I have lots of things on my mind like this. Please also feel free to suggest any good sites or documents to read.
Answering the questions one by one, though not necessarily in the same order:
Is pthread_t a data type similar to int or char, indicating we are defining a thread ? Does the compiler allocate memory to pthread_t thread1 immediately after that sentence or does it wait until it finds the pthread_create() call
pthread_t is a type similar to int and it's created when you define it, not when you call pthread_create. In the snippet:
pthread_t tid;
int x = pthread_create (&tid, blah, blah, blah);
it's the first line that creates the variable, although it doesn't hold anything useful until the return from pthread_create.
How much size does a pthread_t take, 2 bytes or 4 bytes?
You shouldn't care how much space it takes, any more than you should care how much space is taken by a FILE structure. You should just use the structure as intended. If you really want to know, then sizeof is your friend.
Any good information about how to set the thread attributes?
If you want to use anything other than default attributes, you have to create an attributes variable first and then pass that to the pthread_create call.
Can we only pass one argument in the pthread_create function to the function? Can't we send 2 or 3 arguments in the pthread_create() function to the called thread?
While you're only allowed to pass one extra parameter to the thread , there's nothing stopping you from making this one parameter a pointer to a structure holding a hundred different things.
If you're looking for information on how to use pthreads, there's plenty of stuff at the end of a Google search but I still prefer the dead-tree version myself:
how much size does it take
pthread_t uses sizeof pthread_t bytes.
and we can only pass one argument in the pthread_create to the function not more than one? cant we send 2 or 3 arguments in the pthread_create() function to the called thread?
All you need is one argument. All you get is one argument. It's a void * so you can pass a pointer to whatever you want. Such as a structure containing multiple values.
i have lots of things on my mind like this suggest any good sites or documents to read
Have a look at the pthread man pages, online or in your shell of choice (man pthread, man pthread_create, etc.). I started out reading some basic lecture slides (here's the sequel).
pthread_t could be any number of bytes. It could be a char, an int, a pointer, or a struct... But you neither need to know nor to care. If you need the size for allocation purposes, you use sizeof(pthread_t). The only type of variable you can assign it to is another pthread_t.
The compiler may or may not allocate the resources associated with the thread when you define a pthread_t. Again, you do not need to know nor to care, because you are required to call pthread_join (or pthread_detach) on any thread you create. As long as you follow the rules, the system will make sure it does not leak memory (or any other resource).
Attributes are admittedly a bit clumsy. They are held in an pthread_attr_t object, which again could be represented as an integer, pointer, or entire struct. You have to initialize it with pthread_attr_init and destroy it with pthread_attr_destroy. Between those two, you use various pthread_attr_... calls to set or clear attributes, and then you can pass it as part of one or more pthread_create calls to set the attributes of the new threads.
Different implementations can and will handle all of these things differently.
LLNL has a decent set of introductory information.
Look into pthread.h file to get more information. On my system, pthread_t is defined as an unsigned long int. But I guess this is platform dependent, since it is defined into bits/pthreadtype.h.

Resources