Linux Kernel IIO events sysfs files only readable - linux

I have the problem that I registered IIO events for rising and falling thresholds.
I can see the sysfs files in events subfolder and can read them, but when I try to write a new threshold it says "permission denied".
following setup:
static const struct iio_event_spec as6200_events[] = {
{
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_RISING,
.mask_separate = BIT(IIO_EV_INFO_VALUE),
}, {
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_FALLING,
.mask_separate = BIT(IIO_EV_INFO_VALUE),
}
};
static const struct iio_chan_spec as6200_channels[] = {
{
.type = IIO_TEMP,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_PROCESSED) |
BIT(IIO_CHAN_INFO_SCALE),
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SAMP_FREQ),
.event_spec = as6200_events,
.num_event_specs = ARRAY_SIZE(as6200_events),
}
};

finding: it works when I change the permissions of the in_temp_thresh_rising_value file to 666 via sudo. But why is it not created with this permissions via IIO subsystem?
This is common practice for sysfs files, as writing to those files can alter system's behavior and even compromise or break the system. So if you want to write to those files, you should do that from root, or add your user to corresponding group, or change that file mode (by udev rule or by hand).
Here is how it's done in IIO code:
IIO sysfs node names are derived from next tables in drivers/iio/industrialio-event.c: iio_ev_type_text, iio_ev_dir_text and iio_ev_info_text
node creation path is next: iio_device_add_event() -> __iio_add_chan_devattr() -> __iio_device_attr_init()
file mode for sysfs node is being set in __iio_device_attr_init():
for reading: dev_attr->attr.mode |= S_IRUGO;
so every user can read the node (because S_IRUGO allows Reading for User, Group and Others)
for writing: dev_attr->attr.mode |= S_IWUSR;
so it only can be written by root (because S_IWUSR allows writing only for file owner, which is root)

Another solution to this problem is to use a combination of libiio's network and local contexts. In this case, a libiio daemon would be started with the appropriate privileges to write to the sysfs files, and the user application would then connect with this daemon using a libiio network context.

Related

Simple GPIO Device Tree Example for Beaglebone Black Deb 10.3

My goal is to write a simple .dts file (to be compiled to .dtbo using DT 1.4.4) to configure a GPIO output on boot on a Beaglebone Black Rev C running Debian 10.3
I intend to place the .dtbo in /lib/firmware and then specify it in /boot/uEnv.txt
I understand some parts of the .dts file and have tried decompiling exisiting .dtbo files in /lib/firmware/ for guidance but none of them are a simple GPIO output example. A lot of online resources involve make and make install but I believe DT should be able to handle it by now right?
I was able to get the following to compile but with issue:
/* dtc -O dtb -o BB-P8_13-LED.dtbo -b 0 -# BB-P8_13-LED-00A0.dts */
/dts-v1/;
/plugin/;
/ {
compatible = "ti,beaglebone-black";
/* identification */
part-number = "BB-P8_13-LED";
version = "00A0";
/* state the resources this cape uses */
exclusive-use =
/* the pin header uses */
"P8.13", /* GPIO_23 */
/* the hardware ip uses */
"gpio23";
fragment#0 {
target = <&am33xx_pinmux>;
__overlay__ {
bb_gpio23_pin: pinmux_bb_gpio23_pin {
pinctrl-single,pins = < 0x024 0x07 >; /*P8_13 GPIO23 MODE7*/
};
};
};
fragment#1 {
target = <&gpio23>;
__overlay__ {
leds {
status = "okay";
pinctrl-names = "default";
pinctrl-0 = <&bb_gpio23_pin>;
compatible = "gpio-leds";
P8_13 {
label = "P8_13";
default-state = "on";
};
};
};
};
};
Q: Why does loading this .dtbo in /boot/uEnv.txt cause all other GPIOs to disappear from /sys/class/gpio/? I thought fragment0 was for excluding a single gpio, not all of them.
###Additional custom capes
uboot_overlay_addr4=/lib/firmware/BB-P8_13-LED-00A0.dtbo
Q: Where are the files for controlling the GPIO (for testing) or rather what can I add to my .dts file so the gpio23 still appears in /sys/class/gpio or even /sys/class/leds? Ultimately I want to be able to control this GPIO with Node-RED.
Q: Do I need to be consistent with my use of P8.13 vs. P8_13? I think I'm mixing up terminology used in .dts files that get compiled with make vs DT.
Q: I think my fragment#1 P8_13 child node is missing something to specify the gpio bank and active high/low setting. Something like "gpios = <&gpio3 19 GPIO_ACTIVE_HIGH>;" Where can I look to research which bank GPIO23 is in? What does the '19' mean in that statement?
So Dr. Derek Molly did a really nice job of laying this out and I was able to use the example in his repo. Here is a page he made for explaining how to configure GPIO at boot using Device Tree Overlays:
http://derekmolloy.ie/beaglebone/beaglebone-gpio-programming-on-arm-embedded-linux/
Even though his solution is for kernel 3.8 I was able to get the following to compile on 4.19
/* dtc -O dtb -o BB-P8_13-LED-00A0.dtbo -b 0 -# BB-P8_13-LED-00A0.dts */
/dts-v1/;
/plugin/;
/{
compatible = "ti,beaglebone-black";
part-number = "BB-P8_13-LED";
version = "00A0";
fragment#0 {
target = <&am33xx_pinmux>;
__overlay__ {
pinctrl_test: BB-P8_13-LED {
pinctrl-single,pins = <
0x024 0x27 /* P8_13 9 PULLUP ENABLED OUTPUT MODE7 - The LED Output */
>;
};
};
};
fragment#1 {
target = <&ocp>;
__overlay__ {
test_helper: helper {
compatible = "bone-pinmux-helper";
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_test>;
status = "okay";
};
};
};
};
All that needs to be edited for a different GPIO pin is the "0x024" (address offset) and the "0x27" to set various aspects of the GPIO like pullup vs. pulldown and pinmux mode. Derek Molly has an older version of his guide which has the table for building the pinmux binary values (that need to be converted to hex): http://derekmolloy.ie/gpios-on-the-beaglebone-black-using-device-tree-overlays/
Most of the information is available in the Beaglebone SRM which I should probably read at some point.
The .dts file in my first answer did not fix my problem. GPIO P8_13 still boots as an input. After more digging and testing I have discovered it is NOT possible to make a GPIO direction survive a reboot. It will always boot to the default and the best you can do is enable a pullup or pulldown resistor to keep the pin high or low until a custom service file (or program) can write to /sys/class/gpio/gpioXXX/direction. I even tried decompiling am335x-boneblack.dtb, editing it, and re-compiling with no luck.
This is sad and incredibly frustrating. What good is an output that flickers during reboot? Guess I'll have to compensate with fancy external circuitry.
Per the original question, you can author a dts file where the GPIO remains in /sys/gpio/class/. See the article I wrote below for an example that works this way.
https://takeofftechnical.com/beaglebone-black-led-control/

