Loop a command in VxWorks at a certain frequency - shell

I am attempting to loop a command in VxWorks around 6Hz, I cannot compile code for the target in question so I have to use existing VxWorks shell commands
I have tried:
repeat(1000,functionX,param1,param2,param3)
This works well at repeating the command 1000 times but wont give me the frequency I require
As a comprimise I looked at:
period()
as this is capable of giving me 1hz calls on the function (which might be acceptable) however I cannot work out how to enter the required parameters into the FunctionX
I have tried both:
period(1,functionX,param1,param2,param3)
and
period(1,functionX(param1,param2,param3))
with no luck
Any Ideas on how to acheive the 6Hz rate for FunctionX would be great but if that is not possible without compiling some code then I will settle for a way of getting the period command to work with parameters in the function I am calling

Repeat and period have the same signatures, but the interpretation of the first parameter is different. So if you can call repeat successfully then you can also call period successfully.
int period
(
int secs, /* period in seconds */
FUNCPTR func, /* function to call repeatedly */
int arg1, /* first of eight args to pass to func */
int arg2,
int arg3,
int arg4,
int arg5,
int arg6,
int arg7,
int arg8
)
int repeat
(
int n, /* no. of times to call func (0=forever) */
FUNCPTR func, /* function to call repeatedly */
int arg1, /* first of eight args to pass to func */
int arg2,
int arg3,
int arg4,
int arg5,
int arg6,
int arg7,
int arg8
)
For repeat the first parameter, is the number of times to call the function, and for period the first parameter is the period in seconds
So period is really too slow for you, and repeat is too fast, though you could use tickGet to make it work. What you really want is a vxworks watchdog. Lookup wdCreate() and wdStart() in your vxworks docs, but be aware that your watchdog handler will be called from an ISR, and so standard ISR precautions should be taken (i.e. you will need a task to do the real work which should pend on a msgQ, or a semaphore that your watchdog handler triggers).
Actually now that I think about it, I believe that repeat and period also call the handler from an ISR, so technically the same restrictions apply there as well.

Related

Trap memory accesses inside a standard executable built with MinGW

