Replace USB keyboard key press through a kernel module - linux-kernel

I need to replace a key press from a USB keyboard. As a first, I am just trying to print the scan code of the pressed key. However, my current implementation prints Scan Code 7e for every key press or even mouse movements. I used IRQ 19, which corresponds to my USB keyboard. I don't see any resources regarding USB keyboard interception. I would appreciate any pointers to get the below code to work.
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h> /* Needed for the macros */
#include <linux/interrupt.h>
#include <asm/io.h>
#include <linux/irq.h>
#include <linux/irqdesc.h>
#define KBD_IRQ 19 /* IRQ number for keyboard (i8042) */
#define KBD_DATA_REG 0x60 /* I/O port for keyboard data */
#define KBD_SCANCODE_MASK 0x7f
#define KBD_STATUS_MASK 0x80
static irqreturn_t kbd2_isr(int irq, void *dev_id)
{
char scancode;
scancode = inb(KBD_DATA_REG);
printk("Scan Code %x %s\n",
scancode & KBD_SCANCODE_MASK,
scancode & KBD_STATUS_MASK ? "Released" : "Pressed");
return IRQ_HANDLED;
}
static int __init kbd2_init(void)
{
int retval_irqreg;
retval_irqreg= request_irq(KBD_IRQ, (irq_handler_t) kbd2_isr, IRQF_SHARED, "kbd2", (void *)kbd2_isr);
return 0;
}
static void __exit kbd2_exit(void)
{ printk(KERN_INFO "removed interceptKBD module \n");
free_irq(KBD_IRQ, (void *)kbd2_isr);
}
module_init(kbd2_init);
module_exit(kbd2_exit);
MODULE_LICENSE("GPL");

Related

linux hw_breakpoint does not work while accessing memory from userspace

I am debugging a ARMv7 board and I want to know whether a kernel symbol is accessed. So I have to use hw_breakpoint in kernel.
For simplicity, I use kernel sample code:data_breakpoint to test, which locates in samples/hw_breakpoint/data_breakpoint.c.
Then I did the following operation:
insmod data_breakpoint.ko ksym=max
cat /proc/kallsyms | grep max
./read_kmem c06fa128
But this did not trigger the callback function.
If I print the value in that address in any kernel module, callback function will be triggered.
I read the cpu manual and it says that the breakpoint register in my cpu support virtual address matching. But I don't know why it doesn't work while accessing memory from userspace. I think that program does read the right value of kernel symbol.
read_kmem.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#define DEVKMEM "/dev/kmem"
#define PAGE_SIZE 0x1000
#define PAGE_MASK (~(PAGE_SIZE-1))
int main(int argc, char* argv[])
{
int fd;
char *mbase;
char read_buf[10];
unsigned int varAddr;
varAddr = strtoul(argv[1], 0, 16);
unsigned int ptr = varAddr & ~(PAGE_MASK);
fd = open(DEVKMEM, O_RDONLY);
if (fd == -1) {
perror("open");
exit(-1);
}
mbase = mmap(0,PAGE_SIZE,PROT_READ,MAP_SHARED,fd, (varAddr & PAGE_MASK));
if (mbase == MAP_FAILED) {
printf("map failed %s\n",strerror(errno));
}
printf("varAddr = 0x%X \n", varAddr);
printf("mapbase = 0x%X \n", (unsigned int)mbase);
printf("value = 0x%X \n",*(unsigned int*)(mbase+ptr));
close(fd);
munmap(mbase,PAGE_SIZE);
return 0;
}
Your userspace does not access address c06fa128, it accesses a different address - one that that mmap() returned (plus offset). Thus no breakpoint hit.
The fact that virtual address being accessed resolves to same physical address as some other virtual address that has a breapoint, does not matter. CPU executing your userspace code has no idea that different mapping exists.

setting an i2c register to high

