How to get lid state using linux kernel module? - linux

I can read the status of my laptop lid by reading /proc/acpi/button/lid/LID0/state file. Now I want to read it from kernel module.
I found the source file drivers/acpi/button.c in kernel source. But still I didn't understand how to use it. It exporting acpi_lid_notifier_register, acpi_lid_notifier_unregiste and acpi_lid_open functions.
How to write a module for lid state?

acpi_lid_open returns 0 (closed), 1 (open), or a negative error number (unsupported).
To use the notifier, you would define a callback function and a notifier block in your module:
static int yourmodule_lid_notify(struct notifier_block *nb, unsigned long val, void *unused) {
// Whatever you wanted to do here
}
static struct notifier_block lid_notifier;
// Somewhere in a function, likely your module init function:
lid_notifier.notifier_call = yourmodule_lid_notify;
if (acpi_lid_notifier_register(&lid_notifier)) {
// TODO: Handle the failure here
}
// TODO: Unregister the notifier when your module is unloaded:
acpi_lid_notifier_unregister(&lid_notifier);

Related

Glib: Calling a iterative loop function

Have a query on timeout calling and GMainContext. It is really confusing to me
Suppose I have the codes below (a bit incomplete, just for demonstration). I use normal Pthreads to create a thread. Within the thread, I run Glib functionality and created a GMainContext (stored within l_app.context).
I then created a source to run the function check_cmd iteratively at about 1 sec interval. This callback (or could we call it a thread?) will check for command from other threads( Pthreads not shown here for update in cmd status). From here onwards, there are two specific command
One to start a looping function
The other to end the looping function
I have done and thought of two ways to create the function and set them to run iteratively.
To create another timeout
using the same method of creating check_cmd
Essentially both to me are pretty much essentially the same method, when I tried both of them. Plan A (as I called it) does not work but Plan B ...actually run at least once. So I would like to know how to fix them...
Or maybe I should use g_source_add_child_source() instead?
In Summary, my question is
when you created a new context and push it to become the default context, do all subsequent function that require main_context will refer to this context?
in a nut shell, how do you add new sources when a loop is already running, ie like my cases
lastly, it is okay to quit the main loop within the callback you have created?
Here is my pseudocode
#include <glib.h>
#include <dirent.h>
#include <errno.h>
#include <pthread.h>
#define PLAN_A 0
typedef struct
{
GMainContext *context;
GMainLoop *loop;
}_App;
static _App l_app;
guint gID;
gboolean
time_cycle(gpointer udata)
{
g_print("I AM THREADING");
return true;
}
gboolean
check_cmd_session(NULL )
{
while(alive) /// alive is a boolean value that is shared with other threads(not shown)
{
if(start)
{
/// PLAN A
//// which context does this add to ??
#if PLAN_A
g_timeout_add_seconds(10, (GSourceFunc)timeout, NULL);
#else
/// or should i use PLAN B
GSource* source = g_timeout_source_new(1000);
gID = g_source_set_callback(source,
(GSourceFunc)time_cycle,
NULL,
NULL);
g_source_attach(source, l_app.context);
#endif
}
else
{
#if PLAN_A
g_source_remove(gID);
#else
}
}
g_main_loop_quit (l_app.loop);
return FALSE;
}
void*
liveService(Info *info)
{
l_app.context = g_main_context_new ();
g_main_context_push_thread_default(l_app.context);
GSource* source = g_timeout_source_new(1000);
g_source_set_callback(source,
(GSourceFunc)check_cmd_session,
NULL,
NULL);
/// make it run
g_source_attach(source, l_app.context);
g_main_loop_run (l_app.loop);
pthread_exit(NULL);
}
int main()
{
pthread_t tid[2];
int thread_counter = 0;
err = pthread_create(&(tid[thread_counter]), NULL, &live, &info);
if (err != 0)
{
printf("\n can't create live thread :[%s]", strerror(err));
}
else
{
printf("--> Thread for Live created successfully\n");
thread_counter++;
}
/**** other threads are build not shown here */
for(int i = 0; i < 2; i++)
{
printf("Joining the %d threads \n", i);
pthread_join(tid[i],NULL);
}
return 0;
}
In Summary, my question is
when you created a new context and push it to become the default context, do all subsequent function that require main_context will
refer to this context?
Functions that are documented as using the thread-default main context will use the GMainContext which has been most recently pushed with g_main_context_push_thread_default().
Functions that are documented as using the global default main context will not. They will use the GMainContext which is created at init time and which is associated with the main thread.
g_timeout_add_seconds() is documented as using the global default main context. So you need to go with plan B if you want the timeout source to be attached to a specific GMainContext.
in a nut shell, how do you add new sources when a loop is already running, ie like my cases
g_source_attach() works when a main context is being iterated.
lastly, it is okay to quit the main loop within the callback you have created?
Yes, g_main_loop_quit() can be called at any point.
From your code, it looks like you’re not creating a new GMainLoop for each GMainContext and are instead assuming that one GMainLoop will somehow work with all GMainContexts in the process. That’s not correct. If you’re going to use GMainLoop, you need to create a new one for each GMainContext you create.
All other things aside, you might find it easier to use GLib’s threading functions rather than using pthread directly. GLib’s threading functions are portable to other platforms and a little bit easier to use. Given that you’re already linking to libglib, using them would cost nothing extra.