So my problem sounds like this.
I have some platform dependent code (embedded system) which writes to some MMIO locations that are hardcoded at specific addresses.
I compile this code with some management code inside a standard executable (mainly for testing) but also for simulation (because it takes longer to find basic bugs inside the actual HW platform).
To alleviate the hardcoded pointers, i just redefine them to some variables inside the memory pool. And this works really well.
The problem is that there is specific hardware behavior on some of the MMIO locations (w1c for example) which makes "correct" testing hard to impossible.
These are the solutions i thought of:
1 - Somehow redefine the accesses to those registers and try to insert some immediate function to simulate the dynamic behavior. This is not really usable since there are various ways to write to the MMIO locations (pointers and stuff).
2 - Somehow leave the addresses hardcoded and trap the illegal access through a seg fault, find the location that triggered, extract exactly where the access was made, handle and return. I am not really sure how this would work (and even if it's possible).
3 - Use some sort of emulation. This will surely work, but it will void the whole purpose of running fast and native on a standard computer.
4 - Virtualization ?? Probably will take a lot of time to implement. Not really sure if the gain is justifiable.
Does anyone have any idea if this can be accomplished without going too deep? Maybe is there a way to manipulate the compiler in some way to define a memory area for which every access will generate a callback. Not really an expert in x86/gcc stuff.
Edit: It seems that it's not really possible to do this in a platform independent way, and since it will be only windows, i will use the available API (which seems to work as expected). Found this Q here:
Is set single step trap available on win 7?
I will put the whole "simulated" register file inside a number of pages, guard them, and trigger a callback from which i will extract all the necessary info, do my stuff then continue execution.
Thanks all for responding.
I think #2 is the best approach. I routinely use approach #4, but I use it to test code that is running in the kernel, so I need a layer below the kernel to trap and emulate the accesses. Since you have already put your code into a user-mode application, #2 should be simpler.
The answers to this question may provide help in implementing #2. How to write a signal handler to catch SIGSEGV?
What you really want to do, though, is to emulate the memory access and then have the segv handler return to the instruction after the access. This sample code works on Linux. I'm not sure if the behavior it is taking advantage of is undefined, though.
#include <stdint.h>
#include <stdio.h>
#include <signal.h>
#define REG_ADDR ((volatile uint32_t *)0x12340000f000ULL)
static uint32_t read_reg(volatile uint32_t *reg_addr)
{
uint32_t r;
asm("mov (%1), %0" : "=a"(r) : "r"(reg_addr));
return r;
}
static void segv_handler(int, siginfo_t *, void *);
int main()
{
struct sigaction action = { 0, };
action.sa_sigaction = segv_handler;
action.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &action, NULL);
// force sigsegv
uint32_t a = read_reg(REG_ADDR);
printf("after segv, a = %d\n", a);
return 0;
}
static void segv_handler(int, siginfo_t *info, void *ucontext_arg)
{
ucontext_t *ucontext = static_cast<ucontext_t *>(ucontext_arg);
ucontext->uc_mcontext.gregs[REG_RAX] = 1234;
ucontext->uc_mcontext.gregs[REG_RIP] += 2;
}
The code to read the register is written in assembly to ensure that both the destination register and the length of the instruction are known.
This is how the Windows version of prl's answer could look like:
#include <stdint.h>
#include <stdio.h>
#include <windows.h>
#define REG_ADDR ((volatile uint32_t *)0x12340000f000ULL)
static uint32_t read_reg(volatile uint32_t *reg_addr)
{
uint32_t r;
asm("mov (%1), %0" : "=a"(r) : "r"(reg_addr));
return r;
}
static LONG WINAPI segv_handler(EXCEPTION_POINTERS *);
int main()
{
SetUnhandledExceptionFilter(segv_handler);
// force sigsegv
uint32_t a = read_reg(REG_ADDR);
printf("after segv, a = %d\n", a);
return 0;
}
static LONG WINAPI segv_handler(EXCEPTION_POINTERS *ep)
{
// only handle read access violation of REG_ADDR
if (ep->ExceptionRecord->ExceptionCode != EXCEPTION_ACCESS_VIOLATION ||
ep->ExceptionRecord->ExceptionInformation[0] != 0 ||
ep->ExceptionRecord->ExceptionInformation[1] != (ULONG_PTR)REG_ADDR)
return EXCEPTION_CONTINUE_SEARCH;
ep->ContextRecord->Rax = 1234;
ep->ContextRecord->Rip += 2;
return EXCEPTION_CONTINUE_EXECUTION;
}
So, the solution (code snippet) is as follows:
First of all, i have a variable:
__attribute__ ((aligned (4096))) int g_test;
Second, inside my main function, i do the following:
AddVectoredExceptionHandler(1, VectoredHandler);
DWORD old;
VirtualProtect(&g_test, 4096, PAGE_READWRITE | PAGE_GUARD, &old);
The handler looks like this:
LONG WINAPI VectoredHandler(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
static DWORD last_addr;
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) {
last_addr = ExceptionInfo->ExceptionRecord->ExceptionInformation[1];
ExceptionInfo->ContextRecord->EFlags |= 0x100; /* Single step to trigger the next one */
return EXCEPTION_CONTINUE_EXECUTION;
}
if (ExceptionInfo->ExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP) {
DWORD old;
VirtualProtect((PVOID)(last_addr & ~PAGE_MASK), 4096, PAGE_READWRITE | PAGE_GUARD, &old);
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_CONTINUE_SEARCH;
}
This is only a basic skeleton for the functionality. Basically I guard the page on which the variable resides, i have some linked lists in which i hold pointers to the function and values for the address in question. I check that the fault generating address is inside my list then i trigger the callback.
On first guard hit, the page protection will be disabled by the system, but i can call my PRE_WRITE callback where i can save the variable state. Because a single step is issued through the EFlags, it will be followed immediately by a single step exception (which means that the variable was written), and i can trigger a WRITE callback. All the data required for the operation is contained inside the ExceptionInformation array.
When someone tries to write to that variable:
*(int *)&g_test = 1;
A PRE_WRITE followed by a WRITE will be triggered,
When i do:
int x = *(int *)&g_test;
A READ will be issued.
In this way i can manipulate the data flow in a way that does not require modifications of the original source code.
Note: This is intended to be used as part of a test framework and any penalty hit is deemed acceptable.
For example, W1C (Write 1 to clear) operation can be accomplished:
void MYREG_hook(reg_cbk_t type)
{
/** We need to save the pre-write state
* This is safe since we are assured to be called with
* both PRE_WRITE and WRITE in the correct order
*/
static int pre;
switch (type) {
case REG_READ: /* Called pre-read */
break;
case REG_PRE_WRITE: /* Called pre-write */
pre = g_test;
break;
case REG_WRITE: /* Called after write */
g_test = pre & ~g_test; /* W1C */
break;
default:
break;
}
}
This was possible also with seg-faults on illegal addresses, but i had to issue one for each R/W, and keep track of a "virtual register file" so a bigger penalty hit. In this way i can only guard specific areas of memory or none, depending on the registered monitors.