Cleanest way to fix Windows 'filename too long' CI tests failure in this code?

I'm trying to solve this Windows filename issue
Basically our CI job fails, with the 'filename too long' error for Windows.
warning: Could not stat path 'node_modules/data-validator/tests/data/data-examples/ds000247/sub-emptyroom/ses-18910512/meg/sub-emptyroom_ses-18910512_task-noise_run-01_meg.ds/sub-emptyroom_ses-18910512_task-noise_run-01_meg.acq': Filename too long
I've read the docs for Node's path module, which seems like a possible solution. I also read about a Windows prefix (\\?\) to bypass the MAX_PATH...but have no idea how to implement these in a clean way.
This part of the codebase with the tests that are failing. The hardcoded path (testDatasetPath) is likely part of the problem.
function getDirectories(srcpath) {
return fs.readdirSync(srcpath).filter(function(file) {
return (
file !== '.git' && fs.statSync(path.join(srcpath, file)).isDirectory()
)
})
}
var missing_session_files = //array of strings here
const dataDirectory = 'data-validator/tests/data/'
function createDatasetFileList(path) {
const testDatasetPath = `${dataDirectory}${path}`
if (!isNode) {
return createFileList(testDatasetPath)
} else {
return testDatasetPath
}
}
createFileList function
function createFileList(dir) {
const str = dir.substr(dir.lastIndexOf('/') + 1) + '$'
const rootpath = dir.replace(new RegExp(str), '')
const paths = getFilepaths(dir, [], rootpath)
return paths.map(path => {
return createFile(path, path.replace(rootpath, ''))
})
}
tl;dr A GitLab CI Job fails on Windows because the node module filenames become too long. How can I make this nodejs code OS agnostic?
This is a known error in the Windows Environment, however, there is a fix..
If you're using an NTFS based filesystem, you should be able to enable long paths in
Local Computer Policy > Computer Configuration > Administrative Templates > System > Filesystem > NTFS
This is also specified in the document you just linked, and theoretically, should work. However, the path shouldn't really be longer than 32 bits,
This will come with some performance hits, but should get the job done.
Also, you should preferably switch to a better package or search for alternatives. If this is your own package, maybe restructure it?
Finally, if none of these work, move your project folder directly to your data drive, (C:\) this will cut down on the other nested and parent folders.
This is inherently bad, and you may run into issues during deployment, if you choose to do it.

Windows UWP CreateFIle2 cannot read file in ApplicationData.LocalFolder

