KnigaRead.com/
KnigaRead.com » Компьютеры и Интернет » Программирование » Ори Померанц - Энциклопедия разработчика модулей ядра Linux

Ори Померанц - Энциклопедия разработчика модулей ядра Linux

На нашем сайте KnigaRead.com Вы можете абсолютно бесплатно читать книгу онлайн "Ори Померанц - Энциклопедия разработчика модулей ядра Linux". Жанр: Программирование издательство неизвестно, год неизвестен.
Перейти на страницу:

#include <linux/tty.h> /* For the tty declarations */


/* Print the string to the appropriate tty, the one

* the current task uses */

void print_string(char *str) {

 struct tty_struct *my_tty;

 /* The tty for the current task */

 my_tty = current->tty;

 /* If my_tty is NULL, it means that the current task

 * has no tty you can print to (this is possible, for

 * example, if it's a daemon). In this case, there's

 * nothing we can do. */

 if (my_tty != NULL) {

  /* my_tty->driver is a struct which holds the tty's

  * functions, one of which (write) is used to

  * write strings to the tty. It can be used to take

  * a string either from the user's memory segment

  * or the kernel's memory segment.

  *

  * The function's first parameter is the tty to

  * write to, because the same function would

  * normally be used for all tty's of a certain type.

  * The second parameter controls whether the

  * function receives a string from kernel memory

  * (false, 0) or from user memory (true, non zero).

  * The third parameter is a pointer to a string,

  * and the fourth parameter is the length of

  * the string. */

  (*(my_tty->driver).write)(

   my_tty, /* The tty itself */

   0, /* We don't take the string from user space */

   str, /* String */

   strlen(str)); /* Length */

  /* ttys were originally hardware devices, which

  * (usually) adhered strictly to the ASCII standard.

  * According to ASCII, to move to a new line you

  * need two characters, a carriage return and a

  * line feed. In Unix, on the other hand, the

  * ASCII line feed is used for both purposes - so

  * we can't just use n, because it wouldn't have

  * a carriage return and the next line will

  * start at the column right after the line feed.

  *

  * BTW, this is the reason why the text file

  * is different between Unix and Windows.

  * In CP/M and its derivatives, such as MS-DOS and

  * Windows, the ASCII standard was strictly

  * adhered to, and therefore a new line requires

  * both a line feed and a carriage return. */

  (*(my_tty->driver).write)(my_tty, 0, "1512", 2);

 }

}


/* Module initialization and cleanup ****************** */


/* Initialize the module - register the proc file */

int init_module() {

 print_string("Module Inserted");

 return 0;

}


/* Cleanup - unregister our file from /proc */

 void cleanup_module() {

 print_string("Module Removed");

}

Планирование задач

Очень часто, мы имеем «вспомогательные» задачи, которые должны быть выполнены в некоторое время. Если задача должна быть выполнена, мы делаем это, помещая ее в файл crontab. Если задача должна быть выполнена модулем, мы имеем две возможности. Первая в том, чтобы поместить процесс в файл crontab, который пробудит модуль системным вызовом когда необходимо, например, открывая файл. Это ужасно неэффективно, однако мы выполняем новый процесс из crontab, читаем новую программу в память, и всем это только чтобы пробудить модуль, который уже находится в памяти.

Вместо того, чтобы делать это, мы можем создавать функцию, которая будет вызвана прерыванием таймера. Таким путем мы создаем запись, хранимую в struct tq_struct, которая хранит указатель на функцию. Затем мы используем queue_task, чтобы поместить эту задачу в список задач, tq_timer, который является списком задач, которые будут выполнены на следующем прерывании таймера. Поскольку мы хотим, чтобы функция продолжила выполнение, мы должны поместить ее обратно в tq_timer всякий раз, когда она вызвана для следующего прерывания таймера.

Имеется еще одна хитрость. Когда модуль удален rmmod, сначала проверяется счетчик ссылок. Если он нулевой, вызывается module_cleanup . Затем модуль удаляется из памяти со всеми функциями. Никто не проверяет(отмечает), чтобы видеть, содержит ли список задач таймера указатель на одну из тех функций, которые больше не будут доступны. Позже (с точки зрения компьютера, с точки зрения человека мгновенно: меньше чем сотая доля секунды, то есть фактически мгновенно), ядро получит прерывание от таймера и попробует вызывать функцию в списке задач. К сожалению, функции больше там нет. В большинстве случаев, страница памяти, где она была, не используется, и Вы получаете сообщение об ошибке. Но если некоторый другой код теперь хранится в том же самом месте памяти, дело плохо. К сожалению, мы не имеем простой способ удалить задачу из списка задачи.