Using MPI_Wtime() in Openmpi

I am trying to measure the runtime of an mpi programm. I am running it with different number of processes to compare the runtime later.
After calling MPI_Init() I call and save the value of MPI_WTime() in a value.
Before calling MPI_Finalize() I call MPI_WTime and save its value some in another variable.
After MPI_Finalize I subtract the two values of MPI_WTime().
My program looks like this:
int main(int argc, char* argv[]){
double start, end;
MPI_Init(&argc, &argv);
start = MPI_Wtime();
//Do something.......
end = MPI_Wtime();
MPI_Finalize();
if(rank==0){
printf("Runtime=%d\n", end-start);
}
}
This works. The problem is just the results I get. Unfortunately I get no seconds. Running the Program with one process returns a number like this : 41291472 and running the program with 64 processes returns 1978567624.
These values are no seconds! How can I convert them to seconds?
This should do the trick:
printf("Runtime=%f\n", end-start);
Your start and end variables are doubles, so the result of end - start is also a double value. You need to use to correct format specifier in printf, which is %f for floating point values. Using d will interpret the result as an integer and you'll only get garbage.
Mort's answer is correct. I only wanted to add that MPI_Wtime does not return an integer count of elapsed seconds. It returns a floating point value -- you know this because you declared start and end as double, but maybe you forgot when you set up your printf specifier.

How to send signal from kernel to user space

