How Device unbinding from driver works? Does unregister of device waits for fops to complete? - linux-device-driver

I am trying to understand how device unbinding works?
I have a module with which two devices are attached.
Dev1
Dev2
Devices dev1 and dev2 are created in probe function.
Each device(dev1/dev2) creates one more char device under it.
Basically the module has probe and remove
Probe creates device which registers one more char device (with char device own file operations)
remove functionality is for the module(dev1/dev2)
Dev1 & Dev 2, registered char device file operations includes ioctl.
Issue:
Unbinding of device dev1 or dev2 does not wait for char device file operations to finish.
So every time unbind of device happens while ioctl is in progress, system gives oops.
Tried to open and release in fops for the device but didnt help.
Include debug Print in char device fops, release,
the debug print is seen after the device is unbinded.(verified with debug print in remove of dev1/dev2)
Current debug print seq:
~~~ Device removed ~~~ (from module remove)
~~~ Char device released ~~~ (from char device)
Expectation:
Unbinding of device(dev1/dev2) should wait for the char device fops to complete.
Expected debug print seq:
~~~ Char device released ~~~ (from char device)
~~~ Device removed ~~~ (from module remove)

Related

Using srec_cat to merge OpenBLT bootloader with firmware for initial production flash

Attempting to combine OpenBLT bootloader image with a firmware image to make one flash for production using srec_cat. "warning: no execution start address record" is evident in the firmware.srec.
Flashing the bootloader and using the Microboot utility over USB with the firmware srec works perfectly fine. Would like to have one flash binary for production purposes.
srec_cat bootloader.srec firmware.srec -o combined.srec
Yields a "warning: no execution start address record". Attempting to ignore the warning and flash the combined.srec to STM32 hardware creates a non-booting flash.
srec_info bootloader.srec output:
Format: Motorola S-Record
Header: "bin/bootloader.srec"
Execution Start Address: 080001D9
Data: 08000000 - 0800381F
srec_info firmware.srec output:
Format: Motorola S-Record
Header: "http://srecord.sourceforge.net/"
srec_info: fw-latest.srec: 12918: warning: no execution start address record
Data: 08008000 - 0806CE43

Zephyr-RTOS logging with DMA on STM32L432KC

I'm trying to run Zephyr Logging by using DMA on UART on STM32L432KC.
That's simple main loop:
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(example, LOG_LEVEL_DBG);
int main(void)
{
while (1) {
LOG_INF("main loop");
k_msleep(1000);
}
}
That's full configuration:
CONFIG_SOC_SERIES_STM32L4X=y
CONFIG_SOC_STM32L432XX=y
# Enable MPU
CONFIG_ARM_MPU=y
# Enable HW stack protection
CONFIG_HW_STACK_PROTECTION=y
# enable uart driver
CONFIG_SERIAL=y
# enable GPIO
CONFIG_GPIO=y
# Enable Clocks
CONFIG_CLOCK_CONTROL=y
# console
CONFIG_CONSOLE=y
CONFIG_UART_CONSOLE=y
CONFIG_UART_ASYNC_API=y
# enable DMA
CONFIG_DMA=y
# enable pin controller
CONFIG_PINCTRL=y
# config logging
CONFIG_LOG=y
CONFIG_LOG_BACKEND_UART_ASYNC=y
CONFIG_LOG_MODE_IMMEDIATE=y
Then build it and flash:
west flash -b nucleo_l432kc
In logs I see following output:
*** Booting Zephyr OS build zephyr-v3.2.0-863-g78809549ee4c ***
[00:00:01.001,000] <inf> example: main loop
When I change CONFIG_LOG_MODE_IMMEDIATE=y to CONFIG_LOG_MODE_DEFERRED=y it prints log every second like I expect.
I discovered that code stops here on k_sem_take(&sem, K_FOREVER) and this uart_callback is never called to release this mutex.
Also discovered when following options are enabled it's working fine with CONFIG_LOG_MODE_DEFERRED=y option:
CONFIG_LOG_PROCESS_THREAD=y
CONFIG_LOG_PROCESS_THREAD_SLEEP_MS=100
But that makes me wondering why another thread must be created? DMA is no blocking. Really confusing.
What am I missing? I would like to delegate all logging to DMA buffer with Logging subsystem features, without additional threads and buffering. Is there someone experienced who can point what is wrong?

Why might `i2c_smbus_write_byte_data` be returning "Operation not permitted" on uClinux 2.4?

