Linux PCI device interrupt not generated - linux-kernel

I am currently refactoring a driver for the AMD Sensor Fusion Hub.
The original driver can be found here.
When sending commands to the device, the chip takes some time to process the request. I wasusing a hack using msleep to wait for the device to respond. However I'd like to cleanly implement IRQ handling. As a template I looked into the implementation of drivers/i2c/busses/i2c-amd-mp2-pci.c and came up with the following stub interrupt handling.
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
/*
* AMD Sensor Fusion Hub (SFH) PCIe driver
*
* Authors: Shyam Sundar S K <Shyam-sundar.S-k#amd.com>
* Nehal Bakulchandra Shah <Nehal-bakulchandra.Shah#amd.com>
* Richard Neumann <mail#richard-neumann.de>
*/
#include <linux/bitops.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/io-64-nonatomic-lo-hi.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/pm_runtime.h>
#include <linux/types.h>
#include "amd-sfh-pci.h"
/**
* amd_sfh_get_sensor_mask - Returns the sensors mask.
* #pci_dev: The Sensor Fusion Hub PCI device
*
* Returns an unsigned integer representing the bitmask to match
* the sensors connected to the Sensor Fusion Hub.
*/
int amd_sfh_get_sensor_mask(struct pci_dev *pci_dev)
{
int sensor_mask;
struct amd_sfh_dev *sfh_dev = pci_get_drvdata(pci_dev);
sensor_mask = readl(sfh_dev->mmio + AMD_SFH_SENSOR_MASK);
/* Correct bit shift in firmware register */
sensor_mask = sensor_mask >> 4;
if (!sensor_mask)
dev_err(&pci_dev->dev, "no sensors marked active on device\n");
return sensor_mask;
}
EXPORT_SYMBOL_GPL(amd_sfh_get_sensor_mask);
/**
* amd_sfh_start_sensor- Starts the respective sensor.
* #pci_dev: The Sensor Fusion Hub PCI device
* #sensor_idx: The sensor's index
* #dma_handle: The DMA handle
*/
void amd_sfh_start_sensor(struct pci_dev *pci_dev, enum sensor_idx sensor_idx,
dma_addr_t dma_handle)
{
struct amd_sfh_dev *sfh_dev = pci_get_drvdata(pci_dev);
union amd_sfh_cmd command;
union amd_sfh_parm parameter;
command.ul = 0;
command.s.cmd_id = enable_sensor;
command.s.period = PERIOD;
command.s.sensor_id = sensor_idx;
parameter.ul = 0;
parameter.s.buffer_layout = 1;
parameter.s.buffer_length = 16;
writeq(dma_handle, sfh_dev->mmio + AMD_SFH_ADDR);
writel(parameter.ul, sfh_dev->mmio + AMD_SFH_PARM);
writel(command.ul, sfh_dev->mmio + AMD_SFH_CMD);
}
EXPORT_SYMBOL_GPL(amd_sfh_start_sensor);
/**
* amd_sfh_stop_sensor- Stops the respective sensor.
* #pci_dev: The Sensor Fusion Hub PCI device
* #sensor_idx: The sensor's index
*/
void amd_sfh_stop_sensor(struct pci_dev *pci_dev, enum sensor_idx sensor_idx)
{
struct amd_sfh_dev *sfh_dev = pci_get_drvdata(pci_dev);
union amd_sfh_cmd command;
command.ul = 0;
command.s.cmd_id = disable_sensor;
command.s.period = 0;
command.s.sensor_id = sensor_idx;
writeq(0x0, sfh_dev->mmio + AMD_SFH_ADDR);
writel(command.ul, sfh_dev->mmio + AMD_SFH_CMD);
}
EXPORT_SYMBOL_GPL(amd_sfh_stop_sensor);
/**
* amd_sfh_stop_all_sensors- Stops all sensors on the SFH.
* #pci_dev: The Sensor Fusion Hub PCI device
*/
static void amd_sfh_stop_all_sensors(struct pci_dev *pci_dev)
{
struct amd_sfh_dev *sfh_dev = pci_get_drvdata(pci_dev);
union amd_sfh_cmd command;
command.ul = 0;
command.s.cmd_id = stop_all_sensors;
command.s.period = 0;
command.s.sensor_id = 0;
writel(command.ul, sfh_dev->mmio + AMD_SFH_CMD);
}
/**
* amd_sfh_irq_isr - IRQ handler
* #irq: The IRQ number received
* #dev: The underlying device
*/
static irqreturn_t amd_sfh_irq_isr(int irq, void *dev)
{
struct amd_sfh_dev *sfh_dev = dev;
dev_info(&sfh_dev->pci_dev->dev, "got IRQ: %d\n", irq);
return IRQ_NONE;
}
/**
* amd_sfh_pci_init - Initializes the PCI device
* #sfh_dev: The device data
* #pci_dev: The PCI device
*/
static int amd_sfh_pci_init(struct amd_sfh_dev *sfh_dev,
struct pci_dev *pci_dev)
{
int rc;
pci_set_drvdata(pci_dev, sfh_dev);
rc = pcim_enable_device(pci_dev);
if (rc)
goto err_pci_enable;
rc = pcim_iomap_regions(pci_dev, BIT(2), pci_name(pci_dev));
if (rc)
goto err_pci_enable;
sfh_dev->pci_dev = pci_dev;
sfh_dev->mmio = pcim_iomap_table(pci_dev)[2];
pci_set_master(pci_dev);
rc = pci_set_dma_mask(pci_dev, DMA_BIT_MASK(64));
if (rc) {
rc = pci_set_dma_mask(pci_dev, DMA_BIT_MASK(32));
if (rc)
goto err_dma_mask;
}
/* Set up intx irq */
writel(0, sfh_dev->mmio + AMD_P2C_MSG_INTEN);
pci_intx(pci_dev, 1);
dev_info(&pci_dev->dev, "available interrupt: %d\n", pci_dev->irq);
rc = devm_request_irq(&pci_dev->dev, pci_dev->irq, amd_sfh_irq_isr,
0, dev_name(&pci_dev->dev), sfh_dev);
if (rc)
dev_err(&pci_dev->dev, "Failure requesting irq %i: %d\n",
pci_dev->irq, rc);
return rc;
err_dma_mask:
pci_clear_master(pci_dev);
err_pci_enable:
return rc;
}
static int amd_sfh_pci_probe(struct pci_dev *pci_dev,
const struct pci_device_id *id)
{
int rc;
struct amd_sfh_dev *sfh_dev;
sfh_dev = devm_kzalloc(&pci_dev->dev, sizeof(*sfh_dev), GFP_KERNEL);
if (!sfh_dev)
return -ENOMEM;
rc = amd_sfh_pci_init(sfh_dev, pci_dev);
if (rc)
return rc;
pm_runtime_set_autosuspend_delay(&pci_dev->dev, 1000);
pm_runtime_use_autosuspend(&pci_dev->dev);
pm_runtime_put_autosuspend(&pci_dev->dev);
pm_runtime_allow(&pci_dev->dev);
dev_info(&pci_dev->dev, "SFH device registered.\n");
return 0;
}
static void amd_sfh_pci_remove(struct pci_dev *pci_dev)
{
struct amd_sfh_dev *sfh_dev = pci_get_drvdata(pci_dev);
amd_sfh_stop_all_sensors(sfh_dev->pci_dev);
pm_runtime_forbid(&pci_dev->dev);
pm_runtime_get_noresume(&pci_dev->dev);
pci_intx(pci_dev, 0);
pci_clear_master(pci_dev);
}
static const struct pci_device_id amd_sfh_pci_tbl[] = {
{PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_SFH)},
{0}
};
MODULE_DEVICE_TABLE(pci, amd_sfh_pci_tbl);
static struct pci_driver amd_sfh_pci_driver = {
.name = "amd-sfh-pci",
.id_table = amd_sfh_pci_tbl,
.probe = amd_sfh_pci_probe,
.remove = amd_sfh_pci_remove,
};
module_pci_driver(amd_sfh_pci_driver);
/**
* amd_sfh_find_device - Returns the first best AMD SFH device.
*/
struct amd_sfh_dev *amd_sfh_find_device(void)
{
struct device *dev;
struct pci_dev *pci_dev;
dev = driver_find_next_device(&amd_sfh_pci_driver.driver, NULL);
if (!dev)
return NULL;
pci_dev = to_pci_dev(dev);
return pci_get_drvdata(pci_dev);
}
EXPORT_SYMBOL_GPL(amd_sfh_find_device);
MODULE_DESCRIPTION("AMD(R) Sensor Fusion Hub PCI driver");
MODULE_AUTHOR("Shyam Sundar S K <Shyam-sundar.S-k#amd.com>");
MODULE_AUTHOR("Nehal Bakulchandra Shah <Nehal-bakulchandra.Shah#amd.com>");
MODULE_AUTHOR("Richard Neumann <mail#richard-neumann.de>");
MODULE_LICENSE("Dual BSD/GPL");
However the dev_info from amd_sfh_irq_isr is never logged, so I suspect that the IRQ is never triggered when writing to the device registers. What can be the reason for that and what can I do to correctly implement the IRQ handling?
PS
dmesg output:
[ 2272.642762] amd-sfh-pci 0000:04:00.7: available interrupt: 56
[ 2272.642840] amd-sfh-pci 0000:04:00.7: SFH device registered.
Update
The device seems to support MSI:
04:00.7 Non-VGA unclassified device [0000]: Advanced Micro Devices, Inc. [AMD] Raven/Raven2/Renoir Sensor Fusion Hub [1022:15e4]
Subsystem: Hewlett-Packard Company Raven/Raven2/Renoir Sensor Fusion Hub [103c:8496]
Flags: bus master, fast devsel, latency 0, IRQ 56
Memory at fc800000 (32-bit, non-prefetchable) [size=1M]
Memory at fcc8c000 (32-bit, non-prefetchable) [size=8K]
Capabilities: [48] Vendor Specific Information: Len=08 <?>
Capabilities: [50] Power Management version 3
Capabilities: [64] Express Endpoint, MSI 00
Capabilities: [a0] MSI: Enable- Count=1/2 Maskable- 64bit+
Capabilities: [c0] MSI-X: Enable- Count=2 Masked-
Capabilities: [100] Vendor Specific Information: ID=0001 Rev=1 Len=010 <?>
Kernel modules: amd_sfh_pci
But the interrupts are still not received / handled:
static void amd_sfh_debug(struct pci_dev *pci_dev)
{
bool msi;
msi = pci_dev_msi_enabled(pci_dev);
pci_info(pci_dev, "MSI: %s\n", msi ? "true" : "false");
pci_info(pci_dev, "No MSI: %s\n", pci_dev->no_msi ? "true" : "false");
}
/**
* amd_sfh_handle_irq - Handles IRQs.
* #irq: The interrupt request to be handled
* #dev: The driver data
*
* Returns an appropriate IRQ return type.
*/
static irqreturn_t amd_sfh_handle_irq(int irq, void *dev)
{
struct amd_sfh_dev *privdata = dev;
pci_info(privdata->pci_dev, "got IRQ: %d\n", irq);
return IRQ_NONE;
}
static int amd_sfh_setup_irq(struct amd_sfh_dev *privdata)
{
int rc, vecs, irq;
struct pci_dev *pci_dev = privdata->pci_dev;
vecs = pci_alloc_irq_vectors(pci_dev, 1, 3, PCI_IRQ_ALL_TYPES);
if (vecs < 0)
return vecs;
pci_info(pci_dev, "allocated %d IRQ vectors\n", vecs);
for (irq = 0; irq < vecs; irq++) {
pci_info(pci_dev, "requesting IRQ: %d\n", irq);
rc = devm_request_irq(&pci_dev->dev,
pci_irq_vector(pci_dev, irq),
amd_sfh_handle_irq, 0, "sfh-irq",
privdata);
if (rc) {
pci_err(pci_dev, "failed to get IRQ\n");
goto free_irq_vectors;
}
}
return 0;
free_irq_vectors:
pci_free_irq_vectors(pci_dev);
return rc;
}
static int amd_sfh_pci_init(struct amd_sfh_dev *privdata,
struct pci_dev *pci_dev)
{
int rc;
pci_set_drvdata(pci_dev, privdata);
rc = pcim_enable_device(pci_dev);
if (rc)
return rc;
rc = pcim_iomap_regions(pci_dev, BIT(2), pci_name(pci_dev));
if (rc)
return rc;
privdata->pci_dev = pci_dev;
privdata->mmio = pcim_iomap_table(pci_dev)[2];
pci_set_master(pci_dev);
rc = pci_set_dma_mask(pci_dev, DMA_BIT_MASK(64));
if (rc) {
rc = pci_set_dma_mask(pci_dev, DMA_BIT_MASK(32));
if (rc)
goto clear_master;
}
/* Setup IRQ */
amd_sfh_debug(pci_dev);
rc = amd_sfh_setup_irq(privdata);
if (rc)
goto clear_master;
amd_sfh_debug(pci_dev);
/* End of IRQ setup */
pci_info(pci_dev, "AMD Sensor Fusion Hub device initialized\n");
return 0;
clear_master:
pci_clear_master(pci_dev);
return rc;
}
dmesg:
[ 6.954524] amd-sfh-pci 0000:04:00.7: enabling device (0000 -> 0002)
[ 6.954641] amd-sfh-pci 0000:04:00.7: MSI: false
[ 6.954642] amd-sfh-pci 0000:04:00.7: No MSI: false
[ 6.954791] amd-sfh-pci 0000:04:00.7: allocated 2 IRQ vectors
[ 6.954792] amd-sfh-pci 0000:04:00.7: requesting IRQ: 0
[ 6.954825] amd-sfh-pci 0000:04:00.7: requesting IRQ: 1
[ 6.954860] amd-sfh-pci 0000:04:00.7: MSI: true
[ 6.954861] amd-sfh-pci 0000:04:00.7: No MSI: false
[ 6.954861] amd-sfh-pci 0000:04:00.7: AMD Sensor Fusion Hub device initialized
[ 6.969691] amd-sfh-pci 0000:04:00.7: [Firmware Bug]: No sensors marked active!
[ 6.971265] amd-sfh-pci 0000:04:00.7: sensor mask: 0x000001
[ 7.548189] hid-generic 0018:03FE:0001.0001: hidraw0: I2C HID v0.01 Device [amd-sfh-accel] on
The original documentation from AMD mentiones interrupts but is not too specific as to how they are being generated.