My kernel module code needs to send signal [def.] to a user land program, to transfer its execution to registered signal handler.
I know how to send signal between two user land processes, but I can not find any example online regarding the said task.
To be specific, my intended task might require an interface like below (once error != 1, code line int a=10 should not be executed):
void __init m_start(){
...
if(error){
send_signal_to_userland_process(SIGILL)
}
int a = 10;
...
}
module_init(m_start())
An example I used in the past to send signal to user space from hardware interrupt in kernel space. That was just as follows:
KERNEL SPACE
#include <asm/siginfo.h> //siginfo
#include <linux/rcupdate.h> //rcu_read_lock
#include <linux/sched.h> //find_task_by_pid_type
static int pid; // Stores application PID in user space
#define SIG_TEST 44
Some "includes" and definitions are needed. Basically, you need the PID of the application in user space.
struct siginfo info;
struct task_struct *t;
memset(&info, 0, sizeof(struct siginfo));
info.si_signo = SIG_TEST;
// This is bit of a trickery: SI_QUEUE is normally used by sigqueue from user space, and kernel space should use SI_KERNEL.
// But if SI_KERNEL is used the real_time data is not delivered to the user space signal handler function. */
info.si_code = SI_QUEUE;
// real time signals may have 32 bits of data.
info.si_int = 1234; // Any value you want to send
rcu_read_lock();
// find the task with that pid
t = pid_task(find_pid_ns(pid, &init_pid_ns), PIDTYPE_PID);
if (t != NULL) {
rcu_read_unlock();
if (send_sig_info(SIG_TEST, &info, t) < 0) // send signal
printk("send_sig_info error\n");
} else {
printk("pid_task error\n");
rcu_read_unlock();
//return -ENODEV;
}
The previous code prepare the signal structure and send it. Bear in mind that you need the application's PID. In my case the application from user space send its PID through ioctl driver procedure:
static long dev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) {
ioctl_arg_t args;
switch (cmd) {
case IOCTL_SET_VARIABLES:
if (copy_from_user(&args, (ioctl_arg_t *)arg, sizeof(ioctl_arg_t))) return -EACCES;
pid = args.pid;
break;
USER SPACE
Define and implement the callback function:
#define SIG_TEST 44
void signalFunction(int n, siginfo_t *info, void *unused) {
printf("received value %d\n", info->si_int);
}
In main procedure:
int fd = open("/dev/YourModule", O_RDWR);
if (fd < 0) return -1;
args.pid = getpid();
ioctl(fd, IOCTL_SET_VARIABLES, &args); // send the our PID as argument
struct sigaction sig;
sig.sa_sigaction = signalFunction; // Callback function
sig.sa_flags = SA_SIGINFO;
sigaction(SIG_TEST, &sig, NULL);
I hope it helps, despite the fact the answer is a bit long, but it is easy to understand.
You can use, e.g., kill_pid(declared in <linux/sched.h>) for send signal to the specified process. To form parameters to it, see implementation of sys_kill (defined as SYSCALL_DEFINE2(kill) in kernel/signal.c).
Note, that it is almost useless to send signal from the kernel to the current process: kernel code should return before user-space program ever sees signal fired.
Your interface is violating the spirit of Linux. Don't do that..... A system call (in particular those related to your driver) should only fail with errno (see syscalls(2)...); consider eventfd(2) or netlink(7) for such asynchronous kernel <-> userland communications (and expect user code to be able to poll(2) them).
A kernel module could fail to be loaded. I'm not familiar with the details (never coded any kernel modules) but this hello2.c example suggests that the module init function can return a non zero error code on failure.
People are really expecting that signals (which is a difficult and painful concept) are behaving as documented in signal(7) and what you want to do does not fit in that picture. So a well behaved kernel module should never asynchronously send any signal to processes.
If your kernel module is not behaving nicely your users would be pissed off and won't use it.
If you want to fork your experimental kernel (e.g. for research purposes), don't expect it to be used a lot; only then could you realistically break signal behavior like you intend to do, and you could code things which don't fit into the kernel module picture (e.g. add a new syscall). See also kernelnewbies.

Deriving from std::function vs creating a functor manually

I am trying to create a queue of callable elements with state so I can store the callable element (with an integer indicating when it should be called) and then call it later (after checking the stored integer within it).
I have been reading about functors and the std::function template for the past few days and I am wondering which one of the following two options would be better in terms of both memory and performance (which is better for each, if different).
1st Option:
class UpdateFunction : public std::function<bool(unsigned long long int)> {
public:
unsigned long long int _intendedTime;
};
void main()
{
typedef std::deque<UpdateFunction> UpdateQueue;
UpdateQueue _updateQueue;
_updateQueue.push_back(UpdateFunction([](unsigned long long int time)->bool{return outsideFunction(time);}));
_updateQueue.back()._intendedTime = 10;
}
2nd Option:
class UpdateFunction {
bool (*_fn)(unsigned long long int);
unsigned long long int _intendedTime;
UpdateFunction::UpdateFunction(bool (*fn)(unsigned long long int), unsigned long long int time)
: _fn(fn),
_intendedTime(time)
{
}
bool operator()(unsigned long long int time)
{
return _fn(time);
}
};
void main()
{
typedef std::deque<UpdateFunction> UpdateQueue;
UpdateQueue _updateQueue;
_updateQueue.push_back(UpdateFunction(outsideFunction, 10));
}
I have never seen any code where someone derives from std::function so I'm not even sure this would work as expected.
An answer which comes close to what I'm trying to do is this: https://stackoverflow.com/a/9050114/4076418, but I don't need variable arguments (actually, I have only one single signature, which is in the code above), so I thought it might be better to just derive from std::function instead of contain an instance of it. To be honest, I have no idea how slow or fast std::function is; I've read mentions of type erasure but I'm still trying to figure out what that is.
NB: I am a C++ beginner and I'm trying to wrap my head around references and move semantics, so I apologize if there are obvious errors in the code, or if the coding style is horrible.
I would go with a variant of option 2. This gives you the flexibility of function but avoids the headache of subclassing and needing to deal with the constructors.
struct UpdateFunction {
std::function<bool(unsigned long long int)> fn;
unsigned long long int _intendedTime;
};
You don't even need a special constructor, you can just say
queue.push_back(UpdateFunction{outsideFunction, 10});

How to sleep() from kernel init?

I'm debugging some code of the kernel init with an oscilloscope by setting up values on GPIO, what is the best way to sleep() for a given time very early, i.e, in ddr3_init() ?
Thank you
You could use a busy loop that stops after a given time interval. This should sleep for one second (I'm not sure if it works, I put it together by looking at the time.h header):
#include <linux/time.h>
struct timespec start_ts = current_kernel_time();
s64 start = timespec_to_ns(&start_ts);
do {
struct timespec now_ts = current_kernel_time();
s64 now = timespec_to_ns(&now_ts);
} while (now - start < 1000000000ULL);

Resources