What's the difference between flush_delayed_work and cancel_delayed_work_sync?

When shall I use flush_delayed_work and cancel_delayed_work_sync?
I have following delayed workqueue function:
static void workq_function(struct work_struct *work)
{
// ...
queue_delayed_work_on(2, wrkq, work, msecs_to_jiffies(3000));
}
Here I'm rescheduling my workqueue again in workqueue.
Is it a good practice to do like this?
Now i will use the following in rmmod:
flush_delayed_work(&work);
cancel_delayed_work_sync(&work);
destroy_workqueue(wrkq);
My system hangs after these API's at rmmod module.

insmod: ERROR: could not insert module : No child processes

i am trying to run the linux kernel module in linux kernel.
But what is happening, sometimes it succeeds and run, sometimes insertion of module fails with error :
insmod: ERROR: could not insert module netlinkKernel.ko: No child processes
and kernel logs shows it is failing at print
Error creating socket nl_sk
I think its a common error , and i do not think it has to do anything with module.
I am just creating two netlink sockets in module. when i comment the second socket creation line, With one netlink sockets, the module is working fine, but with two as pasted in code below, it alywas gives this error, then again, when i try the module with one netlink socket, then it also fails and i have to reboot the system.
static int __init hello_init(void) {
printk("Entering: %s\n",__FUNCTION__);
// This is for 3.6 kernels and above.
struct netlink_kernel_cfg cfg = {
.input = hello_nl_recv_msg,
};
struct netlink_kernel_cfg cfg1 = {
.input = hello_nl_recv_msg1,
};
nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
nl_sk1 = netlink_kernel_create(&init_net, NETLINK_USER1, &cfg1);
//nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, 0, hello_nl_recv_msg,NULL,THIS_MODULE);
if(!nl_sk)
{
printk(KERN_ALERT "Error creating socket nl_sk.\n");
return -10;
}
if(!nl_sk1)
{
printk(KERN_ALERT "Error creating socket nl_sk1.\n");
return -10;
}
return 0;
}
Can anyone please shed a light on this ?
NB: I am not (yet) a kernel coding master.
If I understand your query correctly, this module will insert properly so long as the 3rd netlink_kernel_create line is commented out. If this is the case, it is likely because once a Netlink socket is created for a specific unit (NETLINK_USER), it needs to be freed using netlink_kernel_release before it can be recreated again with another netlink_kernel_create. This is also why you cannot load the module after it has already failed to load; you are never releasing the allocated netlink sockets. Also, the 3rd invocation of netlink_kernel_create is incorrect for kernels after 3.7.
My recommendation would be to restructure your code to be something like this:
nl_sk = netlink_kernel_create(&init_net, NETLINK_USER, &cfg);
if(!nl_sk)
{
printk(KERN_ALERT "Error creating socket nl_sk.\n");
return -10;
}
nl_sk1 = netlink_kernel_create(&init_net, NETLINK_USER1, &cfg1);
if(!nl_sk1)
{
printk(KERN_ALERT "Error creating socket nl_sk1.\n");
netlink_kernel_release(nl_sk);
return -10;
}
Also, you should include matching netlink_kernel_release calls in your module_exit function
Ok, i changed the value for #define NETLINK_USER1 32 from 32 to 30 and it worked fine. Both sockets created. Need to see fn prototype
netlink_kernel_create(&init_net, NETLINK_USER1, &cfg1);
to check what possible values it expects as the middle argument.

Private variable disappears after thread starts