I am writing a C program with the aim of configuring a peripheral device (the CS5368 ADC) via the I2C interface of a Dante Brooklyn II, a board based on a Microblaze soft-core processor running uClinux 2.4.
I have implemented the configuration following the Dante OEM docs for guidance, however when running my program I am encountering an "Operation not permitted" (EPERM) error when attempting to write data to I2C using i2c_smbus_write_byte_data.
Here is the section of code containing the culprit call to i2c_smbus_write_byte_data:
// Set ADC I2S to "Slave mode all speeds".
printf("Set the CS5368 I2S mode to slave\n");
unsigned char adc_dif = 0x01; // I2S mode
unsigned char adc_mode = 0x03; // Slave mode all speeds
unsigned char data = 0x90 | (adc_dif << 2) | adc_mode;
result = i2c_smbus_write_byte_data(i2c_fd, CS5368_GCTL_MDE, data);
if (result < 0) {
perror("Failed to write to the 'Global Mode Control' register");
return -1;
}
Here is the code within context of the full source of the small program. The program begins by resetting the CS5368 via a GPIO pin before doing the configuration via I2C.
EPERM is returned whether or not I have the CS5368 wired up. I've been able to successfully configure the CS5368 using the I2C interface of an Arduino Uno, so the issue does not appear to be related to the CS5368.
To run the program I login to the board via telnet as root, so I doubt the error has anything to do with user permissions.
The OEM docs state:
The Brooklyn II module can operate as an I2C controller running at
100Khz and using 7 bit addressing mode. It supports multi-master
operation. I2C devices can be accessed from user application running
on the Brooklyn II module. The interface supports the SMBus (System
Management Bus) protocol, which is a subset from the I2C protocol.
It goes on to list the supported i2c_smbus_* functions including i2c_smbus_write_byte_data, so the issue does not appear to be related to lack of support for SMBus or I2C.
I came across a related issue where a user was getting an EPERM error code when attempting to use the I2C write API, however the solution appears to have been to use the i2c_smbus_* API instead which I am already doing.
Any advice on what could be causing this error code to be returned or how to debug the issue further would be greatly appreciated!
Edit: In case it helps, here is the full output, starting from logging onto the board via telnet after having moved the exe to /tmp via ftp:
$ telnet 169.254.72.245
Trying 169.254.72.245...
Connected to 169.254.72.245.
Escape character is '^]'.
login: root
Password:
BusyBox v1.23.2 (2018-05-31 11:33:18 AEST) hush - the humble shell
/ # cd /tmp
/var/tmp # ./cs5368-i2c-config
Open GPIO device
Set GPIO tristate outputs
Set GPIO pins low
Sleep for 10 secs
Set GPIO pins high
Close GPIO file descriptor
Searching for I2C device
Opening /dev/i2c-0
Setting I2C_SLAVE 4c...
I2C Interface found: /dev/i2c-0
Set the CS5368 as the slave
Set the CS5368 I2S mode to slave
Failed to write to the 'Global Mode Control' register: Operation not permitted

In QT how can I detect when a USB port switches from serial mode to DFU when connected to an STM32

I have a Qt5.12.4 MinGw64 app where I want to catch a USB event. In Windows 10 the MS driver for STM/USB emits error messages and I can use that as a trigger. Inelegant but it works, until I try to run it in a Win7-8.1 app where the driver is a third party STM driver with a VCP wrapper. I am thinking I need to adopt libusb to try and catch the ports change of state, but I am at a loss as how to proceed. I can see the port info in Device Manager, I just dont know how to get to it. Some of the questions going through my head....
1) Can I just make an OS call to read the port info? (if so, how?)
2) Can libusb and QSerialport co-exist on the same port?
3) What calls to LibUSB1.0 do I make to query the port status?
4) Is there a Windows cli utility like lsusb (wmic??) where I could scrape the data?
5) Which solution is likely to be the best cross platform solution?
I am using this trigger to start dfuse as a process that does a firmware update automatically on my STM board.
I have looked over the libusb1.0 docs but I do not understand just how I can use it. If that is correct solution, an example of how to query the Com port data and state would be most appreciated.
I tried using qDebug() to print out all of the serialportInfo data, while in serial or DFU state, but there is nothing there that is useful that I can use as a trigger.
USB serial mode = Serial port info is: ("COM3", "USB Serial Device", "Microsoft", "00000000001A", "\\.\COM3", "483", "5740", "1", " no data", "1")
USB DFU mode = Serial port info is: ("COM3", "N/A", "N/A", "N/A", "\\.\COM3", "N/A", "N/A", "no data", " no data", "no data")
I need some direction as to how to grab this port info so I dont really have any code that matters, but I am including an excerpt of my working process function.
This code works just fine to actually perform the firmware load. I just need a way to actually trigger it from a USB port change of state
void updateDevice_Dialog::update_firmware(QString fileName)
{
qDebug() << "Updating firmware: " << fileName ;
QDir dir;
ui->progress_label->setText("Preparing to update Firmware .....");
if(dir.setCurrent(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)+"/firmware"))
{
QSettings settings;
QString comPort = settings.value("USBPort").toString();
ui->progress_label->setText("Setting port to: "+comPort+" and starting download .....");
ui->avr_progressBar->setValue(0);
ui->avr_progressBar->setRange(0,100);
ui->avr_progressBar->setHidden(false);
progress_steps = 0; //reset avrProcess line output counter;
qDebug() << "Starting process for stm-dfu on serial port: " << comPort;
connect(avr_Process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(process_error(QProcess::ProcessError)));
connect(avr_Process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished(int,QProcess::ExitStatus)));
connect(avr_Process,SIGNAL(readyReadStandardOutput()),this,SLOT(process_readLine()));
connect(avr_Process,SIGNAL(errorOccurred(QProcess::ProcessError)),avr_Process,SLOT(kill()));
connect(avr_Process,SIGNAL(error(QProcess::ProcessError)),ui->avr_progressBar,SLOT(close()));
QString dfu_command = "\""+QCoreApplication::applicationDirPath()+"/Tools/\"dfusecommand -c -d --v --fn "
"\""+QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)+"/firmware/\""+fileName;
qDebug().noquote() << "dfu command string is: "<< dfu_command << " Current dir is: " << dir.currentPath();
avr_Process->start(dfu_command);
avr_Process->waitForFinished(20000);
}
}
From the perspective of the host system, rebooting the microcontroller into DFU will look like the original device was disconnected, and a completely different device was plugged in shortly afterwards.
If you need to watch for this, set up a libusb hotplug callback so that you'll be notified when the DFU device is attached.