Так как cleanup_module не может вернуть код ошибки (она имеет тип возврата void), возникает решение не позволить возвращаться вообще. Вместо завершения модуля мы вызываем sleep_on или module_sleep_on[11] чтобы отправить в спячку сам rmmod. Перед этим мы сообщаем функции, вызываемой по прерыванию таймера, чтобы она убрала себя из списка, устанавливая глобальную переменную. На следующем прерывании таймера, процесс rmmod будет пробужден, когда наша функция больше не в очереди, и безопасно удалит модуль.

sched.c

/* sched.c - schedule a function to be called on

* every timer interrupt.

*/

/* Copyright (C) 1998 by Ori Pomerantz */


/* The necessary header files */

/* Standard in kernel modules */

#include <linux/kernel.h> /* We're doing kernel work */

#include <linux/module.h> /* Specifically, a module */


/* Deal with CONFIG_MODVERSIONS */

#if CONFIG_MODVERSIONS==1

#define MODVERSIONS

#include <linux/modversions.h>

#endif


/* Necessary because we use the proc fs */

#include <linux/proc_fs.h>


/* We scheduale tasks here */

#include <linux/tqueue.h>


/* We also need the ability to put ourselves to sleep

* and wake up later */

#include <linux/sched.h>


/* In 2.2.3 /usr/include/linux/version.h includes a

* macro for this, but 2.0.35 doesn't - so I add it

* here if necessary. */

#ifndef KERNEL_VERSION

#define KERNEL_VERSION(a,b,c) ((a)*65536+(b)*256+(c))

#endif


/* The number of times the timer interrupt has been

* called so far */

static int TimerIntrpt = 0;


/* This is used by cleanup, to prevent the module from

* being unloaded while intrpt_routine is still in

* the task queue */

static struct wait_queue *WaitQ = NULL;

static void intrpt_routine(void *);


/* The task queue structure for this task, from tqueue.h */

static struct tq_struct Task = {

 NULL,   /* Next item in list - queue_task will do

         * this for us */

 0,      /* A flag meaning we haven't been inserted

         * into a task queue yet */

 intrpt_routine, /* The function to run */

 NULL    /* The void* parameter for that function */

};


/* This function will be called on every timer

* interrupt. Notice the void* pointer - task functions

* can be used for more than one purpose, each time

* getting a different parameter. */

static void intrpt_routine(void *irrelevant) {

 /* Increment the counter */

 TimerIntrpt++;

 /* If cleanup wants us to die */

 if (WaitQ != NULL) wake_up(&WaitQ);

 /* Now cleanup_module can return */

 else queue_task(&Task, &tq_timer);

 /* Put ourselves back in the task queue */

}


/* Put data into the proc fs file. */

int procfile_read(char *buffer, char **buffer_location, off_t offset, int buffer_length, int zero) {

 int len;  /* The number of bytes actually used */

 /* This is static so it will still be in memory

 * when we leave this function */

 static char my_buffer[80];

 static int count = 1;

 /* We give all of our information in one go, so if

 * the anybody asks us if we have more information

 * the answer should always be no. */

 if (offset > 0) return 0;

 /* Fill the buffer and get its length */

 len = sprintf(my_buffer, "Timer was called %d times so farn", TimerIntrpt);

 count++;

 /* Tell the function which called us where the buffer is */

 *buffer_location = my_buffer;

 /* Return the length */

 return len;

}


struct proc_dir_entry Our_Proc_File = {

 0, /* Inode number - ignore, it will be filled by

     * proc_register_dynamic */

 5, /* Length of the file name */

 "sched", /* The file name */

 S_IFREG | S_IRUGO,

 /* File mode - this is a regular file which can

  * be read by its owner, its group, and everybody else */

 1,  /* Number of links (directories where

      * the file is referenced) */

 0, 0,  /* The uid and gid for the file - we give it to root */

 80, /* The size of the file reported by ls. */

 NULL, /* functions which can be done on the

        * inode (linking, removing, etc.) - we don't

        * support any. */

 procfile_read,

 /* The read function for this file, the function called

  * when somebody tries to read something from it. */

 NULL

 /* We could have here a function to fill the

  * file's inode, to enable us to play with

  * permissions, ownership, etc. */

};


/* Initialize the module - register the proc file */

int init_module() {

 /* Put the task in the tq_timer task queue, so it

 * will be executed at next timer interrupt */

 queue_task(&Task, &tq_timer);

 /* Success if proc_register_dynamic is a success,

 * failure otherwise */

#if LINUX_VERSION_CODE > KERNEL_VERSION(2,2,0)

 return proc_register(&proc_root, &Our_Proc_File);

#else

 return proc_register_dynamic(&proc_root, &Our_Proc_File);

#endif

}


/* Cleanup */

void cleanup_module() {

 /* Unregister our /proc file */

 proc_unregister(&proc_root, Our_Proc_File.low_ino);

 /* Sleep until intrpt_routine is called one last

 * time. This is necessary, because otherwise we'll

Перейти на страницу:
Прокомментировать
Подтвердите что вы не робот:*