Problem:
I have a private variable that is available during the startup of a threaded object, but is out of scope when it is used later (via a signal and slot call).
Details:
I have an application that I'm developing in Qt5 for both linux and windows.
Currently it works as expected under linux (where development began), but now
that I'm trying to stand it up on windows 7 (I didn't have a copy of windows initially) I have run into this problem where (on windows only) my private variables go out of scope after the thread initializes.
Question:
What is wrong with my object/thread structure such that the variable scope is fine under Linux, but not in windows? I thought that was the kind of "behind the scenes" stuff Qt took care of? (clearly not)
More Detail:
The order of operation goes like this
Instantiate an object
Move the object into a thread
Get the thread's start signal and call an init function in the object
Later, get data and emit a signal to the threaded object
Threaded object processes data
The code outlining the steps above is summarized below.
void MyWorkerClass::init()
{
// ... bunchOCode
procThread = new QThread; // <-- procThread - private to MyWorkerClass
procObj = new Processor(startupData); // <-- procObj - private to MyWorkerClass
procObj->moveToThread(procThread);
connect(procThread, SIGNAL(started()), procObj, SLOT(doStart()));
connect(this, SIGNAL(dataIsReady(void *)), procObj, SLOT(processMsgs(void *)));
procThread->start();
ok = waitforProcSetup();
// ... Life is good, do more stuff
}
class Processor : public QObject
{
// ... Other
// ... stuff
private slots:
void doStart();
void processMsgs(void * buffer);
private:
QHash<QString, bool> process;
}
void Processor::doStart() // <-- private slot
{
// ... take care of init stuff that couldn't be done in constructor
// Variable is valid here and I can work with it.
foreach(site, locations.uniqueKeys()) {
process[site] = true; // <-- works like a champ
qDebug() << QString("%1 => %2").arg(site).arg(process[site]);
}
}
void Processor::processMsgs(void * buffer) // <-- buffer is malloc'd memory and works fine
{
// ... When MyWorkerClass gets some data it emits a signal that is connected
// to this private slot.
// Simply trying to examine the variable causes a segfault (because it's uninitialized here)
qDebug() << "... processMsgs:" << process.isEmpty(); // <-- wets the bed
}
.
In trying to improve my question, by following the suggestions from the people who commented, I found out what was going on. I was working on creating a small working version of the example I posted (thanks Kuba Ober). The "error" I was encountering was a segmentation fault that could consistently be recreated with the debug line:
qDebug() << "... processMsgs:" << process.isEmpty(); // <-- wets the bed
Specifically, the private QHash variable "process" was useable when I called it the first time (after the thread was up and running)
connect(procThread, SIGNAL(started()), procObj, SLOT(doStart()));
but that same variable acted like it had gone out of scope when I tried to call it the second time
connect(this, SIGNAL(dataIsReady(void *)), procObj, SLOT(processMsgs(void *)));
The signal (dataIsReady(void *)) for this second call is an explicit "emit" that the worker class does when it's collected some data that can be processed. I tried to make that clear in the comments of the example pseudocode, but I didn't take into account that the comment code I included wouldn't stand out that well since it's all grey.
What was really going on was right after I filled "process[site]" with data I also looped over a quint64 array filling it with data too. The loop went 1 element too far and wrote into the "process" variable, making it look to me like it had gone out of scope. In linux it was purely coincidental that it didn't segfault (likely there was padding between the array and the QHash), but the windows runtime exposed the error for the first time.

program get stuck in getenv()

I am overloading "malloc" by pre-loading a library. In this custom "malloc", i am using environment variable to distinguish my program to use my custom "malloc" from the general "malloc".
The problem is that, after several "mallocs" the program gets stuck inside getenv() call. I am not able to figure out why the program is getting stuck inside it.
The code is the following:
void* PerfTrackMallocInterposition::Malloc(size_t size) {
// Malloc with statistics
pthread_mutex_lock(&fgPTMutex);
char *checkCDBEnd=NULL;
static const char* CDBEndEnv = "checkCDBEnd";
checkCDBEnd = getenv(CDBEndEnv); //program gets stuck here
if(checkCDBEnd!=NULL)
{
if(checkCDBEnd[0]=='1')
{
if(size>1024)
{
void *result = Alloc(size); //Call to custom malloc
pthread_mutex_unlock(&fgPTMutex);
return result;
}
}
}
void* result = (*fPMalloc)(size); //call to normal malloc
pthread_mutex_unlock(&fgPTMutex);
return result;
}
I also get a bus error at same position while using this library with vim editor.
Please help me.
Thank You
Are you sure the program gets stuck on the getenv() call? I would be more suspicious of the mutexes: pthread_mutex_lock(&fgPTMutex); will block if another thread holds the mutex

Resources