stm32 factory bootloader possibly overwritten with openocd?

tl;dr: flashed firmware to 0x00000000 instead of 0x08000000, am I lost?
Hello,
my device is based on a STM32F103CBTx which came with a proprietary firmware and had readout protection on.
I connect to it with a ST-Link v2 SWDIO and SWCLK connected to PA13 and PA14 and this command:
sudo openocd -f /usr/share/openocd/scripts/interface/stlink-v2.cfg -f /usr/share/openocd/scripts/target/stm32f1x.cfg
I don't remember how I removed flash protection, but it worked as the original firmware didn't work anymore. Then I created a simple hello world firmware which pulls up and down three gpios and flashed it. The gpios are pulled up and down in 700ms intervals.
After flashing, I can't connect with openocd anymore. I forgot to specify the offset, the manual says the offset defaults to 0 and as it worked, I suppose instead of the boot loader my shitty hello world is pulling up and down some random pins happily… Is this possible? All other threads I found say the boot loader is write protected.
This is the last contact I had:
> halt
halt
target halted due to debug-request, current mode: Handler HardFault
xPSR: 0x01000003 pc: 0xfffffffe msp: 0xffffffdc
> flash write_image erase fw.hex
flash write_image erase fw.hex
auto erase enabled
target halted due to breakpoint, current mode: Handler HardFault
xPSR: 0x61000003 pc: 0x2000003a msp: 0xffffffdc
wrote 4096 bytes from file fw.hex in 0.285697s (14.001 KiB/s)
> reset
reset
jtag status contains invalid mode value - communication failure
Polling target stm32f1x.cpu failed, trying to reexamine
Examination failed, GDB will be halted. Polling again in 100ms
Any directions highly appreciated.
Edit:
What I get now, also tried another st-link:
% sudo openocd -f /usr/share/openocd/scripts/interface/stlink-v2.cfg -f /usr/share/openocd/scripts/target/stm32f1x.cfg
Open On-Chip Debugger 0.10.0
Licensed under GNU GPL v2
For bug reports, read
http://openocd.org/doc/doxygen/bugs.html
Info : auto-selecting first available session transport "hla_swd". To override use 'transport select '.
Info : The selected transport took over low-level target control. The results might differ compared to plain JTAG/SWD
adapter speed: 1000 kHz
adapter_nsrst_delay: 100
none separate
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : Unable to match requested speed 1000 kHz, using 950 kHz
Info : clock speed 950 kHz
Info : STLINK v2 JTAG v17 API v2 SWIM v4 VID 0x0483 PID 0x3748
Info : using stlink api v2
Info : Target voltage: 3.244356
Error: init mode failed (unable to connect to the target)
in procedure 'init'
in procedure 'ocd_bouncer'
flashed firmware to 0x00000000 instead of 0x08000000, am I lost?
No, it doesn't matter at all, they are the same.
After reset, the MCU loads the word at address 0 in SP, and the next one at address 4 in PC. The BOOT0 and BOOT1 pins control which memory gets mapped to 0x00000000. Usually, BOOT0 is tied low, and flash memory at 0x08000000 gets mirrored at 0x00000000.
instead of the boot loader my shitty hello world is pulling up and down some random pins happily… Is this possible? All other threads I found say the boot loader is write protected.
The factory bootloader is indeed write protected, openocd can't overwrite it.
However, your application could have reconfigured the SWD pins, by writing a wrong value in GPIOA->CRH or AFIO->MAPR, thereby preventing openocd from working. It's the most common cause of this problem.
Fortunately, there is a way to recover.
Connect under Reset
If the reset pin of the controller is held low for a while when openocd is started, the application is prevented from starting, and messing up the GPIO configuration.
Openocd can do this automatically, when
It's told to do so, the line reset_config srst_only srst_nogate is present somewhere in the configuration script.
The MCU reset pin is connected to the debugger hardware, pin 15 on an official ST-Link/V2.
Or you can do it manually, by whatever means your board provides. If you are lucky, it has a reset button, if not, you must find a way to somehow ground the MCU reset pin.
Pull the reset pin low
Start openocd
Wait until the Info : Target voltage line appears. Maybe a second longer.
Release the reset pin.
It requires a bit of trial and error, you'll get better with practice.
Then you can flash your improved application, which carefully avoids reconfiguring the SWD pins.