I have this project that my boss asked me to do and the first step is to figure out how to set a given I2C register to high or low using the silicon lab library, if anyone knows any good sources for this type of problem please provide them thank you. The pic that I am using is the pic16f1823, I've already looked at the documentation of the pic but into only states how to read and write to an I2c.
I use this as a header file and seems to work well for PIC16F1827 which is basically the same as the 1823. It used the peripheral of the PIC. Just include in in any c file you want to use i2c in. Make sure you #define FOSC in order to calculate the correct baud rate. Also double check the port and tris assignments are correct for your device and make adjustments.
It uses polling instead of an interrupt. Uncomment the interrupt setup code and write an interrupt service routine to catch the interrupts.
#ifndef I2C_H
#define I2C_H
#ifdef __cplusplus
extern "C" {
#endif
/*
* Hi-Tech C I2C library for 12F1822
* Master mode routines for I2C MSSP port to read and write to slave device
* Copyright (C)2011 HobbyTronics.co.uk 2011
* Freely distributable.
*/
#define I2C_WRITE 0
#define I2C_READ 1
// Initialise MSSP port. (12F1822 - other devices may differ)
void i2c_Init(void){
// Initialise I2C MSSP
// Master 100KHz
TRISB2 = 1;
TRISB5 = 1;
SSP1CON1 = 0b00101000; // I2C Master mode
SSP1CON2 = 0b00000000;
SSP1CON3 = 0b00000000;
//SSP1MSK = 0b00000000;
SSP1ADD = I2C_BRG; // clock = FOSC/(4 * (SSPxADD+1))
//SSP1IE = 1; // enable interrupt
SSP1STAT = 0b10000000;
}
// i2c_Wait - wait for I2C transfer to finish
void i2c_Wait(void){
while ( ( SSP1CON2 & 0x1F ) || ( SSPSTAT & 0x04 ) );
}
// i2c_Start - Start I2C communication
void i2c_Start(void)
{
i2c_Wait();
SSP1CON2bits.SEN=1;
}
// i2c_Restart - Re-Start I2C communication
void i2c_Restart(void){
i2c_Wait();
SSP1CON2bits.RSEN=1;
}
// i2c_Stop - Stop I2C communication
void i2c_Stop(void)
{
i2c_Wait();
SSP1CON2bits.PEN=1;
}
// i2c_Write - Sends one byte of data
void i2c_Write(unsigned char data)
{
i2c_Wait();
SSPBUF = data;
}
// i2c_Address - Sends Slave Address and Read/Write mode
// mode is either I2C_WRITE or I2C_READ
void i2c_Address(unsigned char address, unsigned char mode)
{
unsigned char l_address;
l_address=address<<1;
l_address+=mode;
i2c_Wait();
SSPBUF = l_address;
}
// i2c_Read - Reads a byte from Slave device
unsigned char i2c_Read(unsigned char ack)
{
// Read data from slave
// ack should be 1 if there is going to be more data read
// ack should be 0 if this is the last byte of data read
unsigned char i2cReadData;
i2c_Wait();
SSP1CON2bits.RCEN=1;
i2c_Wait();
i2cReadData = SSPBUF;
i2c_Wait();
if ( ack ) SSP1CON2bits.ACKDT=0; // Ack
else SSP1CON2bits.ACKDT=1; // NAck
SSP1CON2bits.ACKEN=1; // send acknowledge sequence
return( i2cReadData );
}
#ifdef __cplusplus
}
#endif
#endif /* I2C_H */
Then you can use the higher level functions defined above to control a device, which is described in the datasheet of the slave device.
For example, to read from an eeprom:
#include <xc.h>
#define FOSC 16000000
#include "i2c.h"
unsigned char i2c_read_eeprom( unsigned char slaveaddress, unsigned char memaddress )
{
unsigned char data;
data = 123;
i2c_Start();
i2c_Address( slaveaddress, I2C_WRITE);
i2c_Write(memaddress);
if( SSP1CON2bits.ACKSTAT )
txstring("ACK!\r\n");
else txstring("nACK!\r\n");
i2c_Start();
i2c_Address( slaveaddress, I2C_READ);
data = i2c_Read(0);
i2c_Stop();
return data;
}

gethostbyname fails on OSX (Yosemite 10.10.4)

"gethostbyname" returns a pointer to this structure:
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses from name server */
};
When I try to use it, h_name points to a valid string: the partial name I supply is expanded to the correct fully qualified host name.
The value of h_addr_list is 4
h_name is valid
h_aliasis is a valid pointer to a null pointer
h_addrtype is 2 (AF_INET, IPV4)
h_length is 0 (should be 4, or perhaps a multiple of 4)
h_addr_list is 4, fails when dereferenced.
I'm running a 32 bit process (MS Office), the h_name pointer is a valid 32 bit pointer. WTF am I doing wrong? Does gethostbyname work for other people, or on other versions of OSX?
I was able to run this small example successfully on 10.10.4 (taken from paulschreiber.com)
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: %s hostname", argv[0]);
exit(-1);
}
struct hostent *hp = gethostbyname(argv[1]);
if (hp == NULL) {
printf("gethostbyname() failed\n");
} else {
printf("%s = ", hp->h_name);
unsigned int i=0;
while ( hp -> h_addr_list[i] != NULL) {
printf( "%s ", inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[i])));
i++;
}
printf("\n");
}
}
However, it did segfault on 64-bit without #include <arpa/inet.h: without that, no prototype for inet_ntoa is found, the return type is assumed to be an int (when it's actually a char *), and on 64-bit this truncates the pointer and causes a segfault.

insmod module param : invalid parameters