By try-and-error I found that I needed to set the P2C register 0x10690 to 1 in order to enable interrupts on the device. Whith this set, the device is flooding the driver with interrupts. I'm still figuring out how to make the device generate interrupts only on actual write events to the C2P registers.
Okay, I found out, how:
https://github.com/conqp/linux/blob/5ba797452a794100d65d103e8eb53f64ae14d1d0/drivers/hid/amd-sfh-hid/amd-sfh-pci.c#L301

Related

I2c Slave data PIC MPLAB X

I am trying to migrate from PIC16F886 to PIC18F24K40 . NOw here I am trying to communicate PIC18F24K40 with DS1307 and Display it on 4 Segment Display. I have tested my code on PIC16F886 but not worked on PIC18F24K40 . SInce PIC18F24K40 uses MPLAB X ide and creates MCC code configuration based I2c c file and .h file . Can someone suggest what wrong done i have done in below code
I could not able to update time once written.
/**
Generated Main Source File
Company:
Microchip Technology Inc.
File Name:
main.c
Summary:
This is the main file generated using MPLAB(c) Code Configurator
Description:
This header file provides implementations for driver APIs for all modules selected in the GUI.
Generation Information :
Product Revision : MPLAB(c) Code Configurator - 4.15
Device : PIC18F24K40
Driver Version : 2.00
The generated drivers are tested against the following:
Compiler : XC8 1.35
MPLAB : MPLAB X 3.40
*/
/*
(c) 2016 Microchip Technology Inc. and its subsidiaries. You may use this
software and any derivatives exclusively with Microchip products.
THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
PARTICULAR PURPOSE, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION
WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION.
IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE
TERMS.
*/
#include "mcc_generated_files/mcc.h"
#include "mcc_generated_files/i2c1.h"
uint8_t status;
#define DS1307_RETRY_MAX 100 // define the retry count
#define Ds1307_ADDRESS 0xD0 // slave device address
#define RTC_addres 0x68 // RTC slave device address
//static unsigned char readI2C[10], writeI2C[4];
#define buffersize 20
static unsigned char writeBuffer[buffersize]; //Buffer for I2C writing.
static unsigned char readbuffer[buffersize]; // Buffer for I2C reading.
uint8_t second;
uint8_t start_addres;
uint8_t length;
//I2C1_MESSAGE_STATUS w_status;
uint8_t sourceData[] = {0x1A, 0x2A, 0x4A, 0x8A,0x1A, 0x2A, 0x4A, 0x8A,0x1A, 0x2A, 0x4A, 0x8A,0x1A, 0x2A, 0x4A, 0x8A};
uint8_t addressBuffer[] = {0xAB,0x10} ; //Put your address here
uint8_t readBuffer[16];
uint8_t readByte;
# define LED RC7
unsigned int i;
unsigned int count;
unsigned int x;
unsigned short sec;
unsigned short min;
unsigned short hour;
unsigned short date;
unsigned short month;
unsigned short year;
unsigned short day;
unsigned short int temp=0;
unsigned short r_data;
#define Seg1 0x01
#define Seg2 0x02
#define Seg3 0x04
#define Seg4 0x08
#define Seg5 0x10
#define Seg6 0x20
unsigned short int cnt, num,Dgt=0;;
unsigned short int temp1,temp2,temp3;
void Delay(int k)
{
for(i=0;i<=k;i++);
}
void Blink_LED()
{
LED=!LED;
Delay(10000);
}
void SetSeg(unsigned short data, unsigned short segno)
{
switch(data)
{
case 0: PORTB = 0x3F; break;
case 1: PORTB = 0x06; break;
case 2: PORTB = 0x5B; break;
case 3: PORTB = 0x4F; break;
case 4: PORTB = 0x66; break;
case 5: PORTB = 0x6D; break;
case 6: PORTB = 0x7D; break;
case 7: PORTB = 0x07; break;
case 8: PORTB = 0x7F; break;
case 9: PORTB = 0x6F; break;
default : PORTB = 0X00; break;
}
if(segno==1)
{
PORTA = Seg4;
}
if(segno==2)
{
PORTA = Seg3;
}
if(segno==3)
{
PORTA = Seg2;
}
if(segno==4)
{
PORTA = Seg1;
}
}
unsigned int bcdtodecimal(unsigned int bcd)
{
unsigned int decimal;
decimal = (((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F);
return decimal;
}
void wait_mssp(void)
{
while(!PIR3bits.SSP1IF);
PIR3bits.SSP1IF =0;
}
void ds1307_write(unsigned char addr ,unsigned char data)
{
SSP1CON2bits.SEN =1; //Start bit
//SSP1BUF = 0XD0; //slave address(address of ds1307) + write bit
SSP1BUF =0X68;
SSP1BUF =addr;
SSP1BUF = data;
SSP1CON2bits.PEN =1; //stop bit
}
unsigned int ds1307_read(unsigned char addr)
{
SSP1CON2bits.RSEN =1;
//SSP1BUF =0XD0; //slave address(address of ds1307) + write bit;
SSP1BUF =0X68;
SSP1BUF =addr;
SSP1CON2bits.RSEN =1;
//SSP1BUF =0XD1; //slave address(address of ds1307) + read bit;
SSP1BUF =0X69;
SSP1CON2bits.RCEN =1;
SSP1CON2bits.ACKDT=1;
SSP1CON2bits.ACKEN =1;
SSP1CON2bits.PEN=1;
x = SSP1BUF;
return (x);
}
void SetDateTime()
{
ds1307_write(0X00,0x03);
ds1307_write(0X01,0X07);
ds1307_write(0X02,0X00);
ds1307_write(0X3,0X01);
ds1307_write(0X04,0x07);
ds1307_write(0X5,0X08);
ds1307_write(0X6,0X08);
}
void GetDateTime()
{
sec = ds1307_read(0X00);
sec=bcdtodecimal(sec);
min = ds1307_read(0X01);
min = bcdtodecimal(min);
hour = ds1307_read(0X02);
hour=bcdtodecimal( hour);
day= ds1307_read(0X03);
day = bcdtodecimal(day);
date= ds1307_read(0X04);
date=bcdtodecimal(date);
month= ds1307_read(0X05);
month = bcdtodecimal( month);
year= ds1307_read(0X06);
year= bcdtodecimal(year);
}
void Blink_Count()
{
if(PIR0bits.TMR0IF == 1)
{
PIR0bits.TMR0IF =0;
count=count+1;
if(count>=15)
{
LED=!LED;
count=0;
// SetSeg(min/10,4);
// SetSeg(min%10,3);
// SetSeg(sec/ 10,2);
// SetSeg(sec%10,1);
}
}
}
void main(void)
{
// Initialize the device
SYSTEM_Initialize();
// If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
// If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts
// Use the following macros to:
// Enable high priority global interrupts
//INTERRUPT_GlobalInterruptHighEnable();
// Enable low priority global interrupts.
//INTERRUPT_GlobalInterruptLowEnable();
// Disable high priority global interrupts
//INTERRUPT_GlobalInterruptHighDisable();
// Disable low priority global interrupts.
//INTERRUPT_GlobalInterruptLowDisable();
// Enable the Global Interrupts
//INTERRUPT_GlobalInterruptEnable();
// Enable the Peripheral Interrupts
//INTERRUPT_PeripheralInterruptEnable();
// Disable the Global Interrupts
//INTERRUPT_GlobalInterruptDisable();
// Disable the Peripheral Interrupts
//INTERRUPT_PeripheralInterruptDisable();
// I2C1_Initialize();
SSP1CLKPPS = 0x0E; //RB6->MSSP:SCL;
SSP1DATPPS = 0x0C; //RB4->MSSP:SDA;
RB6PPS = 0x10; //RB6->MSSP:SCL;
RB4PPS = 0x11; //RB4->MSSP:SDA;
SetDateTime();
while (1)
{
GetDateTime();
SetSeg(min/10,4);
SetSeg(min%10,3);
SetSeg(sec/ 10,2);
SetSeg(sec%10,1);
}
}
Based On MCC code configuration and used library below. But i could not see sec parameter updating after writing.
void main(void)
{
uint8_t second;
uint8_t start_addres;
uint8_t length;
I2C1_MESSAGE_STATUS w_status;
I2C1_MESSAGE_STATUS r_status;
// Initialize the device
SYSTEM_Initialize();
start_addres = 0;
length =12;
I2C1_MasterWriteTRBBuild( 0X00, length, RTC_addres, &w_status);
while (1)
{
I2C1_MasterReadTRBBuild( &second, length, RTC_addres, &r_status);
I2C1_MasterRead(&second, length, RTC_addres, &r_status);
sec=second;
}
}
THis is I2C1.c file created after MCC
typedef union
{
struct
{
uint8_t full:1;
uint8_t empty:1;
uint8_t reserved:6;
}s;
uint8_t status;
}I2C_TR_QUEUE_STATUS;
/**
I2C Driver Queue Entry Type
#Summary
Defines the object used for an entry in the i2c queue items.
#Description
This defines the object in the i2c queue. Each entry is a composed
of a list of TRBs, the number of the TRBs and the status of the
currently processed TRB.
*/
typedef struct
{
uint8_t count; // a count of trb's in the trb list
I2C1_TRANSACTION_REQUEST_BLOCK *ptrb_list; // pointer to the trb list
I2C1_MESSAGE_STATUS *pTrFlag; // set with the error of the last trb sent.
// if all trb's are sent successfully,
// then this is I2C1_MESSAGE_COMPLETE
} I2C_TR_QUEUE_ENTRY;
/**
I2C Master Driver Object Type
#Summary
Defines the object that manages the i2c master.
#Description
This defines the object that manages the sending and receiving of
i2c master transactions.
*/
typedef struct
{
/* Read/Write Queue */
I2C_TR_QUEUE_ENTRY *pTrTail; // tail of the queue
I2C_TR_QUEUE_ENTRY *pTrHead; // head of the queue
I2C_TR_QUEUE_STATUS trStatus; // status of the last transaction
uint8_t i2cDoneFlag; // flag to indicate the current
// transaction is done
uint8_t i2cErrors; // keeps track of errors
} I2C_OBJECT ;
/**
I2C Master Driver State Enumeration
#Summary
Defines the different states of the i2c master.
#Description
This defines the different states that the i2c master
used to process transactions on the i2c bus.
*/
typedef enum
{
S_MASTER_IDLE,
S_MASTER_RESTART,
S_MASTER_SEND_ADDR,
S_MASTER_SEND_DATA,
S_MASTER_SEND_STOP,
S_MASTER_ACK_ADDR,
S_MASTER_RCV_DATA,
S_MASTER_RCV_STOP,
S_MASTER_ACK_RCV_DATA,
S_MASTER_NOACK_STOP,
S_MASTER_SEND_ADDR_10BIT_LSB,
S_MASTER_10BIT_RESTART,
} I2C_MASTER_STATES;
/**
Section: Macro Definitions
*/
/* defined for I2C1 */
#ifndef I2C1_CONFIG_TR_QUEUE_LENGTH
#define I2C1_CONFIG_TR_QUEUE_LENGTH 1
#endif
#define I2C1_TRANSMIT_REG SSP1BUF // Defines the transmit register used to send data.
#define I2C1_RECEIVE_REG SSP1BUF // Defines the receive register used to receive data.
// The following control bits are used in the I2C state machine to manage
// the I2C module and determine next states.
#define I2C1_WRITE_COLLISION_STATUS_BIT SSP1CON1bits.WCOL // Defines the write collision status bit.
#define I2C1_MODE_SELECT_BITS SSP1CON1bits.SSPM // I2C Master Mode control bit.
#define I2C1_MASTER_ENABLE_CONTROL_BITS SSP1CON1bits.SSPEN // I2C port enable control bit.
#define I2C1_START_CONDITION_ENABLE_BIT SSP1CON2bits.SEN // I2C START control bit.
#define I2C1_REPEAT_START_CONDITION_ENABLE_BIT SSP1CON2bits.RSEN // I2C Repeated START control bit.
#define I2C1_RECEIVE_ENABLE_BIT SSP1CON2bits.RCEN // I2C Receive enable control bit.
#define I2C1_STOP_CONDITION_ENABLE_BIT SSP1CON2bits.PEN // I2C STOP control bit.
#define I2C1_ACKNOWLEDGE_ENABLE_BIT SSP1CON2bits.ACKEN // I2C ACK start control bit.
#define I2C1_ACKNOWLEDGE_DATA_BIT SSP1CON2bits.ACKDT // I2C ACK data control bit.
#define I2C1_ACKNOWLEDGE_STATUS_BIT SSP1CON2bits.ACKSTAT // I2C ACK status bit.
#define I2C1_7bit true
/**
Section: Local Functions
*/
void I2C1_FunctionComplete(void);
void I2C1_Stop(I2C1_MESSAGE_STATUS completion_code);
/**
Section: Local Variables
*/
static I2C_TR_QUEUE_ENTRY i2c1_tr_queue[I2C1_CONFIG_TR_QUEUE_LENGTH];
static I2C_OBJECT i2c1_object;
static I2C_MASTER_STATES i2c1_state = S_MASTER_IDLE;
static uint8_t i2c1_trb_count = 0;
static I2C1_TRANSACTION_REQUEST_BLOCK *p_i2c1_trb_current = NULL;
static I2C_TR_QUEUE_ENTRY *p_i2c1_current = NULL;
/**
Section: Driver Interface
*/
void I2C1_Initialize(void)
{
i2c1_object.pTrHead = i2c1_tr_queue;
i2c1_object.pTrTail = i2c1_tr_queue;
i2c1_object.trStatus.s.empty = true;
i2c1_object.trStatus.s.full = false;
i2c1_object.i2cErrors = 0;
// SMP Standard Speed; CKE enabled;
SSP1STAT = 0xC0;
// SSPEN enabled; CKP disabled; SSPM FOSC/4_SSPxADD_I2C;
SSP1CON1 = 0x28;
// SBCDE disabled; BOEN disabled; SCIE disabled; PCIE disabled; DHEN disabled; SDAHT 100ns; AHEN disabled;
SSP1CON3 = 0x00;
// Baud Rate Generator Value: SSPADD 2;
SSP1ADD = 0x02;
// clear the master interrupt flag
PIR3bits.SSP1IF = 0;
// enable the master interrupt
PIE3bits.SSP1IE = 1;
}
uint8_t I2C1_ErrorCountGet(void)
{
uint8_t ret;
ret = i2c1_object.i2cErrors;
return ret;
}
void I2C1_ISR ( void )
{
static uint8_t *pi2c_buf_ptr;
static uint16_t i2c_address = 0;
static uint8_t i2c_bytes_left = 0;
static uint8_t i2c_10bit_address_restart = 0;
PIR3bits.SSP1IF = 0;
// Check first if there was a collision.
// If we have a Write Collision, reset and go to idle state */
if(I2C1_WRITE_COLLISION_STATUS_BIT)
{
// clear the Write colision
I2C1_WRITE_COLLISION_STATUS_BIT = 0;
i2c1_state = S_MASTER_IDLE;
*(p_i2c1_current->pTrFlag) = I2C1_MESSAGE_FAIL;
// reset the buffer pointer
p_i2c1_current = NULL;
return;
}
/* Handle the correct i2c state */
switch(i2c1_state)
{
case S_MASTER_IDLE: /* In reset state, waiting for data to send */
if(i2c1_object.trStatus.s.empty != true)
{
// grab the item pointed by the head
p_i2c1_current = i2c1_object.pTrHead;
i2c1_trb_count = i2c1_object.pTrHead->count;
p_i2c1_trb_current = i2c1_object.pTrHead->ptrb_list;
i2c1_object.pTrHead++;
// check if the end of the array is reached
if(i2c1_object.pTrHead == (i2c1_tr_queue + I2C1_CONFIG_TR_QUEUE_LENGTH))
{
// adjust to restart at the beginning of the array
i2c1_object.pTrHead = i2c1_tr_queue;
}
// since we moved one item to be processed, we know
// it is not full, so set the full status to false
i2c1_object.trStatus.s.full = false;
// check if the queue is empty
if(i2c1_object.pTrHead == i2c1_object.pTrTail)
{
// it is empty so set the empty status to true
i2c1_object.trStatus.s.empty = true;
}
// send the start condition
I2C1_START_CONDITION_ENABLE_BIT = 1;
// start the i2c request
i2c1_state = S_MASTER_SEND_ADDR;
}
break;
case S_MASTER_RESTART:
/* check for pending i2c Request */
// ... trigger a REPEATED START
I2C1_REPEAT_START_CONDITION_ENABLE_BIT = 1;
// start the i2c request
i2c1_state = S_MASTER_SEND_ADDR;
break;
case S_MASTER_SEND_ADDR_10BIT_LSB:
if(I2C1_ACKNOWLEDGE_STATUS_BIT)
{
i2c1_object.i2cErrors++;
I2C1_Stop(I2C1_MESSAGE_ADDRESS_NO_ACK);
}
else
{
// Remove bit 0 as R/W is never sent here
I2C1_TRANSMIT_REG = (i2c_address >> 1) & 0x00FF;
// determine the next state, check R/W
if(i2c_address & 0x01)
{
// if this is a read we must repeat start
// the bus to perform a read
i2c1_state = S_MASTER_10BIT_RESTART;
}
else
{
// this is a write continue writing data
i2c1_state = S_MASTER_SEND_DATA;
}
}
break;
case S_MASTER_10BIT_RESTART:
if(I2C1_ACKNOWLEDGE_STATUS_BIT)
{
i2c1_object.i2cErrors++;
I2C1_Stop(I2C1_MESSAGE_ADDRESS_NO_ACK);
}
else
{
// ACK Status is good
// restart the bus
I2C1_REPEAT_START_CONDITION_ENABLE_BIT = 1;
// fudge the address so S_MASTER_SEND_ADDR works correctly
// we only do this on a 10-bit address resend
i2c_address = 0x00F0 | ((i2c_address >> 8) & 0x0006);
// set the R/W flag
i2c_address |= 0x0001;
// set the address restart flag so we do not change the address
i2c_10bit_address_restart = 1;
// Resend the address as a read
i2c1_state = S_MASTER_SEND_ADDR;
}
break;
case S_MASTER_SEND_ADDR:
/* Start has been sent, send the address byte */
/* Note:
On a 10-bit address resend (done only during a 10-bit
device read), the original i2c_address was modified in
S_MASTER_10BIT_RESTART state. So the check if this is
a 10-bit address will fail and a normal 7-bit address
is sent with the R/W bit set to read. The flag
i2c_10bit_address_restart prevents the address to
be re-written.
*/
if(i2c_10bit_address_restart != 1)
{
// extract the information for this message
i2c_address = p_i2c1_trb_current->address;
pi2c_buf_ptr = p_i2c1_trb_current->pbuffer;
i2c_bytes_left = p_i2c1_trb_current->length;
}
// check for 10-bit address
if(!I2C1_7bit && (0x0 != i2c_address))
{
if (0 == i2c_10bit_address_restart)
{
// we have a 10 bit address
// send bits<9:8>
// mask bit 0 as this is always a write
I2C1_TRANSMIT_REG = 0xF0 | ((i2c_address >> 8) & 0x0006);
i2c1_state = S_MASTER_SEND_ADDR_10BIT_LSB;
}
else
{
// resending address bits<9:8> to trigger read
I2C1_TRANSMIT_REG = i2c_address;
i2c1_state = S_MASTER_ACK_ADDR;
// reset the flag so the next access is ok
i2c_10bit_address_restart = 0;
}
}
else
{
// Transmit the address
I2C1_TRANSMIT_REG = i2c_address;
if(i2c_address & 0x01)
{
// Next state is to wait for address to be acked
i2c1_state = S_MASTER_ACK_ADDR;
}
else
{
// Next state is transmit
i2c1_state = S_MASTER_SEND_DATA;
}
}
break;
case S_MASTER_SEND_DATA:
// Make sure the previous byte was acknowledged
if(I2C1_ACKNOWLEDGE_STATUS_BIT)
{
// Transmission was not acknowledged
i2c1_object.i2cErrors++;
// Reset the Ack flag
I2C1_ACKNOWLEDGE_STATUS_BIT = 0;
// Send a stop flag and go back to idle
I2C1_Stop(I2C1_DATA_NO_ACK);
}
else
{
// Did we send them all ?
if(i2c_bytes_left-- == 0U)
{
// yup sent them all!
// update the trb pointer
p_i2c1_trb_current++;
// are we done with this string of requests?
if(--i2c1_trb_count == 0)
{
I2C1_Stop(I2C1_MESSAGE_COMPLETE);
}
else
{
// no!, there are more TRB to be sent.
//I2C1_START_CONDITION_ENABLE_BIT = 1;
// In some cases, the slave may require
// a restart instead of a start. So use this one
// instead.
I2C1_REPEAT_START_CONDITION_ENABLE_BIT = 1;
// start the i2c request
i2c1_state = S_MASTER_SEND_ADDR;
}
}
else
{
// Grab the next data to transmit
I2C1_TRANSMIT_REG = *pi2c_buf_ptr++;
}
}
break;
case S_MASTER_ACK_ADDR:
/* Make sure the previous byte was acknowledged */
if(I2C1_ACKNOWLEDGE_STATUS_BIT)
{
// Transmission was not acknowledged
i2c1_object.i2cErrors++;
// Send a stop flag and go back to idle
I2C1_Stop(I2C1_MESSAGE_ADDRESS_NO_ACK);
// Reset the Ack flag
I2C1_ACKNOWLEDGE_STATUS_BIT = 0;
}
else
{
I2C1_RECEIVE_ENABLE_BIT = 1;
i2c1_state = S_MASTER_ACK_RCV_DATA;
}
break;
case S_MASTER_RCV_DATA:
/* Acknowledge is completed. Time for more data */
// Next thing is to ack the data
i2c1_state = S_MASTER_ACK_RCV_DATA;
// Set up to receive a byte of data
I2C1_RECEIVE_ENABLE_BIT = 1;
break;
case S_MASTER_ACK_RCV_DATA:
// Grab the byte of data received and acknowledge it
*pi2c_buf_ptr++ = I2C1_RECEIVE_REG;
// Check if we received them all?
if(--i2c_bytes_left)
{
/* No, there's more to receive */
// No, bit 7 is clear. Data is ok
// Set the flag to acknowledge the data
I2C1_ACKNOWLEDGE_DATA_BIT = 0;
// Wait for the acknowledge to complete, then get more
i2c1_state = S_MASTER_RCV_DATA;
}
else
{
// Yes, it's the last byte. Don't ack it
// Flag that we will nak the data
I2C1_ACKNOWLEDGE_DATA_BIT = 1;
I2C1_FunctionComplete();
}
// Initiate the acknowledge
I2C1_ACKNOWLEDGE_ENABLE_BIT = 1;
break;
case S_MASTER_RCV_STOP:
case S_MASTER_SEND_STOP:
// Send the stop flag
I2C1_Stop(I2C1_MESSAGE_COMPLETE);
break;
default:
// This case should not happen, if it does then
// terminate the transfer
i2c1_object.i2cErrors++;
I2C1_Stop(I2C1_LOST_STATE);
break;
}
}
void I2C1_FunctionComplete(void)
{
// update the trb pointer
p_i2c1_trb_current++;
// are we done with this string of requests?
if(--i2c1_trb_count == 0)
{
i2c1_state = S_MASTER_SEND_STOP;
}
else
{
i2c1_state = S_MASTER_RESTART;
}
}
void I2C1_Stop(I2C1_MESSAGE_STATUS completion_code)
{
// then send a stop
I2C1_STOP_CONDITION_ENABLE_BIT = 1;
// make sure the flag pointer is not NULL
if (p_i2c1_current->pTrFlag != NULL)
{
// update the flag with the completion code
*(p_i2c1_current->pTrFlag) = completion_code;
}
// Done, back to idle
i2c1_state = S_MASTER_IDLE;
}
void I2C1_MasterWrite(
uint8_t *pdata,
uint8_t length,
uint16_t address,
I2C1_MESSAGE_STATUS *pflag)
{
static I2C1_TRANSACTION_REQUEST_BLOCK trBlock;
// check if there is space in the queue
if (i2c1_object.trStatus.s.full != true)
{
I2C1_MasterWriteTRBBuild(&trBlock, pdata, length, address);
I2C1_MasterTRBInsert(1, &trBlock, pflag);
}
else
{
*pflag = I2C1_MESSAGE_FAIL;
}
}
void I2C1_MasterRead(
uint8_t *pdata,
uint8_t length,
uint16_t address,
I2C1_MESSAGE_STATUS *pflag)
{
static I2C1_TRANSACTION_REQUEST_BLOCK trBlock;
// check if there is space in the queue
if (i2c1_object.trStatus.s.full != true)
{
I2C1_MasterReadTRBBuild(&trBlock, pdata, length, address);
I2C1_MasterTRBInsert(1, &trBlock, pflag);
}
else
{
*pflag = I2C1_MESSAGE_FAIL;
}
}
void I2C1_MasterTRBInsert(
uint8_t count,
I2C1_TRANSACTION_REQUEST_BLOCK *ptrb_list,
I2C1_MESSAGE_STATUS *pflag)
{
// check if there is space in the queue
if (i2c1_object.trStatus.s.full != true)
{
*pflag = I2C1_MESSAGE_PENDING;
i2c1_object.pTrTail->ptrb_list = ptrb_list;
i2c1_object.pTrTail->count = count;
i2c1_object.pTrTail->pTrFlag = pflag;
i2c1_object.pTrTail++;
// check if the end of the array is reached
if (i2c1_object.pTrTail == (i2c1_tr_queue + I2C1_CONFIG_TR_QUEUE_LENGTH))
{
// adjust to restart at the beginning of the array
i2c1_object.pTrTail = i2c1_tr_queue;
}
// since we added one item to be processed, we know
// it is not empty, so set the empty status to false
i2c1_object.trStatus.s.empty = false;
// check if full
if (i2c1_object.pTrHead == i2c1_object.pTrTail)
{
// it is full, set the full status to true
i2c1_object.trStatus.s.full = true;
}
}
else
{
*pflag = I2C1_MESSAGE_FAIL;
}
// for interrupt based
if (*pflag == I2C1_MESSAGE_PENDING)
{
while(i2c1_state != S_MASTER_IDLE);
{
// force the task to run since we know that the queue has
// something that needs to be sent
PIR3bits.SSP1IF = true;
}
} // block until request is complete
}
void I2C1_MasterReadTRBBuild(
I2C1_TRANSACTION_REQUEST_BLOCK *ptrb,
uint8_t *pdata,
uint8_t length,
uint16_t address)
{
ptrb->address = address << 1;
// make this a read
ptrb->address |= 0x01;
ptrb->length = length;
ptrb->pbuffer = pdata;
}
void I2C1_MasterWriteTRBBuild(
I2C1_TRANSACTION_REQUEST_BLOCK *ptrb,
uint8_t *pdata,
uint8_t length,
uint16_t address)
{
ptrb->address = address << 1;
ptrb->length = length;
ptrb->pbuffer = pdata;
}
bool I2C1_MasterQueueIsEmpty(void)
{
return(i2c1_object.trStatus.s.empty);
}
bool I2C1_MasterQueueIsFull(void)
{
return(i2c1_object.trStatus.s.full);
}
void I2C1_BusCollisionISR( void )
{
// enter bus collision handling code here
}
/**
End of File
*/

probe is not getting called in i2c driver

I am trying to learn to write a i2c driver on raspberry pi board and i have taken groove LCD back-light.Here driver.probe is not getting called whereas driver's inserted in system as i can see in dmesg.
Init code of driver is getting called, and code =>
static int lcd_probe(struct i2c_client *i2c_client, const struct i2c_device_id *i2c_id)
{
int ret = 0;
//struct lcd_data *lcd_data;
// struct device *dev = &i2c_client->dev;
// lcd_data->client = i2c_client;
pr_debug("lcd_probe : calling the probe\n");
pr_debug("lcd_probe : i2c_client->addr = %d, i2c_client_name = %s\n",
i2c_client->addr, i2c_client->name);
return ret;
}
static struct i2c_device_id lcd_id[] = {
{"lcd", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, lcd_id);
static struct i2c_driver lcd_driver = {
.driver = {
.name = "lcd",
.owner = THIS_MODULE,
},
.probe = lcd_probe,
// .remove = lcd_remove,
// .attach_adapter = lcd_attach,
.detect = lcd_detect,
.id_table = lcd_id,
};
static int __init lcd_init(void)
{
pr_debug("lcd_init : calling init\n");
return (i2c_add_driver(&lcd_driver));
}
and dmesg =>
[ 1.971009] lcd_init : calling init
But driver.probe is not registering in i2c subsystem.
board file initialization =>
Board init code =>
/** start aartyaa lcd i2c driver */
printk(KERN_INFO "board file registering i2c lcd device\n");
i2c_register_board_info_dt(1, lcd_i2c_devices, ARRAY_SIZE(lcd_i2c_devices));
i2c_board_info code =>
/** aaryaa i2c lcd struct */
static struct i2c_board_info __initdata lcd_i2c_devices[] = {
{
.type = "lcd",
.addr = 0x62,
},
};
i added debugs in i2c_register_device
and i found driver prove device is not getting called. dmesg i have linked
dmesg link
It seems that i need to register in platform also ..
How probe gets called in i2c ... ?
Any help will be appreciated.
Thank you...!!!

Why this proc driver crashes?

I am trying to write a proc driver that will print the driver history up till 10 last updates. In this driver, I haven't added the kernel data structure that I want to print. But, I am relying on the 'i' value to print the value up till 10. Here is my code.
#include <linux/init.h>
#include <linux/module.h> /** needed by all modules **/
#include <linux/kernel.h> /** This is for KERN_ALERT **/
#include <linux/proc_fs.h> /** This is for procfs **/
#include <linux/seq_file.h>
#include <linux/cdev.h> /** character device **/
#include <linux/device.h> /** for sys device registration in /dev/ and /sys/class **/
/** For class registration to work, you need GPL license **/
MODULE_LICENSE("GPL");
#define PROCFS_NAME "basicProcfs1"
static struct cdev basicCdev;
static struct class *basicDriverClass;
struct proc_dir_entry *procFileEntry = NULL;
static int basicMajorNumber = 0;
#define NUMBER_OF_MINOR_DEVICE (0)
#define NUM_MSG_HIST_ENTRIES (10)
static int gui32CmdMsgHistoryStartIndex=0;
/** This File operation table for proc file system **/
static int av_cmd_hist_show( struct seq_file *filp, void *v )
{
int i = *((int *)v);
printk("the av_cmd_hist_show called\r\n");
if ( i == 0)
{
seq_printf(filp, "Sequential print for debugging-- called for i-times i.e. 10 times \r\n");
}
seq_printf(filp, "Hello SJ proc! %d\r\n", i);
return 0;
}
static void av_cmd_hist_stop( struct seq_file *filp, void *v )
{
printk("av_cmd_hist_stop called..\r\n");
} /* av_cmd_hist_stop */
static void *av_cmd_hist_next( struct seq_file *filp, void *v, loff_t *pos )
{
(*pos)++;
printk("av_cmd_hist_next called..\r\n");
return( ( *pos < NUM_MSG_HIST_ENTRIES ) ? pos : NULL );
} /* av_cmd_hist_next */
static void *av_cmd_hist_start( struct seq_file *filp, loff_t *pos )
{
if( *pos == 0 )
{
printk("av_cmd_hist_start.. Initial..\r\n");
gui32CmdMsgHistoryStartIndex = 5;
}
printk("av_cmd_hist_start.. the *pos=0..\r\n");
return( ( *pos < NUM_MSG_HIST_ENTRIES ) ? pos : NULL );
} /* av_cmd_hist_start */
static struct seq_operations av_seq_cmd_hist_fops =
{
.start = av_cmd_hist_start,
.next = av_cmd_hist_next,
.stop = av_cmd_hist_stop,
.show = av_cmd_hist_show
};
static int basicProcShow(struct seq_file *m, void *v) {
seq_printf(m, "Hello SJ proc!\n");
return 0;
}
static int basicProcOpen(struct inode *inode, struct file *file)
{
int i;
i = seq_open( file, &av_seq_cmd_hist_fops );
return i;
//return single_open(file, basicProcShow, NULL);
}
/** Put data into the proc fs file **/
static const struct file_operations basic_proc_fops =
{
.owner = THIS_MODULE,
.open = basicProcOpen,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct file_operations fops = {
.read = NULL,
.write = NULL,
.open = NULL,
.release = NULL
};
static void setup_cdev(struct cdev *dev, int minor, struct file_operations *fops)
{
int err = -1;
/** MKDEV call creates a device number i.e. combination of major and minor number **/
int devno = MKDEV(basicMajorNumber, minor);
/** Initiliaze character dev with fops **/
cdev_init(dev, fops);
/**owner and operations initialized **/
dev->owner = THIS_MODULE;
dev->ops = fops;
/** add the character device to the system**/
/** Here 1 means only 1 minor number, you can give 2 for 2 minor device, the last param is the count of minor number enrolled **/
err = cdev_add (dev, devno, 1);
if (err)
{
printk (KERN_NOTICE "Couldn't add cdev");
}
}
static int chrDriverInit(void)
{
int result;
dev_t dev;
printk("Welcome!! Device Init now..");
/** int alloc_chrdev_region(dev_t *dev, unsigned int firstminor,unsigned int count, char *name); **/
/** dev -> The dev_t variable type,which will get the major number that the kernel allocates. **/
/**The same name will appear in /proc/devices. **/
/** it is registering the character device **/
/** a major number will be dynamically allocated here **/
/** alloc_chrdev_region(&dev_num, FIRST_MINOR, COUNT, DEVICE_NAME); **/
result = alloc_chrdev_region(&dev, 0, NUMBER_OF_MINOR_DEVICE, "pSeudoDrv1");
if( result < 0 )
{
printk("Error in allocating device");
return -1;
}
/** From these two if's we are avoiding the manual mknod command to create the /dev/<driver> **/
/** creating class, and then device created removes the dependency of calling mknod **/
/** A good method - the mknod way is depreciated **/
/** mknod way is - mknod /dev/<driver_name> c <majorNumber> <minorNumber>
/** add the driver to /sys/class/chardrv **/
if ((basicDriverClass = class_create(THIS_MODULE, "chardrv")) == NULL) //$ls /sys/class
{
unregister_chrdev_region(dev, 1);
return -1;
}
/** add the driver to /dev/pSeudoDrv -- here **/
if (device_create(basicDriverClass, NULL, dev, NULL, "pSeudoDrv") == NULL) //$ls /dev/
{
class_destroy(basicDriverClass);
unregister_chrdev_region(dev, 1);
return -1;
}
/** let's see what major number was assigned by the Kernel **/
basicMajorNumber = MAJOR(dev);
printk("Kernel assigned major number is %d ..\r\n",basicMajorNumber );
/** Now setup the cdev **/
setup_cdev(&basicCdev,NUMBER_OF_MINOR_DEVICE, &fops);
/** Setup Proc Entry here **/
/** 0644 means -
* 0 - owning (user) : read and write - 110
* Group - only read - 100
* Other - only read - 100 **/
procFileEntry = proc_create(PROCFS_NAME, 0, NULL, &basic_proc_fops);
if ( procFileEntry == NULL)
{
remove_proc_entry(PROCFS_NAME, NULL);
}
return 0;
}
static void chrDriverExit(void)
{
/** A reverse - destroy mechansim -- the way it was created **/
printk("Releasing Simple Devs -- %s\r\n", __FUNCTION__);
/** delete the character driver added **/
cdev_del(&basicCdev);
/** destroy the device created **/
device_destroy(basicDriverClass, MKDEV(basicMajorNumber, 0));
/** destroy the class created **/
class_destroy(basicDriverClass);
/** unregister the chr dev **/
unregister_chrdev(basicMajorNumber, NUMBER_OF_MINOR_DEVICE);
remove_proc_entry(PROCFS_NAME, NULL);
}
module_init(chrDriverInit);
module_exit(chrDriverExit);
The dmesg logs are the following.
# dmesg
[14102.921743] Releasing Simple Devs -- chrDriverExit
[14163.285107] Welcome!! Device Init now..Kernel assigned major number is 244 ..
[14174.979098] av_cmd_hist_start.. Initial..
[14174.979103] av_cmd_hist_start.. the *pos=0..
[14174.979104] the av_cmd_hist_show called
[14174.979107] av_cmd_hist_next called..
[14174.979108] the av_cmd_hist_show called
[14174.979109] av_cmd_hist_next called..
[14174.979110] the av_cmd_hist_show called
[14174.979112] av_cmd_hist_next called..
[14174.979113] the av_cmd_hist_show called
[14174.979114] av_cmd_hist_next called..
[14174.979115] the av_cmd_hist_show called
[14174.979117] av_cmd_hist_next called..
[14174.979118] the av_cmd_hist_show called
[14174.979119] av_cmd_hist_next called..
[14174.979120] the av_cmd_hist_show called
[14174.979121] av_cmd_hist_next called..
[14174.979122] the av_cmd_hist_show called
[14174.979124] av_cmd_hist_next called..
[14174.979125] the av_cmd_hist_show called
[14174.979126] av_cmd_hist_next called..
[14174.979127] the av_cmd_hist_show called
[14174.979128] av_cmd_hist_next called..
[14174.979130] av_cmd_hist_stop called..
[14174.979231] av_cmd_hist_start.. the *pos=0..
[14174.979233] av_cmd_hist_stop called..
[14174.979250] ------------[ cut here ]------------
[14174.979252] kernel BUG at mm/slub.c:3483!
[14174.979254] invalid opcode: 0000 [#2] SMP
[14174.979258] Modules linked in: procfs_driver1(O) procfs_driver(O-) tcp_lp nfsv3 nfsv4 nfs fscache dns_resolver fuse vboxpci(O) vboxnetadp(O) vboxnetflt(O) 8021q garp stp llc binfmt_misc vboxdrv(O) tpm_bios snd_hda_codec_hdmi snd_hda_codec_realtek fglrx(PO) snd_hda_intel snd_hda_codec snd_hwdep snd_seq snd_seq_device snd_pcm iTCO_wdt iTCO_vendor_support r8169 snd_timer mii e1000e snd i2c_i801 lpc_ich i2c_core soundcore snd_page_alloc coretemp kvm_intel kvm serio_raw video dcdbas microcode uinput nfsd lockd nfs_acl auth_rpcgss sunrpc crc32c_intel [last unloaded: procfs_driver1]
[14174.979297] Pid: 19055, comm: cat Tainted: P B D C O 3.6.11-4.fc16.i686 #1 Dell Inc. OptiPlex 9010/00F82W
[14174.979300] EIP: 0060:[<c0530891>] EFLAGS: 00210246 CPU: 5
The proc output is the following -
# cat /proc/basicProcfs1
Sequential print for debugging-- called for i-times i.e. 10 times
Hello SJ proc! 0
Hello SJ proc! 1
Hello SJ proc! 2
Hello SJ proc! 3
Hello SJ proc! 4
Hello SJ proc! 5
Hello SJ proc! 6
Hello SJ proc! 7
Hello SJ proc! 8
Hello SJ proc! 9
Segmentation fault
Sorry, I got the fix.
Erroneous code
static const struct file_operations basic_proc_fops =
{
.owner = THIS_MODULE,
.open = basicProcOpen,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
Right code-
static const struct file_operations basic_proc_fops =
{
.owner = THIS_MODULE,
.open = basicProcOpen,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
I would appreciate, if someone can explain why it makes the difference.
It is crashing becasue of this return( ( *pos < NUM_MSG_HIST_ENTRIES ) ? pos : NULL );
(I do not have enough reputation to comment, so adding it as an answer) Regarding your question on why seq_release and not single_release, 'release' functions should compliment 'open' functions. Your open function here 'basicProcOpen' calls 'seq_open' so you should be calling seq_release.
If you look at single_release, in addition to seq_release, there is a kfree(op) which causes your crash.
623 int single_release(struct inode *inode, struct file *file)
624 {
625 const struct seq_operations *op = ((struct seq_file *)file->private_data)->op;
626 int res = seq_release(inode, file);
627 kfree(op);
628 return res;
629 }
630 EXPORT_SYMBOL(single_release);

Associate existing Linux device structure with device file

I'm developing with a PowerPC 405 embedded in a Virtex4 FPGA with Linux kernel 2.6.33.
Up until now, I've been writing drivers for platform devices implemented in the FPGA in the form of kernel loadable modules. The devices are registered using the flat Open Firmware Device Tree file. To create a device file, I use the OF functions to get the device node, and then register a new miscdevice which then automatically registers a minor device number and creates the device file for me. This also creates a device that is embedded in the miscdevice (i.e. miscdevice.this_device)
The problem is now I need to perform DMA operations. I tried to call the dma_alloc_coherent() function using the miscdevice.this_device, but this device isn't associated with any bus and always returns an error. I did some digging around and it turns out that the struct of_device also has a struct device embedded in it (i.e. of_device.dev). When I tried using this with dma_alloc_coherent(), it worked just fine.
So now I have two different struct device structures, one to manage my character device file, and one to manage the underlying Open Firmware system calls, the bus and DMA transactions. These devices are not associated with each other in the sysfs of course.
My question is, is it possible to somehow request that a device file be created for the device structure I get from the OF layer and not create a new device with the Misc Device API? That way everything will be associated with a single device structure.
I think your fix about dma_alloc_coherent() is correct.
But I don't think it's not right to use the device structure embedded in structure of_device to replace the miscdevice you created. The of_device is description of objects in Open Firmware database. And according to Linux device driver model, device structure is embedded in various device objects in Linux Kernel. And I think you registe miscdevice as one character device, there should be file_operations structure associated.
In one word, they are different views, and they can not replace each other.
I wrote some experimental dma driver using miscdevice.this_device for raspberry pi
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/miscdevice.h>
#include "gpio.h"
#include <linux/dma-mapping.h>
#include <linux/dmaengine.h>
#include "DMA.h"
#include <linux/of_irq.h>
static int my_open(struct inode *i, struct file *f)
{
printk(KERN_INFO "Driver: open() %d\n", current->pid);
return 0;
}
static int my_close(struct inode *i, struct file *f)
{
printk(KERN_INFO "Driver: close()\n");
return 0;
}
static ssize_t my_read(struct file *f, char __user *buf, size_t len, loff_t *off)
{
printk(KERN_INFO "Driver: read()\n");
return 0;
}
char databuf[100];
static ssize_t my_write(struct file *f, const char __user *buf, size_t len, loff_t *off)
{
if(copy_from_user(databuf, buf, 100) != 0) return 0;
printk("Data from the user: %s\n", databuf);
return len;
}
static struct file_operations sample_fops =
{
.owner = THIS_MODULE,
.open = my_open,
.release = my_close,
.read = my_read,
.write = my_write
};
struct miscdevice sample_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "ledButton",
.fops = &sample_fops,
.mode = 0666,
};
//static struct dmadata_s *cpu_addr;
//dma_addr_t dma_addr;
struct dma_cb *virt_cb;
dma_addr_t phys_cb;
uint32_t *virt_src;
dma_addr_t phys_src;
uint32_t *virt_dst;
dma_addr_t phys_dst;
static irqreturn_t dma_irq_fn(int irq, void *dev_id)
{
printk("destAddr %u\n", *virt_dst);
dma_regs->CS.INT = 1;
return IRQ_HANDLED;
}
static struct device *dev;
int IRQ_DMA0;
static int __init ofcd_init(void) /* Constructor */
{
int error, mret;
struct device_node * np = NULL;
error = misc_register(&sample_device);
if (error) {
pr_err("can't misc_register :(\n");
return error;
}
dev = sample_device.this_device;
dev->coherent_dma_mask = ~0;
dev->dma_mask = &dev->coherent_dma_mask;
// dev_set_name(dev, "mydmadev");
// cpu_addr = (struct dmadata_s*)kmalloc(sizeof(struct dmadata_s), GFP_KERNEL | GFP_DMA);
//dma_addr = dma_map_single(dev, cpu_addr, sizeof(struct dmadata_s), DMA_BIDIRECTIONAL);
virt_cb = dma_alloc_coherent(dev, 32, &phys_cb, GFP_KERNEL | GFP_DMA);
if(virt_cb == 0 || phys_cb == 0){
printk("DMA cb error\n");
}
virt_src = dma_alloc_coherent(dev, 4, &phys_src, GFP_KERNEL | GFP_DMA);
if(virt_src == 0 || phys_src == 0){
printk("DMA src error\n");
}
virt_dst = dma_alloc_coherent(dev, 4, &phys_dst, GFP_KERNEL | GFP_DMA);
if(virt_dst == 0 || phys_dst == 0){
printk("DMA dst error\n");
}
memset(virt_cb, 0, sizeof(*virt_cb));
dma_regs = (struct dma_ch *)ioremap(DMA_BASE, sizeof(struct dma_ch));
// strcpy(cpu_addr->srcAddr, "DMA0");
*virt_src = 200;
virt_cb->TI.SRC_INC = 1;
virt_cb->TI.DEST_INC = 1;
virt_cb->TI.INTEN = 1;
virt_cb->SOURCE_AD = (uint32_t)phys_src;
virt_cb->DEST_AD = (uint32_t)phys_dst;
virt_cb->TXFR_LEN = 4;
virt_cb->reserved[0] = 0;
virt_cb->reserved[1] = 0;
printk("srcAddr %u\n", *virt_src);
printk("destAddr %u\n", *virt_dst);
//dma_regs->CS = (DMA_CS_t){.RESET = 1, .END = 1};
dma_regs->CS.RESET = 1;
udelay(10);
// dma_regs->CS = (DMA_CS_t){.END = 1, .INT = 1};
dma_regs->CS.INT = 1;
dma_regs->CS.END = 1;
dma_regs->CONBLK_AD = (uint32_t)phys_cb;
//dma_regs->DEBUG = (DMA_DEBUG_t){.READ_LAST_NOT_SET_ERROR = 1, .FIFO_ERROR = 1, .READ_ERROR = 1};
dma_regs->DEBUG.READ_LAST_NOT_SET_ERROR = 1;
dma_regs->DEBUG.FIFO_ERROR = 1;
dma_regs->DEBUG.READ_ERROR =1;
udelay(10);
// dma_regs->CS = (DMA_CS_t){.RESET = 1, .PRIORITY = 8, .PANIC_PRIORITY = 8, .ACTIVE = 1};
dma_regs->CS.RESET = 1;
udelay(10);
dma_regs->CS.PRIORITY = 8;
dma_regs->CS.PANIC_PRIORITY = 8;
dma_regs->CS.ACTIVE = 1;
if(dma_regs->CS.ERROR) printk("ERROR %d %d\n", dma_regs->CS.ACTIVE, dma_regs->CS.PANIC_PRIORITY);
//np = of_find_compatible_node(NULL,NULL,"brcm,bcm2835-system-timer");
np = of_find_node_by_path("/soc/dma#7e007000");
if (np == NULL){
printk("Error node not found\n");
}
// printk("node name %s\n", np->name);
IRQ_DMA0 = irq_of_parse_and_map(np, 0);
if (IRQ_DMA0 <= 0) {
printk("Can't parse IRQ\n");
}
mret = request_irq(IRQ_DMA0, dma_irq_fn, IRQF_SHARED, "dma", &dma_irq_fn);
if (mret < 0) printk(KERN_ALERT "%s: dma request_irg failed with %d\n", __func__, mret);
return 0;
}
static void __exit ofcd_exit(void) /* Destructor */
{
free_irq( IRQ_DMA0, &dma_irq_fn );
//dma_unmap_single(dev, dma_addr, sizeof(struct dmadata_s), DMA_BIDIRECTIONAL);
//kfree(cpu_addr);
dma_free_coherent(dev, 32, virt_cb, phys_cb);
dma_free_coherent(dev, 4, virt_src, phys_src);
dma_free_coherent(dev, 4, virt_dst, phys_dst);
iounmap(dma_regs);
// device_unregister(dev);
misc_deregister(&sample_device);
printk(KERN_INFO "Module unregistered\n");
}
module_init(ofcd_init);
module_exit(ofcd_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("MBajor>");
MODULE_DESCRIPTION("PiCNC driver");
MODULE_VERSION("0.1");
I hope this help.

Kernel panics : trying to write / read on tiny tty driver

I'm a beginner to the Linux programming and trying my hands on some device driver examples while practising.
The below code (a trimmed down version of tiny_tty.c) loads perfectly using insmod and I'm able to see it in /proc/tty/drivers , /proc/modules and device nodes are getting created under /dev. When I try to write to device file like echo "abcd" > /dev/ttyms0 (I hope this is fine) or read like cat /dev/ttyms0, the kernel panics with a call trace on the screen. I'm on kernel 3.5.0 under Ubuntu. Unfortunately I'm not able to capture the trace , as when it panics I'm left with no option but reboot using power button. I believe some issue with timer is here, as the trace shows a line on top saying :
"*kernel bug at /build/buildd/linux-3.5.0/kernel/timer.c:901*", then the call trace , followed by
"*EIP is at add_timer+0x18/0x20*"
Below is the full code. Any guidance is very much appreciated in anticipation.
10May2013 : I tried initializing the timer in open function and this time below is the call trace for "kernel panic - not syncing : fatal exception in interrupt panic occurred, switching back to text console":
update_sd_lb_stats+0xcd/0x4b0
find_busiest_group+0x2e/0x420
enqueue_entity+0xcb/0x510
load_balance+0x7e/0x5e0
rebalance_domains+0xed/0x150
__do_softirq+0xdb/0x180
local_bh_enable_ip+0x90/0x90
<IRQ>
copy_to_user0x41/0x60
sys_gettimeofday+0x2a/0x70
sysenter_do_call0x12/0x20
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/wait.h>
#include <linux/errno.h>
#include <linux/slab.h> /* kmalloc() */
#include <linux/tty_driver.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/mutex.h>
#include <linux/serial.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include <asm/termios.h>
MODULE_LICENSE("GPL");
#define MS_TTY_MAJOR 250 //test value
#define MS_TTY_NUM_DEV 2
#define DELAY_TIME HZ * 2 /* 2 seconds per character */
#define TINY_DATA_CHARACTER 't'
static int major_num;
//static int minor_num=0;
//static int num_tty_dev=2;
/* Below structure is a wrapper for device specific fields */
struct ms_tty_serial {
struct tty_struct *tty; /* pointer to the tty for this device */
int open_count; /* number of times this port has been opened */
struct semaphore sem; /* locks this structure */
struct timer_list *timer;
};
static struct ms_tty_serial *ms_tty_table[MS_TTY_NUM_DEV]; /* initially all NULL */
static void ms_tty_timer(unsigned long timer_data)
{
struct ms_tty_serial *ms_ptr = (struct ms_tty_serial *)timer_data;
struct tty_struct *tty;
char data[1] = {TINY_DATA_CHARACTER};
int data_size = 1;
if (!ms_ptr)
return;
tty = ms_ptr->tty;
tty->low_latency=1;
/* send the data to the tty layer for users to read. This doesn't
* actually push the data through unless tty->low_latency is set */
tty_buffer_request_room (tty, data_size);
tty_insert_flip_string(tty, data, data_size);
tty_flip_buffer_push(tty);
/* resubmit the timer again */
ms_ptr->timer->expires = jiffies + DELAY_TIME;
add_timer(ms_ptr->timer);
}
//// Define the open function ////
static int tty_ms_open(struct tty_struct *tty_this, struct file *file_this)
{
printk(KERN_ALERT "tty_ms driver: OPENED ...\n");
struct ms_tty_serial *ms_ptr;
struct timer_list *timer;
int index;
/* initialize the pointer in case something fails */
tty_this->driver_data = NULL;
/* get the serial object associated with this tty pointer */
index = tty_this->index;
ms_ptr = ms_tty_table[index];
if (ms_ptr == NULL) {
/* first time accessing this device, create it */
ms_ptr = kmalloc(sizeof(*ms_ptr), GFP_KERNEL);
if (!ms_ptr)
return -ENOMEM;
// init_MUTEX(&ms_ptr->sem); /* didn't work for this kernel version 3.5.0 */
#ifndef init_MUTEX /* sema_init is to be used for kernel 2.6.37 and above */
sema_init(&ms_ptr->sem,1);
#else
init_MUTEX(&ms_ptr->sem);
#endif
ms_ptr->open_count = 0;
ms_ptr->timer = NULL;
ms_tty_table[index] = ms_ptr;
}
down(&ms_ptr->sem);
/* save our structure within the tty structure */
tty_this->driver_data = ms_ptr;
ms_ptr->tty = tty_this;
ms_ptr->filp = file_this; // to be tried
++ms_ptr->open_count;
if (ms_ptr->open_count == 1) {
/* this is the first time this port is opened */
/* do any hardware initialization needed here */
/* create timer and submit it */
if (!ms_ptr->timer) {
timer = kmalloc(sizeof(*timer), GFP_KERNEL);
if (!timer) {
up(&ms_ptr->sem);
return -ENOMEM;
}
ms_ptr->timer = timer;
}
init_timer (ms_ptr->timer); // to be tried
ms_ptr->timer->data = (unsigned long )ms_ptr;
ms_ptr->timer->expires = jiffies + DELAY_TIME;
ms_ptr->timer->function = ms_tty_timer;
add_timer(ms_ptr->timer);
}
up(&ms_ptr->sem);
return 0;
}
//// Define the close function ////
static void do_close(struct ms_tty_serial *ms_ptr)
{
down(&ms_ptr->sem);
if (!ms_ptr->open_count) {
/* port was never opened */
goto exit;
}
--ms_ptr->open_count;
if (ms_ptr->open_count <= 0) {
/* The port is being closed by the last user. */
/* Do any hardware specific stuff here */
/* shut down our timer */
del_timer(ms_ptr->timer);
}
exit:
up(&ms_ptr->sem);
}
static void tty_ms_close(struct tty_struct *tty_this, struct file *file_this)
{
printk(KERN_ALERT "tty_ms driver: CLOSING ...\n");
struct ms_tty_serial *ms_ptr = tty_this->driver_data;
if (ms_ptr)
do_close(ms_ptr);
}
//// Define the write function ////
static int tty_ms_write(struct tty_struct *tty_this, const unsigned char *tty_buff, int count)
{
printk(KERN_ALERT "tty_ms driver: WRITING ...\n");
struct ms_tty_serial *ms_ptr = tty_this->driver_data;
int i;
int retval = -EINVAL;
if (!ms_ptr)
return -ENODEV;
down(&ms_ptr->sem);
if (!ms_ptr->open_count)
/* port was not opened */
{
up(&ms_ptr->sem);
return retval;
}
/* fake sending the data out a hardware port by
* writing it to the kernel debug log.
*/
printk(KERN_DEBUG "%s - ", __FUNCTION__);
for (i = 0; i < count; ++i)
printk("%02x ", tty_buff[i]);
printk("\n");
return 0;
}
// Define the operations for tty driver in tty_operations struct //
static struct tty_operations tty_ms_ops = {
.open = tty_ms_open,
.close = tty_ms_close,
.write = tty_ms_write,
//.set_termios = tty_ms_set_termios,
};
///////////////////////////////////////// Module Initialization Starts ////////////////////////////////////
static struct tty_driver *tty_ms_driver;
static int tty_ms_init(void)
{
// static int result;
static int retval,iter;
// Allocate the tty_driver struct for this driver //
tty_ms_driver = alloc_tty_driver(MS_TTY_NUM_DEV);
if (!tty_ms_driver)
return -ENOMEM; // Error NO Memory , allocation failed
else
printk(KERN_INFO "tty_driver structure allocated..!!"); //debug line
// Initialize the allocated tty_driver structure //
tty_ms_driver->magic=TTY_DRIVER_MAGIC;
tty_ms_driver->owner = THIS_MODULE;
tty_ms_driver->driver_name = "tty_ms";
tty_ms_driver->name = "ttyms";
tty_ms_driver->major = MS_TTY_MAJOR,
tty_ms_driver->type = TTY_DRIVER_TYPE_SERIAL,
tty_ms_driver->subtype = SERIAL_TYPE_NORMAL,
tty_ms_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV,
tty_ms_driver->init_termios = tty_std_termios;
tty_ms_driver->init_termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | CLOCAL;
tty_set_operations(tty_ms_driver, &tty_ms_ops);
printk(KERN_INFO "allocated tty_driver structure -INITIALIZED."); //debug line
//// Register this driver with the tty core ////
retval = tty_register_driver(tty_ms_driver);
if (retval) {
printk(KERN_ERR "failed to register tty_ms driver\n tty registration returned %d", retval);
put_tty_driver(tty_ms_driver);
return retval;
}
//// Register the tty devices(nodes) with the tty core ////
for (iter = 0; iter < MS_TTY_NUM_DEV ; ++iter)
tty_register_device(tty_ms_driver, iter, NULL);
return 0; // All initializations done
} // init func ends
///////////////////////////////////////// Module Initialization Ends ////////////////////////////////////
///////////////////////////////////////// Module cleanup Starts ////////////////////////////////////
static void tty_ms_terminate(void)
{
static int iter;
struct ms_tty_serial *tty_ser;
printk(KERN_ALERT "tty_ms driver: Unloading...\n");
for(iter=1;iter<=MS_TTY_NUM_DEV;iter++)
tty_unregister_device(tty_ms_driver,iter); //unregister all the devices, from tty layer
tty_unregister_driver(tty_ms_driver); // Now unregister the driver from tty layer
/* shut down all of the timers and free the memory */
for (iter = 0; iter < MS_TTY_NUM_DEV; ++iter) {
tty_ser = ms_tty_table[iter];
if (tty_ser) {
/* close the port */
while (tty_ser->open_count)
do_close(tty_ser);
/* shut down our timer and free the memory */
del_timer(tty_ser->timer);
kfree(tty_ser->timer);
kfree(tty_ser);
ms_tty_table[iter] = NULL;
}
}
dev_t devno=MKDEV(major_num,0); // wrap major/minor numbers in a dev_t structure , to pass for deassigning.
unregister_chrdev_region(devno,MS_TTY_NUM_DEV);
}
///////////////////////////////////////// Module cleanup ends ////////////////////////////////////
module_init(tty_ms_init);
module_exit(tty_ms_terminate);

Resources