CDev extract from drivers Device class hierarchy

- leave CDev shim for now until all usage is updated
This commit is contained in:
Daniel Agar
2018-08-27 13:14:15 -04:00
parent 6955272316
commit a2f4757e31
14 changed files with 802 additions and 623 deletions
+398
View File
@@ -0,0 +1,398 @@
/****************************************************************************
*
* Copyright (c) 2012-2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file CDev.cpp
*
* Character device base class.
*/
#include "CDev.hpp"
#include <cstring>
#include <px4_posix.h>
#include <drivers/drv_device.h>
namespace cdev
{
CDev::CDev(const char *devname) :
_devname(devname)
{
PX4_DEBUG("CDev::CDev");
int ret = px4_sem_init(&_lock, 0, 1);
if (ret != 0) {
PX4_ERR("SEM INIT FAIL: ret %d", ret);
}
}
CDev::~CDev()
{
PX4_DEBUG("CDev::~CDev");
if (_registered) {
unregister_driver(_devname);
}
if (_pollset) {
delete[](_pollset);
}
px4_sem_destroy(&_lock);
}
int
CDev::register_class_devname(const char *class_devname)
{
PX4_DEBUG("CDev::register_class_devname %s", class_devname);
if (class_devname == nullptr) {
return -EINVAL;
}
int class_instance = 0;
int ret = -ENOSPC;
while (class_instance < 4) {
char name[32];
snprintf(name, sizeof(name), "%s%d", class_devname, class_instance);
ret = register_driver(name, &fops, 0666, (void *)this);
if (ret == OK) {
break;
}
class_instance++;
}
if (class_instance == 4) {
return ret;
}
return class_instance;
}
int
CDev::unregister_class_devname(const char *class_devname, unsigned class_instance)
{
PX4_DEBUG("CDev::unregister_class_devname");
char name[32];
snprintf(name, sizeof(name), "%s%u", class_devname, class_instance);
return unregister_driver(name);
}
int
CDev::init()
{
PX4_DEBUG("CDev::init");
int ret = PX4_OK;
// now register the driver
if (_devname != nullptr) {
ret = register_driver(_devname, &fops, 0666, (void *)this);
if (ret == PX4_OK) {
_registered = true;
}
}
return ret;
}
/*
* Default implementations of the character device interface
*/
int
CDev::open(file_t *filep)
{
PX4_DEBUG("CDev::open");
int ret = PX4_OK;
lock();
/* increment the open count */
_open_count++;
if (_open_count == 1) {
/* first-open callback may decline the open */
ret = open_first(filep);
if (ret != PX4_OK) {
_open_count--;
}
}
unlock();
return ret;
}
int
CDev::close(file_t *filep)
{
PX4_DEBUG("CDev::close");
int ret = PX4_OK;
lock();
if (_open_count > 0) {
/* decrement the open count */
_open_count--;
/* callback cannot decline the close */
if (_open_count == 0) {
ret = close_last(filep);
}
} else {
ret = -EBADF;
}
unlock();
return ret;
}
int
CDev::ioctl(file_t *filep, int cmd, unsigned long arg)
{
PX4_DEBUG("CDev::ioctl");
int ret = -ENOTTY;
switch (cmd) {
/* fetch a pointer to the driver's private data */
case DIOC_GETPRIV:
*(void **)(uintptr_t)arg = (void *)this;
ret = PX4_OK;
break;
default:
break;
}
return ret;
}
int
CDev::poll(file_t *filep, px4_pollfd_struct_t *fds, bool setup)
{
PX4_DEBUG("CDev::Poll %s", setup ? "setup" : "teardown");
int ret = PX4_OK;
if (setup) {
/*
* Save the file pointer in the pollfd for the subclass'
* benefit.
*/
fds->priv = (void *)filep;
PX4_DEBUG("CDev::poll: fds->priv = %p", filep);
/*
* Lock against poll_notify() and possibly other callers (protect _pollset).
*/
ATOMIC_ENTER;
/*
* Try to store the fds for later use and handle array resizing.
*/
while ((ret = store_poll_waiter(fds)) == -ENFILE) {
// No free slot found. Resize the pollset. This is expensive, but it's only needed initially.
if (_max_pollwaiters >= 256 / 2) { //_max_pollwaiters is uint8_t
ret = -ENOMEM;
break;
}
const uint8_t new_count = _max_pollwaiters > 0 ? _max_pollwaiters * 2 : 1;
px4_pollfd_struct_t **prev_pollset = _pollset;
#ifdef __PX4_NUTTX
// malloc uses a semaphore, we need to call it enabled IRQ's
px4_leave_critical_section(flags);
#endif
px4_pollfd_struct_t **new_pollset = new px4_pollfd_struct_t *[new_count];
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
if (prev_pollset == _pollset) {
// no one else updated the _pollset meanwhile, so we're good to go
if (!new_pollset) {
ret = -ENOMEM;
break;
}
if (_max_pollwaiters > 0) {
memset(new_pollset + _max_pollwaiters, 0, sizeof(px4_pollfd_struct_t *) * (new_count - _max_pollwaiters));
memcpy(new_pollset, _pollset, sizeof(px4_pollfd_struct_t *) * _max_pollwaiters);
}
_pollset = new_pollset;
_pollset[_max_pollwaiters] = fds;
_max_pollwaiters = new_count;
// free the previous _pollset (we need to unlock here which is fine because we don't access _pollset anymore)
#ifdef __PX4_NUTTX
px4_leave_critical_section(flags);
#endif
if (prev_pollset) {
delete[](prev_pollset);
}
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
// Success
ret = PX4_OK;
break;
}
#ifdef __PX4_NUTTX
px4_leave_critical_section(flags);
#endif
// We have to retry
delete[] new_pollset;
#ifdef __PX4_NUTTX
flags = px4_enter_critical_section();
#endif
}
if (ret == PX4_OK) {
/*
* Check to see whether we should send a poll notification
* immediately.
*/
fds->revents |= fds->events & poll_state(filep);
/* yes? post the notification */
if (fds->revents != 0) {
px4_sem_post(fds->sem);
}
}
ATOMIC_LEAVE;
} else {
ATOMIC_ENTER;
/*
* Handle a teardown request.
*/
ret = remove_poll_waiter(fds);
ATOMIC_LEAVE;
}
return ret;
}
void
CDev::poll_notify(pollevent_t events)
{
PX4_DEBUG("CDev::poll_notify events = %0x", events);
/* lock against poll() as well as other wakeups */
ATOMIC_ENTER;
for (unsigned i = 0; i < _max_pollwaiters; i++) {
if (nullptr != _pollset[i]) {
poll_notify_one(_pollset[i], events);
}
}
ATOMIC_LEAVE;
}
void
CDev::poll_notify_one(px4_pollfd_struct_t *fds, pollevent_t events)
{
PX4_DEBUG("CDev::poll_notify_one");
/* update the reported event set */
fds->revents |= fds->events & events;
PX4_DEBUG(" Events fds=%p %0x %0x %0x", fds, fds->revents, fds->events, events);
if (fds->revents != 0) {
px4_sem_post(fds->sem);
}
}
int
CDev::store_poll_waiter(px4_pollfd_struct_t *fds)
{
// Look for a free slot.
PX4_DEBUG("CDev::store_poll_waiter");
for (unsigned i = 0; i < _max_pollwaiters; i++) {
if (nullptr == _pollset[i]) {
/* save the pollfd */
_pollset[i] = fds;
return PX4_OK;
}
}
return -ENFILE;
}
int
CDev::remove_poll_waiter(px4_pollfd_struct_t *fds)
{
PX4_DEBUG("CDev::remove_poll_waiter");
for (unsigned i = 0; i < _max_pollwaiters; i++) {
if (fds == _pollset[i]) {
_pollset[i] = nullptr;
return PX4_OK;
}
}
PX4_DEBUG("poll: bad fd state");
return -EINVAL;
}
} // namespace cdev
+300
View File
@@ -0,0 +1,300 @@
/****************************************************************************
*
* Copyright (c) 2012-2017 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file CDev.hpp
*
* Definitions for the generic base classes in the device framework.
*/
#ifndef _CDEV_HPP
#define _CDEV_HPP
#include <px4_config.h>
#include <px4_posix.h>
#ifdef __PX4_NUTTX
#include "nuttx/cdev_platform.hpp"
#else
#include "posix/cdev_platform.hpp"
#endif
namespace cdev
{
/**
* Abstract class for any character device
*/
class __EXPORT CDev
{
public:
/**
* Constructor
*
* @param name Driver name
* @param devname Device node name
*/
CDev(const char *devname);
virtual ~CDev();
virtual int init();
/**
* Handle an open of the device.
*
* This function is called for every open of the device. The default
* implementation maintains _open_count and always returns OK.
*
* @param filep Pointer to the NuttX file structure.
* @return OK if the open is allowed, -errno otherwise.
*/
virtual int open(file_t *filep);
/**
* Handle a close of the device.
*
* This function is called for every close of the device. The default
* implementation maintains _open_count and returns OK as long as it is not zero.
*
* @param filep Pointer to the NuttX file structure.
* @return OK if the close was successful, -errno otherwise.
*/
virtual int close(file_t *filep);
/**
* Perform a read from the device.
*
* The default implementation returns -ENOSYS.
*
* @param filep Pointer to the NuttX file structure.
* @param buffer Pointer to the buffer into which data should be placed.
* @param buflen The number of bytes to be read.
* @return The number of bytes read or -errno otherwise.
*/
virtual ssize_t read(file_t *filep, char *buffer, size_t buflen) { return -ENOSYS; }
/**
* Perform a write to the device.
*
* The default implementation returns -ENOSYS.
*
* @param filep Pointer to the NuttX file structure.
* @param buffer Pointer to the buffer from which data should be read.
* @param buflen The number of bytes to be written.
* @return The number of bytes written or -errno otherwise.
*/
virtual ssize_t write(file_t *filep, const char *buffer, size_t buflen) { return -ENOSYS; }
/**
* Perform a logical seek operation on the device.
*
* The default implementation returns -ENOSYS.
*
* @param filep Pointer to the NuttX file structure.
* @param offset The new file position relative to whence.
* @param whence SEEK_OFS, SEEK_CUR or SEEK_END.
* @return The previous offset, or -errno otherwise.
*/
virtual off_t seek(file_t *filep, off_t offset, int whence) { return -ENOSYS; }
/**
* Perform an ioctl operation on the device.
*
* The default implementation handles DIOC_GETPRIV, and otherwise
* returns -ENOTTY. Subclasses should call the default implementation
* for any command they do not handle themselves.
*
* @param filep Pointer to the NuttX file structure.
* @param cmd The ioctl command value.
* @param arg The ioctl argument value.
* @return OK on success, or -errno otherwise.
*/
virtual int ioctl(file_t *filep, int cmd, unsigned long arg);
/**
* Perform a poll setup/teardown operation.
*
* This is handled internally and should not normally be overridden.
*
* @param filep Pointer to the internal file structure.
* @param fds Poll descriptor being waited on.
* @param setup True if this is establishing a request, false if
* it is being torn down.
* @return OK on success, or -errno otherwise.
*/
virtual int poll(file_t *filep, px4_pollfd_struct_t *fds, bool setup);
protected:
/**
* Pointer to the default cdev file operations table; useful for
* registering clone devices etc.
*/
static const px4_file_operations_t fops;
/**
* Check the current state of the device for poll events from the
* perspective of the file.
*
* This function is called by the default poll() implementation when
* a poll is set up to determine whether the poll should return immediately.
*
* The default implementation returns no events.
*
* @param filep The file that's interested.
* @return The current set of poll events.
*/
virtual pollevent_t poll_state(file_t *filep) { return 0; }
/**
* Report new poll events.
*
* This function should be called anytime the state of the device changes
* in a fashion that might be interesting to a poll waiter.
*
* @param events The new event(s) being announced.
*/
virtual void poll_notify(pollevent_t events);
/**
* Internal implementation of poll_notify.
*
* @param fds A poll waiter to notify.
* @param events The event(s) to send to the waiter.
*/
virtual void poll_notify_one(px4_pollfd_struct_t *fds, pollevent_t events);
/**
* Notification of the first open.
*
* This function is called when the device open count transitions from zero
* to one. The driver lock is held for the duration of the call.
*
* The default implementation returns OK.
*
* @param filep Pointer to the NuttX file structure.
* @return OK if the open should proceed, -errno otherwise.
*/
virtual int open_first(file_t *filep) { return PX4_OK; }
/**
* Notification of the last close.
*
* This function is called when the device open count transitions from
* one to zero. The driver lock is held for the duration of the call.
*
* The default implementation returns OK.
*
* @param filep Pointer to the NuttX file structure.
* @return OK if the open should return OK, -errno otherwise.
*/
virtual int close_last(file_t *filep) { return PX4_OK; }
/**
* Register a class device name, automatically adding device
* class instance suffix if need be.
*
* @param class_devname Device class name
* @return class_instamce Class instance created, or -errno on failure
*/
virtual int register_class_devname(const char *class_devname);
/**
* Register a class device name, automatically adding device
* class instance suffix if need be.
*
* @param class_devname Device class name
* @param class_instance Device class instance from register_class_devname()
* @return OK on success, -errno otherwise
*/
virtual int unregister_class_devname(const char *class_devname, unsigned class_instance);
/**
* Get the device name.
*
* @return the file system string of the device handle
*/
const char *get_devname() { return _devname; }
/**
* Take the driver lock.
*
* Each driver instance has its own lock/semaphore.
*
* Note that we must loop as the wait may be interrupted by a signal.
*
* Careful: lock() calls cannot be nested!
*/
void lock() { do {} while (px4_sem_wait(&_lock) != 0); }
/**
* Release the driver lock.
*/
void unlock() { px4_sem_post(&_lock); }
px4_sem_t _lock; /**< lock to protect access to all class members (also for derived classes) */
private:
const char *_devname{nullptr}; /**< device node name */
px4_pollfd_struct_t **_pollset{nullptr};
bool _registered{false}; /**< true if device name was registered */
uint8_t _max_pollwaiters{0}; /**< size of the _pollset array */
uint8_t _open_count{0}; /**< number of successful opens */
/**
* Store a pollwaiter in a slot where we can find it later.
*
* Expands the pollset as required. Must be called with the driver locked.
*
* @return OK, or -errno on error.
*/
int store_poll_waiter(px4_pollfd_struct_t *fds);
/**
* Remove a poll waiter.
*
* @return OK, or -errno on error.
*/
int remove_poll_waiter(px4_pollfd_struct_t *fds);
/* do not allow copying this class */
CDev(const CDev &);
CDev operator=(const CDev &);
};
} // namespace cdev
#endif /* _CDEV_HPP */
+49
View File
@@ -0,0 +1,49 @@
############################################################################
#
# Copyright (c) 2015 PX4 Development Team. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name PX4 nor the names of its contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
############################################################################
set(SRCS_PLATFORM)
if (${OS} STREQUAL "nuttx")
list(APPEND SRCS_PLATFORM
nuttx/cdev_platform.cpp
)
else()
list(APPEND SRCS_PLATFORM
posix/cdev_platform.cpp
posix/vfile.cpp
)
endif()
px4_add_library(cdev
CDev.cpp
${SRCS_PLATFORM}
)
+143
View File
@@ -0,0 +1,143 @@
/****************************************************************************
*
* Copyright (c) 2012-2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file cdev_platform.cpp
*
* NuttX Character device functions
*/
#include "cdev_platform.hpp"
#include "../CDev.hpp"
#include "px4_posix.h"
#include "drivers/drv_device.h"
#include <sys/ioctl.h>
#ifdef CONFIG_DISABLE_POLL
# error This driver is not compatible with CONFIG_DISABLE_POLL
#endif
namespace cdev
{
/*
* The standard NuttX operation dispatch table can't call C++ member functions
* directly, so we have to bounce them through this dispatch table.
*/
static int cdev_open(file_t *filp);
static int cdev_close(file_t *filp);
static ssize_t cdev_read(file_t *filp, char *buffer, size_t buflen);
static ssize_t cdev_write(file_t *filp, const char *buffer, size_t buflen);
static off_t cdev_seek(file_t *filp, off_t offset, int whence);
static int cdev_ioctl(file_t *filp, int cmd, unsigned long arg);
static int cdev_poll(file_t *filp, px4_pollfd_struct_t *fds, bool setup);
/**
* Character device indirection table.
*
* Every cdev we register gets the same function table; we use the private data
* field in the inode to store the instance pointer.
*
* Note that we use the GNU extension syntax here because we don't get designated
* initialisers in gcc 4.6.
*/
const struct file_operations cdev::CDev::fops = {
open : cdev_open,
close : cdev_close,
read : cdev_read,
write : cdev_write,
seek : cdev_seek,
ioctl : cdev_ioctl,
poll : cdev_poll,
#ifndef CONFIG_DISABLE_PSEUDOFS_OPERATIONS
unlink : nullptr
#endif
};
static int
cdev_open(file_t *filp)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->open(filp);
}
static int
cdev_close(file_t *filp)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->close(filp);
}
static ssize_t
cdev_read(file_t *filp, char *buffer, size_t buflen)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->read(filp, buffer, buflen);
}
static ssize_t
cdev_write(file_t *filp, const char *buffer, size_t buflen)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->write(filp, buffer, buflen);
}
static off_t
cdev_seek(file_t *filp, off_t offset, int whence)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->seek(filp, offset, whence);
}
static int
cdev_ioctl(file_t *filp, int cmd, unsigned long arg)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->ioctl(filp, cmd, arg);
}
static int
cdev_poll(file_t *filp, px4_pollfd_struct_t *fds, bool setup)
{
cdev::CDev *cdev = (cdev::CDev *)(filp->f_inode->i_private);
return cdev->poll(filp, fds, setup);
}
} // namespace cdev
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include <cinttypes>
#include <nuttx/arch.h>
#include <px4_micro_hal.h>
#define ATOMIC_ENTER irqstate_t flags = px4_enter_critical_section()
#define ATOMIC_LEAVE px4_leave_critical_section(flags)
namespace cdev
{
using px4_file_operations_t = struct file_operations;
using file_t = struct file;
} // namespace cdev
+551
View File
@@ -0,0 +1,551 @@
/****************************************************************************
*
* Copyright (c) 2015 Mark Charlebois. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file vdev_posix.cpp
*
* POSIX-like API for virtual character device
*/
#include "cdev_platform.hpp"
#include <string>
#include <map>
#include "vfile.h"
#include "../CDev.hpp"
#include <px4_log.h>
#include <px4_posix.h>
#include <px4_time.h>
#include "DevMgr.hpp"
using namespace std;
using namespace DriverFramework;
const cdev::px4_file_operations_t cdev::CDev::fops = {};
pthread_mutex_t devmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER;
px4_sem_t lockstep_sem;
bool sim_lockstep = false;
volatile bool sim_delay = false;
#define PX4_MAX_FD 350
static map<string, void *> devmap;
static cdev::file_t filemap[PX4_MAX_FD] = {};
extern "C" {
int px4_errno;
static cdev::CDev *getDev(const char *path)
{
PX4_DEBUG("CDev::getDev");
pthread_mutex_lock(&devmutex);
auto item = devmap.find(path);
if (item != devmap.end()) {
pthread_mutex_unlock(&devmutex);
return (cdev::CDev *)item->second;
}
pthread_mutex_unlock(&devmutex);
return nullptr;
}
static cdev::CDev *get_vdev(int fd)
{
pthread_mutex_lock(&filemutex);
bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd].vdev);
cdev::CDev *dev;
if (valid) {
dev = (cdev::CDev *)(filemap[fd].vdev);
} else {
dev = nullptr;
}
pthread_mutex_unlock(&filemutex);
return dev;
}
int register_driver(const char *name, const cdev::px4_file_operations_t *fops, cdev::mode_t mode, void *data)
{
PX4_DEBUG("CDev::register_driver %s", name);
int ret = 0;
if (name == nullptr || data == nullptr) {
return -EINVAL;
}
pthread_mutex_lock(&devmutex);
// Make sure the device does not already exist
auto item = devmap.find(name);
if (item != devmap.end()) {
pthread_mutex_unlock(&devmutex);
return -EEXIST;
}
devmap[name] = (void *)data;
PX4_DEBUG("Registered DEV %s", name);
pthread_mutex_unlock(&devmutex);
return ret;
}
int unregister_driver(const char *name)
{
PX4_DEBUG("CDev::unregister_driver %s", name);
int ret = -EINVAL;
if (name == nullptr) {
return -EINVAL;
}
pthread_mutex_lock(&devmutex);
if (devmap.erase(name) > 0) {
PX4_DEBUG("Unregistered DEV %s", name);
ret = 0;
}
pthread_mutex_unlock(&devmutex);
return ret;
}
int px4_open(const char *path, int flags, ...)
{
PX4_DEBUG("px4_open");
cdev::CDev *dev = getDev(path);
int ret = 0;
int i;
mode_t mode;
if (!dev && (flags & PX4_F_WRONLY) != 0 &&
strncmp(path, "/obj/", 5) != 0 &&
strncmp(path, "/dev/", 5) != 0) {
va_list p;
va_start(p, flags);
mode = va_arg(p, int);
va_end(p);
// Create the file
PX4_DEBUG("Creating virtual file %s", path);
dev = cdev::VFile::createFile(path, mode);
}
if (dev) {
pthread_mutex_lock(&filemutex);
for (i = 0; i < PX4_MAX_FD; ++i) {
if (filemap[i].vdev == nullptr) {
filemap[i] = cdev::file_t(flags, dev);
break;
}
}
pthread_mutex_unlock(&filemutex);
if (i < PX4_MAX_FD) {
ret = dev->open(&filemap[i]);
} else {
const unsigned NAMELEN = 32;
char thread_name[NAMELEN] = {};
#ifndef __PX4_QURT
int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN);
if (nret || thread_name[0] == 0) {
PX4_WARN("failed getting thread name");
}
PX4_BACKTRACE();
#endif
PX4_WARN("%s: exceeded maximum number of file descriptors, accessing %s",
thread_name, path);
ret = -ENOENT;
}
} else {
ret = -EINVAL;
}
if (ret < 0) {
return -1;
}
PX4_DEBUG("px4_open fd = %d", i);
return i;
}
int px4_close(int fd)
{
int ret;
cdev::CDev *dev = get_vdev(fd);
if (dev) {
pthread_mutex_lock(&filemutex);
ret = dev->close(&filemap[fd]);
filemap[fd].vdev = nullptr;
pthread_mutex_unlock(&filemutex);
PX4_DEBUG("px4_close fd = %d", fd);
} else {
ret = -EINVAL;
}
if (ret < 0) {
px4_errno = -ret;
ret = PX4_ERROR;
}
return ret;
}
ssize_t px4_read(int fd, void *buffer, size_t buflen)
{
int ret;
cdev::CDev *dev = get_vdev(fd);
if (dev) {
PX4_DEBUG("px4_read fd = %d", fd);
ret = dev->read(&filemap[fd], (char *)buffer, buflen);
} else {
ret = -EINVAL;
}
if (ret < 0) {
px4_errno = -ret;
ret = PX4_ERROR;
}
return ret;
}
ssize_t px4_write(int fd, const void *buffer, size_t buflen)
{
int ret;
cdev::CDev *dev = get_vdev(fd);
if (dev) {
PX4_DEBUG("px4_write fd = %d", fd);
ret = dev->write(&filemap[fd], (const char *)buffer, buflen);
} else {
ret = -EINVAL;
}
if (ret < 0) {
px4_errno = -ret;
ret = PX4_ERROR;
}
return ret;
}
int px4_ioctl(int fd, int cmd, unsigned long arg)
{
PX4_DEBUG("px4_ioctl fd = %d", fd);
int ret = 0;
cdev::CDev *dev = get_vdev(fd);
if (dev) {
ret = dev->ioctl(&filemap[fd], cmd, arg);
} else {
ret = -EINVAL;
}
if (ret < 0) {
px4_errno = -ret;
}
return ret;
}
int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout)
{
if (nfds == 0) {
PX4_WARN("px4_poll with no fds");
return -1;
}
px4_sem_t sem;
int count = 0;
int ret = -1;
unsigned int i;
const unsigned NAMELEN = 32;
char thread_name[NAMELEN] = {};
#ifndef __PX4_QURT
int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN);
if (nret || thread_name[0] == 0) {
PX4_WARN("failed getting thread name");
}
#endif
while (sim_delay) {
usleep(100);
}
PX4_DEBUG("Called px4_poll timeout = %d", timeout);
px4_sem_init(&sem, 0, 0);
// sem use case is a signal
px4_sem_setprotocol(&sem, SEM_PRIO_NONE);
// Go through all fds and check them for a pollable state
bool fd_pollable = false;
for (i = 0; i < nfds; ++i) {
fds[i].sem = &sem;
fds[i].revents = 0;
fds[i].priv = nullptr;
cdev::CDev *dev = get_vdev(fds[i].fd);
// If fd is valid
if (dev) {
PX4_DEBUG("%s: px4_poll: CDev->poll(setup) %d", thread_name, fds[i].fd);
ret = dev->poll(&filemap[fds[i].fd], &fds[i], true);
if (ret < 0) {
PX4_WARN("%s: px4_poll() error: %s",
thread_name, strerror(errno));
break;
}
if (ret >= 0) {
fd_pollable = true;
}
}
}
// If any FD can be polled, lock the semaphore and
// check for new data
if (fd_pollable) {
if (timeout > 0) {
// Get the current time
struct timespec ts;
// FIXME: check if QURT should probably be using CLOCK_MONOTONIC
px4_clock_gettime(CLOCK_REALTIME, &ts);
// Calculate an absolute time in the future
const unsigned billion = (1000 * 1000 * 1000);
unsigned tdiff = timeout;
uint64_t nsecs = ts.tv_nsec + (tdiff * 1000 * 1000);
ts.tv_sec += nsecs / billion;
nsecs -= (nsecs / billion) * billion;
ts.tv_nsec = nsecs;
// Execute a blocking wait for that time in the future
errno = 0;
ret = px4_sem_timedwait(&sem, &ts);
#ifndef __PX4_DARWIN
ret = errno;
#endif
// Ensure ret is negative on failure
if (ret > 0) {
ret = -ret;
}
if (ret && ret != -ETIMEDOUT) {
PX4_WARN("%s: px4_poll() sem error", thread_name);
}
} else if (timeout < 0) {
px4_sem_wait(&sem);
}
// We have waited now (or not, depending on timeout),
// go through all fds and count how many have data
for (i = 0; i < nfds; ++i) {
cdev::CDev *dev = get_vdev(fds[i].fd);
// If fd is valid
if (dev) {
PX4_DEBUG("%s: px4_poll: CDev->poll(teardown) %d", thread_name, fds[i].fd);
ret = dev->poll(&filemap[fds[i].fd], &fds[i], false);
if (ret < 0) {
PX4_WARN("%s: px4_poll() 2nd poll fail", thread_name);
break;
}
if (fds[i].revents) {
count += 1;
}
}
}
}
px4_sem_destroy(&sem);
// Return the positive count if present,
// return the negative error number if failed
return (count) ? count : ret;
}
int px4_fsync(int fd)
{
return 0;
}
int px4_access(const char *pathname, int mode)
{
if (mode != F_OK) {
errno = EINVAL;
return -1;
}
cdev::CDev *dev = getDev(pathname);
return (dev != nullptr) ? 0 : -1;
}
void px4_show_devices()
{
int i = 0;
PX4_INFO("PX4 Devices:");
pthread_mutex_lock(&devmutex);
for (const auto &dev : devmap) {
if (strncmp(dev.first.c_str(), "/dev/", 5) == 0) {
PX4_INFO(" %s", dev.first.c_str());
}
}
pthread_mutex_unlock(&devmutex);
PX4_INFO("DF Devices:");
const char *dev_path;
unsigned int index = 0;
i = 0;
do {
// Each look increments index and returns -1 if end reached
i = DevMgr::getNextDeviceName(index, &dev_path);
if (i == 0) {
PX4_INFO(" %s", dev_path);
}
} while (i == 0);
}
void px4_show_topics()
{
PX4_INFO("Devices:");
pthread_mutex_lock(&devmutex);
for (const auto &dev : devmap) {
if (strncmp(dev.first.c_str(), "/obj/", 5) == 0) {
PX4_INFO(" %s", dev.first.c_str());
}
}
pthread_mutex_unlock(&devmutex);
}
void px4_show_files()
{
PX4_INFO("Files:");
pthread_mutex_lock(&devmutex);
for (const auto &dev : devmap) {
if (strncmp(dev.first.c_str(), "/obj/", 5) != 0 &&
strncmp(dev.first.c_str(), "/dev/", 5) != 0) {
PX4_INFO(" %s", dev.first.c_str());
}
}
pthread_mutex_unlock(&devmutex);
}
void px4_enable_sim_lockstep()
{
px4_sem_init(&lockstep_sem, 0, 0);
// lockstep_sem use case is a signal
px4_sem_setprotocol(&lockstep_sem, SEM_PRIO_NONE);
sim_lockstep = true;
sim_delay = false;
}
void px4_sim_start_delay()
{
sim_delay = true;
}
void px4_sim_stop_delay()
{
sim_delay = false;
}
bool px4_sim_delay_enabled()
{
return sim_delay;
}
} // extern "C"
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <cinttypes>
#define ATOMIC_ENTER lock()
#define ATOMIC_LEAVE unlock()
namespace cdev
{
struct file_operations {
void *op;
};
using px4_file_operations_t = struct file_operations;
using mode_t = uint32_t;
struct file_t {
int flags;
void *priv;
void *vdev;
file_t() : flags(0), priv(nullptr), vdev(nullptr) {}
file_t(int f, void *c) : flags(f), priv(nullptr), vdev(c) {}
};
} // namespace cdev
extern "C" __EXPORT int register_driver(const char *name, const cdev::px4_file_operations_t *fops,
cdev::mode_t mode, void *data);
extern "C" __EXPORT int unregister_driver(const char *path);
+67
View File
@@ -0,0 +1,67 @@
/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file vdev_file.cpp
* Virtual file
*
* @author Mark Charlebois <charlebm@gmail.com>
*/
#include "vfile.h"
namespace cdev
{
VFile::VFile(const char *fname, mode_t mode) :
CDev(fname)
{
}
VFile *VFile::createFile(const char *fname, mode_t mode)
{
VFile *me = new VFile(fname, mode);
px4_file_operations_t *file_ops = nullptr;
register_driver(fname, file_ops, 0666, (void *)me);
return me;
}
ssize_t VFile::write(file_t *handlep, const char *buffer, size_t buflen)
{
// ignore what was written, but let pollers know something was written
poll_notify(POLLIN);
return buflen;
}
} // namespace cdev
+62
View File
@@ -0,0 +1,62 @@
/****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file vfile.cpp
* Virtual file
*
* @author Mark Charlebois <charlebm@gmail.com>
*/
#pragma once
#include "../CDev.hpp"
namespace cdev
{
class VFile : public CDev
{
public:
static VFile *createFile(const char *fname, mode_t mode);
~VFile() {}
ssize_t write(file_t *handlep, const char *buffer, size_t buflen) override;
private:
VFile(const char *fname, mode_t mode);
VFile(const VFile &);
};
} // namespace cdev