I am trying to build UWP app in C#. My app has a native library written in C++. Whenever the app tries to read a file in ApplicationData.LocalFolder, CreateFile2 api is returning ERROR_NOT_SUPPORTED_IN_APPCONTAINER. The file exists in the path specified to this api.
This is the sequence of operation in my app.
Launch app. App creates file & writes some data
Later on based on user input app tries to read data in this file
Step 1 is working fine. App is able to create the file & write data in it. Only when app tries to access it later on, does it get this error.
I get the path to ApplicationData.LocalFolder using
Windows.Storage.ApplicationData.Current.LocalFolder.Path
This is the actual path I see in the app:
C:\Users\xxxxx\AppData\Local\Packages\ac7a11e4-c1d6-4d37-b9eb-a4b0dc8f67b8_yyjvd81p022em\LocalState\temp.txt
My code is as below:
CREATEFILE2_EXTENDED_PARAMETERS ms_param = {0};
ms_param.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
ms_param.dwFileAttributes = FILE_ATTRIBUTE_READONLY;
ms_param.dwFileFlags = FILE_FLAG_NO_BUFFERING;
ms_param.dwSecurityQosFlags = SECURITY_DELEGATION;
ms_param.lpSecurityAttributes = NULL;
ms_param.hTemplateFile = NULL;
g_hfile = CreateFile2(filename, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, OPEN_EXISTING, &ms_param);
if (g_hfile == INVALID_HANDLE_VALUE)
{
return GetLastError();
}
I tried CreateFile2 with both OPEN_EXISTING & OPEN_ALWAYS option for dwCreationDisposition parameter, but I see the same error in either case.
I had similar issue with CreateFile2 earlier. But that was an problem with my app & I have fixed that issue. This time though the file is available within the LocalFolder, still I get the error.
The problem here is related to the dwSecurityQosFlags you've set in CREATEFILE2_EXTENDED_PARAMETERS.
When called from a Windows Store app, CreateFile2 is simplified. You can open only files or directories inside the ApplicationData.LocalFolder or Package.InstalledLocation directories. You can't open named pipes or mailslots or create encrypted files (FILE_ATTRIBUTE_ENCRYPTED).
The dwSecurityQosFlags parameter specifies SQOS information. In Windows Stroe app, we can only set it to SECURITY_ANONYMOUS. Using other flag will raise ERROR_NOT_SUPPORTED_IN_APPCONTAINER exception. This indicates that it is not supported in UWP app.
Following is the code I used to test:
StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
String^ path = localFolder->Path;
path += L"\\MyFile.txt";
CREATEFILE2_EXTENDED_PARAMETERS ms_param = { 0 };
ms_param.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
ms_param.dwFileAttributes = FILE_ATTRIBUTE_READONLY;
ms_param.dwFileFlags = FILE_FLAG_NO_BUFFERING;
ms_param.dwSecurityQosFlags = SECURITY_ANONYMOUS;
ms_param.lpSecurityAttributes = NULL;
ms_param.hTemplateFile = NULL;
HANDLE g_hfile = CreateFile2(path->Data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, &ms_param);
DWORD error = GetLastError();
If I don't have "MyFile.txt" under LocalFolder, I will get ERROR_FILE_NOT_FOUND exception, otherwise it will be ERROR_SUCCESS.

Using persistent storage in linux kernel