I'm developping sample kernel module driver.ko. I want to specify the block size of data_node structure with module parameter BlockSize. when I run insmod driver.ko alone, it works, but when I specify BlockSize insmod driver.ko BlockSize = 10 I get this eror :
Error: could not insert module driver.ko: Invalid parameters
modinfo -p ./driver.ko command give me this :
BlockSize: size of buffer (int)
driver.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/slab.h>
/* parametter */
static int BlockNumber = 8;
static int BlockSize = 512;
module_param( variable name, type, permission); */
module_param(BlockSize, int, S_IRUGO);
MODULE_PARM_DESC(BlockSize , " size of buffer");
/* using 'k' as magic number */
#define SAMPLE_IOC_MAGIC 'k'
#define SAMPLE_IOCRESET _IOWR(SAMPLE_IOC_MAGIC, 0, int)
#define SAMPLE_IOC_MAXNR 0
struct cdev* my_cdev;
dev_t dev;
static int size_to_read;
/* Macro used to compute the minimum */
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
/* data buffer structure */
typedef struct dnode
{
int bufSize;
char *buffer;
struct dnode *next;
} data_node;
/* liste stucture */
typedef struct lnode
{
data_node *head;
data_node *cur_write_node;
data_node *cur_read_node;
int cur_read_offset;
int cur_write_offset;
}liste;
code ..........................
..
It appears that module parameters should be passed without a space between the name and value, ie you should use:
insmod driver.ko BlockSize=10
This makes some sense, as in the command line to insmod itself "BlockSize=10" is a single entry in *argv[] which can be handed off to the kernel as a chunk, while "BlockSize = 10" would be three distinct entries ("BlockSize", "=", "10") which someone would have to write code to re-join.

Keyboard interrupt handler for own kernel (C)

I am writing a tiny OS as part of an assigment for school,but I got stuck when it comes to get keyboard input (press a key -> display it on screen). I am using the Bare Bones tutorial from osdev.org (gcc cross-compiler, GRUB bootloader, ld linker) and since I am in protected mode I can not use BIOS interrupts for input, that's why I have to write my own interrupt handler (?) but I'm not sure how to do that even after I read some osdev articles and forum discussions. Very similar problem (http://forum.osdev.org/viewtopic.php?f=1&t=9746) except that I don't know how to "set up the interrupts".
#if !defined(__cplusplus)
#include <stdbool.h> /* C doesn't have booleans by default. */
#endif
#include <stddef.h>
#include <stdint.h>
#define INT_DISABLE 0
#define INT_ENABLE 0x200
#define PIC1 0x20
#define PIC2 0xA0
#define ICW1 0x11
#define ICW4 0x01
void outb( unsigned short port, unsigned char val )
{
asm volatile("outb %0, %1" : : "a"(val), "Nd"(port) );
}
static __inline unsigned char inb (unsigned short int port)
{
unsigned char _v;
__asm__ __volatile__ ("inb %w1,%0":"=a" (_v):"Nd" (port));
return _v;
}
void init_pics(int pic1, int pic2)
{
/* send ICW1 */
outb(PIC1, ICW1);
outb(PIC2, ICW1);
/* send ICW2 */
outb(PIC1 + 1, pic1);
outb(PIC2 + 1, pic2);
/* send ICW3 */
outb(PIC1 + 1, 4);
outb(PIC2 + 1, 2);
/* send ICW4 */
outb(PIC1 + 1, ICW4);
outb(PIC2 + 1, ICW4);
/* disable all IRQs */
outb(PIC1 + 1, 0xFF);
}
/*irrelevant code*/
#if defined(__cplusplus)
extern "C" /* Use C linkage for kernel_main. */
#endif
void kernel_main()
{
terminal_initialize();
char c;
init_pics(0x20, 0x28);
c = inb(0x60);
terminal_putchar(c);
}
This is printing me a white box.If I try listening to port 0x64 I get some different character. I don't expect this to work, because I don't have the interrupt. I think it should be something like
void _interrupt button_pressed()
{
/*code*/
}
if(button_pressed)
{
c = inb(0x60);
//code to translate the char to ASCII
terminal_putchar(asciiChar);
}
Any help is appreciated. Thanks
If there is someone interested how I solved the problem, here is the solution
char c = 0;
init_pics(0x20, 0x28);
do
{
if(inb(0x60)!=c) //PORT FROM WHICH WE READ
{
c = inb(0x60);
if(c>0)
{
terminal_putinput(c); //print on screen
}
}
}
while(c!=1); // 1= ESCAPE
c variable contains the code of the pressed button. Creating a translation array by associating to each code, the corresponding ASCII code, I can print the letter/number which is written on button.
The buttons code can be found here: http://www.nondot.org/sabre/os/files/HCI/keyboard.txt
The ASCII here: http://www.ascii-code.com/

Resources