I am trying to use persistent store(Pstore) available in linux kernel but somehow I am not getting the logs in case of kernel panics. I made the following kernel modules in kernel config file as built in:
CONFIG_PSTORE=y
CONFIG_PSTORE_CONSOLE=y
CONFIG_PSTORE_RAM=y
Now a/c to documentation pstore I should get the logs on next reboot in /sys/fs/pstore/... (or /dev/pstore/...) but couldn't find the logs there.
Am I missing something...?
Besides the kernel config options:
CONFIG_PSTORE=y
CONFIG_PSTORE_CONSOLE=y
CONFIG_PSTORE_PMSG=y
CONFIG_PSTORE_RAM=y
I had to reserve a part of memory in which the logs will be saved. I did this through the device tree like this:
reserved-memory {
#address-cells = <2>;
#size-cells = <2>;
ranges;
pstore: pstore#FF00000 {
no-map;
reg = <0x0 0xFF00000 0x0 0x00100000>; /* pstore/ramoops buffer
starts at memory address 0xFF00000 and is of size 0x00100000 */
};
};
ramoops {
compatible = "ramoops";
memory-region = <&pstore>;
record-size = <0x0 0x00020000>;
console-size = <0x0 0x00020000>;
pmsg-size = <0x0 0x00020000>;
};
Also, check if the following kernel patch is present (which is needed for the kernel to be able to parse the options given above):
https://android-review.googlesource.com/#/c/kernel/common/+/195160/
Another way is to turn it on through the kernel cmdline, for example:
ramoops.mem_address=0x30000000 ramoops.mem_size=0x100000 memmap=0x100000$0x30000000
check if below config options are enabled
CONFIG_PSTORE=y
CONFIG_PSTORE_CONSOLE=y
**CONFIG_PSTORE_FTRACE=y**
CONFIG_PSTORE_RAM=y
But why /dev/pstore file?, it's not needed,
To check if console-ramoops working,
do echo Trigger a kernel panic using command
echo c > /proc/sysrq-trigger
then reboot device manually. after system boots up, run command "/sys/fs/pstore/console-ramoops", check if console_ramoops has got anything logged.
You have to declare platform data as described by #shadowfire. But all kernel cannot use device tree for ramoops.
Generic way to do it, is to add in the source file for your hardware (example for mx6ul : arch/arm/mach-imx/mach-imx6ul.c) the following piece of code in the function xxx_init_machine :
#include <linux/pstore_ram.h>
[...]
static struct ramoops_platform_data ramoops_data = {
.mem_size = <...>,
.mem_address = <...>,
.mem_type = <...>,
.record_size = <...>,
.dump_oops = <...>,
.ecc = <...>,
};
static struct platform_device ramoops_dev = {
.name = "ramoops",
.dev = {
.platform_data = &ramoops_data,
},
};
[... inside xxx_init_machine ...]
int ret;
ret = platform_device_register(&ramoops_dev);
if (ret) {
printk(KERN_ERR "unable to register platform device\n");
return ret;
}
More info available in documentation : ramoops
Do you have logs in dmesg which can confirm that ramoops is enabled successfully ?
# dmesg | grep -i "pstore\|ramoops"
console [pstore-1] enabled
pstore: Registered ramoops as persistent store backend
ramoops: attached 0x20000#0x80000000, ecc: 0/0
Moreover you must mount pstore directory, that's why the directory is empty on your rootfs :
mount -t pstore -o kmsg_bytes=8000 - /sys/fs/pstore
Default size for the mount is 10 Kbytes in you don't set the kmsg_bytes option. You can use /etc/fstab to mount it automatically.

intel XDK directory browsing

I'm trying to get a way to reach and parse all JSON file from a directory, witch inside an Intel Xdk project. All files in my case stored in '/cards' folder of the project.
I have tried to reach theme with fs.readdirSync('/cards') method, but that wasn't pointed to the location what I expected, and I haven't got luck with 'intel.xdk.webRoot' path.
With the simulator I've managed to get files, with a trick:
fs.readdirSync(intel.xdk.webRoot.replace('localhost:53862/http-services/emulator-webserver/ripple/userapp/', '')+'cards');
(intel.xdk.webRoot contains absolute path to my '/cards' folder)
and its work like a charm, but it isn't working in any real device what I'd like to build it.
I have tried it with iOS7 and Android 4.2 phones.
Please help me to use in a great way the fs.readdirSync() method, or give me some alternate solution.
Thanks and regards,
satire
You can't use nodejs api's on mobile apps. It is a bug that the XDK emulator lets you do it. The bug is fixed in the next release of XDK.
You could write a node program that scans the directory and then writes out a js file with the contents of the directory. You would run the node script on your laptop before packaging the app in the build tab. The output would look like this:
files.js:
dir = {files: ['file1.txt', 'file2.txt']}
Then use a script tag to load it:
And your js can read the dir variable. This assumes that the contents does not change while the app is running.
The location of your application's root directory will vary depending on the target platform and can also vary with the emulator and the debug containers (e.g., App Preview versus App Analyzer). Here's what I've done to locate files within the project:
// getWebPath() returns the location of index.html
// getWebRoot() returns URI pointing to index.html
function getWebPath() {
"use strict" ;
var path = window.location.pathname ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return 'file://' + path ;
}
function getWebRoot() {
"use strict" ;
var path = window.location.href ;
path = path.substring( 0, path.lastIndexOf('/') ) ;
return path ;
}
I have not been able to test this exhaustively, but it appears to be working so far. Here's an example where I'm using a Cordova media object and want it to play a file stored locally in the project. Note that I have to "special case" the iOS container:
var x = window.device && window.device.platform ;
console.log("platform = ", x) ;
if(x.match(/(ios)|(iphone)|(ipod)|(ipad)/ig)) {
var media = new Media("audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
else {
var media = new Media(getWebRoot() + "/audio/bark.wav", mediaSuccess, mediaError, mediaStatus) ;
}
console.log("media.src = ", media.src) ;
media.play() ;
Not quite sure if this is what you are looking for...
You will need to use the Cordova build in the Intel XDK, here is information on building with Cordova:
https://software.intel.com/en-us/html5/articles/using-the-cordova-for-android-ios-etc-build-option
And a DirectoryReader example:
function success(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
}
}
function fail(error) {
alert("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);

Resources