From daaa2e92c8c52fb58ff8a19738cc764f6d0f44cc Mon Sep 17 00:00:00 2001 From: Jon Szymaniak Date: Sat, 1 Feb 2014 17:42:05 -0500 Subject: [PATCH] libbladeRF: Re-implemented sync interface, updated API docs, renamed timeout function The sync interface has been re-implemented atop the existing asynchronous interface. This is currently opt-in and only enable when pthreads support is enabled and available. Some clarifications have been made in the API documentation, specifically in the explanations of the various stream parameters. The bladerf_set_transfer_timeout and bladerf_get_transfer_timeout have been named more appropriately, as these control stream transfer timeouts, as opposed to all transfers. --- host/common/include/conversions.h | 25 + .../common/include/osx/clock_gettime.h | 0 .../common/include/windows/clock_gettime.h | 0 .../common/include/windows/ptw32_timespec.h | 0 host/common/src/conversions.c | 37 ++ .../common/src/osx/clock_gettime.c | 0 .../common/src/windows/clock_gettime.c | 0 host/libraries/libbladeRF/CMakeLists.txt | 68 ++- .../libbladeRF/doc/doxygen/Doxyfile.in | 2 +- .../libraries/libbladeRF/include/libbladeRF.h | 384 ++++++++---- .../libraries/libbladeRF/src/backend/libusb.c | 92 +-- host/libraries/libbladeRF/src/backend/linux.c | 69 --- host/libraries/libbladeRF/src/bladerf.c | 82 ++- host/libraries/libbladeRF/src/bladerf_priv.c | 22 + host/libraries/libbladeRF/src/bladerf_priv.h | 23 +- host/libraries/libbladeRF/src/lms.h | 4 - host/libraries/libbladeRF/src/sync.c | 422 +++++++++++++ host/libraries/libbladeRF/src/sync.h | 108 ++++ host/libraries/libbladeRF/src/sync_worker.c | 571 ++++++++++++++++++ host/libraries/libbladeRF/src/sync_worker.h | 124 ++++ .../libraries/libbladeRF/tests/CMakeLists.txt | 1 + .../libbladeRF/tests/test_async/main.c | 6 +- .../libbladeRF/tests/test_sync/CMakeLists.txt | 21 + .../libbladeRF/tests/test_sync/src/main.c | 364 +++++++++++ .../libbladeRF/tests/test_sync/src/test.c | 293 +++++++++ .../libbladeRF/tests/test_sync/src/test.h | 63 ++ host/utilities/bladeRF-cli/CMakeLists.txt | 7 +- host/utilities/bladeRF-cli/src/cmd/rx.c | 4 +- host/utilities/bladeRF-cli/src/cmd/tx.c | 4 +- 29 files changed, 2495 insertions(+), 301 deletions(-) rename host/{utilities => }/common/include/osx/clock_gettime.h (100%) rename host/{utilities => }/common/include/windows/clock_gettime.h (100%) rename host/{utilities => }/common/include/windows/ptw32_timespec.h (100%) rename host/{utilities => }/common/src/osx/clock_gettime.c (100%) rename host/{utilities => }/common/src/windows/clock_gettime.c (100%) create mode 100644 host/libraries/libbladeRF/src/sync.c create mode 100644 host/libraries/libbladeRF/src/sync.h create mode 100644 host/libraries/libbladeRF/src/sync_worker.c create mode 100644 host/libraries/libbladeRF/src/sync_worker.h create mode 100644 host/libraries/libbladeRF/tests/test_sync/CMakeLists.txt create mode 100644 host/libraries/libbladeRF/tests/test_sync/src/main.c create mode 100644 host/libraries/libbladeRF/tests/test_sync/src/test.c create mode 100644 host/libraries/libbladeRF/tests/test_sync/src/test.h diff --git a/host/common/include/conversions.h b/host/common/include/conversions.h index 0ad64ab2..c0f09703 100644 --- a/host/common/include/conversions.h +++ b/host/common/include/conversions.h @@ -136,9 +136,34 @@ int str2version(const char *str, struct bladerf_version *version); /** * Convert a bladerf_dev_speed to a string suitable for printing + * + * @note The caller should not attempt to modify or free() the returned string. + * + * @param speed Device speed + * @return Const string describing the provided speed */ const char * devspeed2str(bladerf_dev_speed speed); +/** + * Convert a string to libbladeRF log verbosity level + * + * @param[in] str Input string + * @param[out] ok Value is updated to true if the input string was valid + * + * @return Log level if ok is true, undefined otherwise + */ +bladerf_log_level str2loglevel(const char *str, bool *ok); + +/** + * Convert a module enumeration to a string + * + * @note The caller should not attempt to modify or free() the returned string. + * + * @param module Module to convert to string + * @return String representation of module + */ +const char * module2str(bladerf_module m); + /** * Convert a string to an argc/argv-style argument list. Arguments are split * on whitespace. Double-quotes may be used to include whitespace in an diff --git a/host/utilities/common/include/osx/clock_gettime.h b/host/common/include/osx/clock_gettime.h similarity index 100% rename from host/utilities/common/include/osx/clock_gettime.h rename to host/common/include/osx/clock_gettime.h diff --git a/host/utilities/common/include/windows/clock_gettime.h b/host/common/include/windows/clock_gettime.h similarity index 100% rename from host/utilities/common/include/windows/clock_gettime.h rename to host/common/include/windows/clock_gettime.h diff --git a/host/utilities/common/include/windows/ptw32_timespec.h b/host/common/include/windows/ptw32_timespec.h similarity index 100% rename from host/utilities/common/include/windows/ptw32_timespec.h rename to host/common/include/windows/ptw32_timespec.h diff --git a/host/common/src/conversions.c b/host/common/src/conversions.c index ad323bc0..ce58f173 100644 --- a/host/common/src/conversions.c +++ b/host/common/src/conversions.c @@ -293,6 +293,43 @@ const char * devspeed2str(bladerf_dev_speed speed) } } +bladerf_log_level str2loglevel(const char *str, bool *ok) +{ + bladerf_log_level level = BLADERF_LOG_LEVEL_ERROR; + bool valid = true; + + if (!strcasecmp(str, "critical")) { + level = BLADERF_LOG_LEVEL_CRITICAL; + } else if (!strcasecmp(str, "error")) { + level = BLADERF_LOG_LEVEL_ERROR; + } else if (!strcasecmp(str, "warning")) { + level = BLADERF_LOG_LEVEL_WARNING; + } else if (!strcasecmp(str, "info")) { + level = BLADERF_LOG_LEVEL_INFO; + } else if (!strcasecmp(str, "debug")) { + level = BLADERF_LOG_LEVEL_DEBUG; + } else if (!strcasecmp(str, "verbose")) { + level = BLADERF_LOG_LEVEL_VERBOSE; + } else { + valid = false; + } + + *ok = valid; + return level; +} + +const char * module2str(bladerf_module m) +{ + switch (m) { + case BLADERF_MODULE_RX: + return "RX"; + case BLADERF_MODULE_TX: + return "TX"; + default: + return "Unknown"; + } +} + int str2args(const char *line, char ***argv_ret) { int line_i, arg_i; /* Index into line and current argument */ diff --git a/host/utilities/common/src/osx/clock_gettime.c b/host/common/src/osx/clock_gettime.c similarity index 100% rename from host/utilities/common/src/osx/clock_gettime.c rename to host/common/src/osx/clock_gettime.c diff --git a/host/utilities/common/src/windows/clock_gettime.c b/host/common/src/windows/clock_gettime.c similarity index 100% rename from host/utilities/common/src/windows/clock_gettime.c rename to host/common/src/windows/clock_gettime.c diff --git a/host/libraries/libbladeRF/CMakeLists.txt b/host/libraries/libbladeRF/CMakeLists.txt index ecbde37b..1b30d3e4 100644 --- a/host/libraries/libbladeRF/CMakeLists.txt +++ b/host/libraries/libbladeRF/CMakeLists.txt @@ -1,6 +1,22 @@ cmake_minimum_required(VERSION 2.8.5) project(libbladeRF C) +if(MSVC) + find_package(LibPThreadsWin32 REQUIRED) + if(LIBPTHREADSWIN32_FOUND) + set(HAVE_THREADS true) + else() + set(HAVE_THREADS false) + endif() +else(MSVC) + find_package(Threads REQUIRED) + if(Threads_FOUND) + set(HAVE_THREADS true) + else() + set(HAVE_THREADS false) + endif() +endif(MSVC) + ################################################################################ # Version information ################################################################################ @@ -60,6 +76,17 @@ option(LIBUSB_DETACH_KERNEL_DRIVER ON ) +option(ENABLE_LIBBLADERF_SYNC + "Enable the libbladeRF synchronous data interface. Requires pthreads." + ${HAVE_THREADS} +) + +option(ENABLE_LIBBLADERF_SYNC_LOG_VERBOSE + "Enable log_verbose() calls in the sync interface's data path. Note that this may harm performance." + OFF +) + + option(ENABLE_BACKEND_LINUX_DRIVER "Enable Linux driver backend support." OFF @@ -123,6 +150,23 @@ if(ENABLE_BACKEND_LIBUSB) endif(NOT LIBUSB_FOUND) endif(ENABLE_BACKEND_LIBUSB) +if(ENABLE_LIBBLADERF_SYNC) + if(NOT HAVE_THREADS) + message(FATAL_ERROR "Pthreads is required for the libbladeRF sync interface") + endif() + + if(MSVC) + set(LIBBLADERF_INCLUDES ${LIBBLADERF_INCLUDES} + ${LIBPTHREADSWIN32_INCLUDE_DIRS}) + endif() + + add_definitions(-DENABLE_LIBBLADERF_SYNC) + + if(ENABLE_LIBBLADERF_SYNC_LOG_VERBOSE AND ENABLE_LIBBLADERF_LOGGING) + add_definitions(-DENABLE_LIBBLADERF_SYNC_LOG_VERBOSE) + endif() +endif(ENABLE_LIBBLADERF_SYNC) + include_directories(${LIBBLADERF_INCLUDES}) ################################################################################ @@ -153,21 +197,39 @@ if(ENABLE_BACKEND_DUMMY) set(LIBBLADERF_SOURCE ${LIBBLADERF_SOURCE} src/backend/dummy.c) endif() - if(ENABLE_BACKEND_LINUX_DRIVER) set(LIBBLADERF_SOURCE ${LIBBLADERF_SOURCE} src/backend/linux.c) endif() +if(ENABLE_LIBBLADERF_SYNC) + set(LIBBLADERF_SOURCE ${LIBBLADERF_SOURCE} + src/sync.c + src/sync_worker.c + ) + + if(MSVC) + set(LIBBLADERF_SOURCE ${LIBBLADERF_SOURCE} + ${BLADERF_HOST_COMMON_SOURCE_DIR}/windows/clock_gettime.c + ) + endif() +endif() + add_library(libbladerf_shared SHARED ${LIBBLADERF_SOURCE}) ################################################################################ # Build configuration ################################################################################ -if(ENABLE_BACKEND_LIBUSB) - target_link_libraries(libbladerf_shared ${LIBUSB_LIBRARIES}) +if(MSVC AND ENABLE_LIBBLADERF_SYNC) + set(LIBBLADERF_LIBS ${LIBBLADERF_LIBS} ${LIBPTHREADSWIN32_LIBRARIES}) endif() +if(ENABLE_BACKEND_LIBUSB) + set(LIBBLADERF_LIBS ${LIBBLADERF_LIBS} ${LIBUSB_LIBRARIES}) +endif() + +target_link_libraries(libbladerf_shared ${LIBBLADERF_LIBS}) + # Adjust our output name set_target_properties(libbladerf_shared PROPERTIES OUTPUT_NAME bladeRF) diff --git a/host/libraries/libbladeRF/doc/doxygen/Doxyfile.in b/host/libraries/libbladeRF/doc/doxygen/Doxyfile.in index 8f73353b..81c96993 100644 --- a/host/libraries/libbladeRF/doc/doxygen/Doxyfile.in +++ b/host/libraries/libbladeRF/doc/doxygen/Doxyfile.in @@ -1223,7 +1223,7 @@ FORMULA_TRANSPARENT = YES # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. -USE_MATHJAX = NO +USE_MATHJAX = YES # When MathJax is enabled you can set the default output format to be used for # the MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and diff --git a/host/libraries/libbladeRF/include/libbladeRF.h b/host/libraries/libbladeRF/include/libbladeRF.h index f12c02c6..96bef8f0 100644 --- a/host/libraries/libbladeRF/include/libbladeRF.h +++ b/host/libraries/libbladeRF/include/libbladeRF.h @@ -221,6 +221,7 @@ void CALL_CONV bladerf_close(struct bladerf *device); /** * @defgroup FN_DEVINFO Device identifier information functions + * * @{ */ @@ -446,7 +447,10 @@ typedef enum } bladerf_correction; /** - * Enable or disable the specified RX/TX module + * Enable or disable the specified RX/TX module. + * + * When a synchronous stream is associated with the specified module, this + * stream will be shut down. * * @param dev Device handle * @param m Device module @@ -807,10 +811,8 @@ int CALL_CONV bladerf_get_frequency(struct bladerf *dev, /** @} (End of FN_CTRL) */ - /** - * @defgroup FN_DATA Data transmission and reception - * + * @defgroup FMT_META Formats and Metadata * @{ */ @@ -840,38 +842,110 @@ typedef enum { */ #define BLADERF_FORMAT_SC16_Q12 BLADERF_FORMAT_SC16_Q11 + + +/* + * Metadata status bits + */ + +/** + * The host-side data stream encountered an overrun failure + */ +#define BLADERF_META_STATUS_SW_OVERRUN (1 << 0) + +/** + * The host-side data stream encountered an underrun failure + */ +#define BLADERF_META_STATUS_SW_UNDERRUN (1 << 1) + +/** + * An overrun failure occurred in the FPGA + */ +#define BLADERF_META_STATUS_HW_OVERRUN (1 << 8) + +/** + * An underrrun failure occurred in the FPGA + */ +#define BLADERF_META_STATUS_HW_UNDERRUN (1 << 9) + + + +/* + * Metadata flags + */ + +/** + * Mark the associated buffer as the start of a burst transfer + */ +#define BLADERF_META_FLAG_BURST_START (1 << 0) + +/** + * Mark the associated buffer as the end of a burst transfer + */ +#define BLADERF_META_FLAG_BURST_END (1 << 1) + + +/** + * Sample metadata + * + * @bug Metadata support is not yet implemented. API users should not attempt + * to read or write to metadata structures. + */ +struct bladerf_metadata { + + /** + * Free-running FPGA counter that monotonically increases at the + * samplerate of the associated module. */ + uint64_t timestamp; + + /** + * Input bit field to control the behavior of the call that the metadata + * structure is passed to. API calls read this field from the provided + * data structure, and do not modify it. + * + * See the BLADERF_META_FLAG_* values for available options. + */ + uint32_t flags; + + /** + * Output bit field to denoting the status of transmissions/receptions. API + * calls will write this field. + * + * See the BLADERF_META_STATUS_* values for possible status items. + */ + uint32_t status; +}; + + +/** @} (End of FMT_META) */ + + +/** + * @defgroup FN_DATA_ASYNC Asynchronous data transmission and reception + * + * @{ + */ + /** This opaque structure is used to keep track of stream information */ struct bladerf_stream; -/** - * Sample metadata - */ -struct bladerf_metadata { - uint32_t version; /**< Metadata format version */ - uint64_t timestamp; /**< Timestamp (TODO format TBD) */ -}; - /** * For both RX and TX, the stream callback receives: - * dev: Device structure - * stream: The associated stream - * metadata: TBD - * user_data: User data provided when initializing stream - * - *
+ * - dev: Device structure + * - stream: The associated stream + * - metadata: (TODO) + * - user_data: User data provided when initializing stream * * For TX callbacks: - * samples: Pointer fo buffer of samples that was sent - * num_samples: Number of sent in last transfer and to send in next transfer - * - * Return value: The user specifies the address of the next buffer to send + * - samples: Pointer to buffer of samples that was sent + * - num_samples: Number of sent in last transfer and to send in next transfer + * - Return value: The user specifies the address of the next buffer to send * * For RX callbacks: - * samples: Buffer filled with received data - * num_samples: Number of samples received and size of next buffers - * - * Return value: The user specifies the next buffer to fill with RX data, - * which should be num_samples in size. + * - samples: Buffer filled with received data + * - num_samples: Number of samples received and size of next buffers + * - Return value: The user specifies the next buffer to fill with RX data, + * which should be `num_samples` in size. * */ typedef void *(*bladerf_stream_cb)(struct bladerf *dev, @@ -882,7 +956,40 @@ typedef void *(*bladerf_stream_cb)(struct bladerf *dev, void *user_data); /** - * Initialize a stream for use with asynchronous routines + * Initialize a stream for use with asynchronous routines. + * + * This function will internally allocate data buffers, which will be provided + * to the API user in callback functions. + * + * The `buffers` output parameter populates a pointer to the list of allocated + * buffers. This allows the API user to implement a buffer management scheme to + * best suit his or her specific use case. + * + * Generally, one will want to set the `buffers` parameter to a value larger + * than the `num_transfers` parameter, and keep track of which buffers are + * currently "in-flight", versus those available for use. + * + * For example, for a transmit stream, modulated data can be actively written + * into free buffers while transfers of other buffers are occurring. Once a + * buffer has been filled with data, it can be marked 'in-flight' and be + * returned in a successive callback to transmit. + * + * The choice of values for the `num_transfers` and `buffer_size` should be + * made based upon the desired samplerate, and the stream timeout value + * specified via bladerf_set_stream_timeout(), which defaults to 1 second. + * + * For a given sample rate, the below relationship must be upheld to transmit or + * receive data without timeouts or dropped data. + * + * @f[ + * Sample\ Rate < \frac{\#\ Transfers}{Timeout} \times Buffer\ Size + * @f] + * + * To account for general system overhead, it is recommended to multiply the + * righthand side by 1.1 to 1.25. + * + * While increasing the number of buffers available provides additional + * elasticity, be aware that it also increases latency. * * @param[out] stream Upon success, this will be updated to contain * a stream handle (i.e., address) @@ -894,17 +1001,18 @@ typedef void *(*bladerf_stream_cb)(struct bladerf *dev, * @param[out] buffers This will be updated to point to a dynamically * allocated array of buffer pointers. * - * @param[in] num_buffers Number of buffers to allocate and return + * @param[in] num_buffers Number of buffers to allocate and return. This + * value must >= the `num_transfers` parameter. * * @param[in] format Sample data format * - * @param[in] num_samples Number of samples in each buffer of samples. + * @param[in] buffer_size Size of allocated buffers, in samples. * Note that the physical size of the buffer * is a function of this and the format parameter. * * @param[in] num_transfers Maximum number of transfers that may be - * in-flight simultaneous. This must be <= the - * number of buffers. + * in-flight simultaneously. This must be <= the + * `num_buffers` parameter. * * @param[in] user_data Caller-provided data that will be provided * in stream callbacks @@ -923,7 +1031,7 @@ int CALL_CONV bladerf_init_stream(struct bladerf_stream **stream, void ***buffers, size_t num_buffers, bladerf_format format, - size_t num_samples, + size_t buffer_size, size_t num_transfers, void *user_data); @@ -967,66 +1075,14 @@ int CALL_CONV bladerf_stream(struct bladerf_stream *stream, * * @post Stream is deallocated and may no longer be used. * - * @param stream Stream to deinitialize. This function does nothin + * @param stream Stream to deinitialize. This function does nothing * if stream is NULL. */ API_EXPORT void CALL_CONV bladerf_deinit_stream(struct bladerf_stream *stream); /** - * Transmit IQ samples - * - * @param[in] dev Device handle - * @param[in] format Format of the provided samples - * @param[in] samples Array of samples - * @param[in] num_samples Number of samples to write - * @param[in] metadata Sample metadata. This parameter is currently - * unused. - * - * @note When using the libusb backend, this function will likely be too slow - * for mid to high sample rates. For anything other than slow sample - * rates, the bladerf_stream() function is better choice. - * - * @warning This function is scheduled to be removed and replaced by a - * synchronous companion library that utilizes the async interface - * - * @return number of samples sent on success, - * value from \ref RETCODES list on failure - */ -API_EXPORT -int CALL_CONV bladerf_tx(struct bladerf *dev, bladerf_format format, - void *samples, int num_samples, - struct bladerf_metadata *metadata); - -/** - * Receive IQ samples - * - * @param[in] dev Device handle - * @param[in] format The data format that the received data should be in. - * The caller is responsible for ensuring the provided - * sample buffer is sufficiently large. - * - * @param[out] samples Buffer to store samples in - * @param[in] num_samples Number of samples to read - * @param[out] metadata Sample metadata. This parameter is currently - * unused. - * - * @note When using the libusb backend, this function will likely be too slow - * for mid to high sample rates. For anything other than slow sample - * rates, the bladerf_stream() function is better choice. - * - * @warning This function is scheduled to be removed and replaced by a - * synchronous companion library that utilizes the async interface - * - * @return number of samples read or value from \ref RETCODES list on failure - */ -API_EXPORT -int CALL_CONV bladerf_rx(struct bladerf *dev, bladerf_format format, - void *samples, int num_samples, - struct bladerf_metadata *metadata); - -/** - * Set transfer timeout in milliseconds + * Set stream transfer timeout in milliseconds * * @param dev Device handle * @param module Module to adjust @@ -1035,9 +1091,9 @@ int CALL_CONV bladerf_rx(struct bladerf *dev, bladerf_format format, * @return 0 on success, value from \ref RETCODES list on failure */ API_EXPORT -int CALL_CONV bladerf_set_transfer_timeout(struct bladerf *dev, - bladerf_module module, - unsigned int timeout); +int CALL_CONV bladerf_set_stream_timeout(struct bladerf *dev, + bladerf_module module, + unsigned int timeout); /** @@ -1051,13 +1107,135 @@ int CALL_CONV bladerf_set_transfer_timeout(struct bladerf *dev, * @return 0 on success, value from \ref RETCODES list on failure */ API_EXPORT -int CALL_CONV bladerf_get_transfer_timeout(struct bladerf *dev, - bladerf_module module, - unsigned int *timeout); +int CALL_CONV bladerf_get_stream_timeout(struct bladerf *dev, + bladerf_module module, + unsigned int *timeout); -/** @} (End of FN_DATA) */ +/** @} (End of FN_DATA_ASYNC) */ + +/** + * @defgroup FN_DATA_SYNC Synchronous data transmission and reception + * + * The synchronous interface is built atop the asynchronous interface. This + * interface requires libbladeRF to be built with pthreads support. + * + * @{ + */ + +/** + * (Re)Configure a device for synchronous transmission or reception + * + * This function sets up the device for the specified format and initializes + * the underlying asynchronous stream parameters + * + * This function does not call bladerf_enable_module(). The API user is + * responsible for enabling/disable modules when desired. + * + * Note that (re)configuring BLADERF_MODULE_TX does not affect the + * BLADERF_MODULE_RX modules, and vice versa. This call configures each module + * independently. + * + * Memory allocated by this function will be deallocated when bladerf_close() + * is called. + * + * See the bladerf_init_stream() documentation for information on determining + * appropriate values for `buffers_size`, `num_transfers`, and `stream_timeout`. + * The `num_buffers` parameter should generally be increased as the amount of + * work done between bladerf_sync_rx() or bladerf_sync_tx() calls increases. + * + * + * @param dev Device to configure + * + * @param module Module to use with synchronous interface + * + * @param format Format to use in synchronous data transfers + * + * @param num_buffers The number of buffers to use in the underlying + * data stream. This must be greater than the + * `num_xfers` parameter. + * + * @param buffer_size The size of the underlying stream buffers, in + * samples. This value must be a multiple of 1024. + * + * @param num_transfers The number of active USB transfers that may be + * in-flight at any given time. If unsure of what + * to use here, try values of 4, 8, or 16. + * + * @param stream_timeout Timeout (milliseconds) for transfers in the + * underlying data stream. + * + * @return 0 on success, + * BLADERF_ERR_UNSUPPORTED if libbladeRF is not built with support + * for this functionality, + * or a value from \ref RETCODES list on failures. + */ +API_EXPORT +int CALL_CONV bladerf_sync_config(struct bladerf *dev, + bladerf_module module, + bladerf_format format, + unsigned int num_buffers, + unsigned int buffer_size, + unsigned int num_transfers, + unsigned int stream_timeout); + +/** + * Transmit IQ samples + * + * @param[in] dev Device handle + * @param[in] samples Array of samples + * @param[in] num_samples Number of samples to write + * @param[in] metadata Sample metadata. (Currently not used.) + * @param[in] timeout_ms Timeout (milliseconds) for this call to complete. + * Zero implies "infinite." + * + * @pre A bladerf_sync_config() call has been to configure the device for + * synchronous data transfer. + * + * @return 0 on success, + * BLADERF_ERR_UNSUPPORTED if libbladeRF is not built with support + * for this functionality, + * or a value from \ref RETCODES list on failures. + */ +API_EXPORT +int CALL_CONV bladerf_sync_tx(struct bladerf *dev, + void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, + unsigned int timeout_ms); + +/** + * Receive IQ samples + * + * @param[in] dev Device handle + * + * @param[out] samples Buffer to store samples in. The caller is + * responsible for ensuring this buffer is sufficiently + * large for the number of samples requested, + * considering the size of the sample format being + * used. + * + * @param[in] num_samples Number of samples to read + * + * @param[out] metadata Sample metadata. (Currently not used.) + * + * @param[in] timeout_ms Timeout (milliseconds) for this call to complete. + * Zero implies "infinite." + * + * @pre A bladerf_sync_config() call has been to configure the device for + * synchronous data transfer. + * + * @return 0 on success, + * BLADERF_ERR_UNSUPPORTED if libbladeRF is not built with support + * for this functionality, + * or a value from \ref RETCODES list on failures. + */ +API_EXPORT +int CALL_CONV bladerf_sync_rx(struct bladerf *dev, + void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, + unsigned int timeout_ms); +/** @} (End of FN_DATA_SYNC) */ /** * @defgroup FN_INFO Device info @@ -1118,7 +1296,7 @@ int CALL_CONV bladerf_get_vctcxo_trim(struct bladerf *dev, uint16_t *trim); * Query a device's FPGA size * * @param[in] dev Device handle - * @param[out] size Will be updated with the onboard FPGA's size. If an + * @param[out] size Will be updated with the on-board FPGA's size. If an * error occurs, no data will be written to this pointer. * * @return 0 on success, value from \ref RETCODES list on failure @@ -1304,12 +1482,12 @@ void CALL_CONV bladerf_log_set_verbosity(bladerf_log_level level); /** Type of data stored in a flash image */ typedef enum { - BLADERF_IMAGE_TYPE_INVALID = -1, /** Used to denote invalid value */ - BLADERF_IMAGE_TYPE_RAW, /** Misc. raw data */ - BLADERF_IMAGE_TYPE_FIRMWARE, /** Firmware data */ - BLADERF_IMAGE_TYPE_FPGA_40KLE, /** FPGA bitstream for 40 KLE device */ - BLADERF_IMAGE_TYPE_FPGA_115KLE, /** FPGA bitstream for 115 KLE device */ - BLADERF_IMAGE_TYPE_CALIBRATION, /** Calibration data */ + BLADERF_IMAGE_TYPE_INVALID = -1, /**< Used to denote invalid value */ + BLADERF_IMAGE_TYPE_RAW, /**< Misc. raw data */ + BLADERF_IMAGE_TYPE_FIRMWARE, /**< Firmware data */ + BLADERF_IMAGE_TYPE_FPGA_40KLE, /**< FPGA bitstream for 40 KLE device */ + BLADERF_IMAGE_TYPE_FPGA_115KLE, /**< FPGA bitstream for 115 KLE device */ + BLADERF_IMAGE_TYPE_CALIBRATION, /**< Calibration data */ } bladerf_image_type; /** @@ -1332,7 +1510,7 @@ typedef enum { * * The on disk format generated by the bladerf_image_write function is a * serialized version of this structure and its contents. When written to disk, - * values are CALL_CONVerted to big-endian byte order, for ease of reading in a hex + * values are converted to big-endian byte order, for ease of reading in a hex * editor. */ struct bladerf_image { @@ -1828,7 +2006,7 @@ int CALL_CONV bladerf_write_flash(struct bladerf *dev, uint32_t addr, * Program an unaligned region of flash memory (read/erase/write/verify). * * @note This function performs a full read/erase/write/verify cycle and the - * aligned variants should be prefered whenever possible. + * aligned variants should be preferred whenever possible. * * @param dev Device handle * @param addr Unaligned byte address of destination diff --git a/host/libraries/libbladeRF/src/backend/libusb.c b/host/libraries/libbladeRF/src/backend/libusb.c index a19c4634..5c4203da 100644 --- a/host/libraries/libbladeRF/src/backend/libusb.c +++ b/host/libraries/libbladeRF/src/backend/libusb.c @@ -2008,89 +2008,6 @@ static int lusb_get_correction(struct bladerf *dev, bladerf_module module, return status; } - -static int lusb_tx(struct bladerf *dev, bladerf_format format, void *samples, - int n, struct bladerf_metadata *metadata) -{ - size_t bytes_total, bytes_remaining, ret; - struct bladerf_lusb *lusb = (struct bladerf_lusb *)dev->backend; - uint8_t *samples8 = (uint8_t *)samples; - int transferred, status; - - /* This is the only format we currently support */ - assert(format == BLADERF_FORMAT_SC16_Q11); - - bytes_total = bytes_remaining = c16_samples_to_bytes(n); - - assert(bytes_remaining <= INT_MAX); - - while( bytes_remaining > 0 ) { - transferred = 0; - status = libusb_bulk_transfer( - lusb->handle, - EP_OUT(0x1), - samples8, - (int)bytes_remaining, - &transferred, - dev->transfer_timeout[BLADERF_MODULE_TX] - ); - if( status < 0 ) { - log_error( "Error transmitting samples (%d): %s\n", status, libusb_error_name(status) ); - return BLADERF_ERR_IO; - } else { - assert(transferred > 0); - assert(bytes_remaining >= (size_t)transferred); - bytes_remaining -= transferred; - samples8 += transferred; - } - } - - ret = bytes_to_c16_samples(bytes_total - bytes_remaining); - assert(ret <= INT_MAX); - return (int)ret; -} - -static int lusb_rx(struct bladerf *dev, bladerf_format format, void *samples, - int n, struct bladerf_metadata *metadata) -{ - size_t bytes_total, bytes_remaining, ret; - struct bladerf_lusb *lusb = (struct bladerf_lusb *)dev->backend; - uint8_t *samples8 = (uint8_t *)samples; - int transferred, status; - - /* The only format currently is assumed here */ - assert(format == BLADERF_FORMAT_SC16_Q11); - bytes_total = bytes_remaining = c16_samples_to_bytes(n); - - assert(bytes_remaining <= INT_MAX); - - while( bytes_remaining ) { - transferred = 0; - status = libusb_bulk_transfer( - lusb->handle, - EP_IN(0x1), - samples8, - (int)bytes_remaining, - &transferred, - dev->transfer_timeout[BLADERF_MODULE_RX] - ); - if( status < 0 ) { - log_error( "Error reading samples (%d): %s\n", status, libusb_error_name(status) ); - return BLADERF_ERR_IO; - } else { - assert(transferred > 0); - assert(bytes_remaining >= (size_t)transferred); - bytes_remaining -= transferred; - samples8 += transferred; - } - } - - assert(bytes_total >= bytes_remaining); - ret = bytes_to_c16_samples(bytes_total - bytes_remaining); - assert(ret <= INT_MAX); - return (int)ret; -} - /* At the risk of being a little inefficient, just keep attempting to cancel * everything. If a transfer's no longer active, we'll just get a NOT_FOUND * error -- no big deal. Just accepting that alleviates the need to track @@ -2120,6 +2037,9 @@ static void LIBUSB_CALL lusb_stream_cb(struct libusb_transfer *transfer) struct lusb_stream_data *stream_data = stream->backend_data; size_t bytes_per_buffer; + /* Currently unused - zero out for out own debugging sanity... */ + memset(&metadata, 0, sizeof(metadata)); + /* Check to see if the transfer has been cancelled or errored */ if( transfer->status != LIBUSB_TRANSFER_COMPLETED ) { @@ -2340,8 +2260,8 @@ static int lusb_stream(struct bladerf_stream *stream, bladerf_module module) dev->transfer_timeout[module] ); - log_debug("Initial transfer with buffer: %p (i=" PRIu64 ")\n", - buffer, (uint64_t)i); + log_verbose("Initial transfer with buffer: %p (i=%" PRIu64 ")\n", + buffer, (uint64_t)i); stream_data->active_transfers++; status = libusb_submit_transfer(stream_data->transfers[i]); @@ -2495,8 +2415,6 @@ const struct bladerf_fn bladerf_lusb_fn = { FIELD_INIT(.dac_write, lusb_dac_write), FIELD_INIT(.enable_module, lusb_enable_module), - FIELD_INIT(.rx, lusb_rx), - FIELD_INIT(.tx, lusb_tx), FIELD_INIT(.init_stream, lusb_stream_init), FIELD_INIT(.stream, lusb_stream), diff --git a/host/libraries/libbladeRF/src/backend/linux.c b/host/libraries/libbladeRF/src/backend/linux.c index bbd6f73c..51efec62 100644 --- a/host/libraries/libbladeRF/src/backend/linux.c +++ b/host/libraries/libbladeRF/src/backend/linux.c @@ -441,73 +441,6 @@ static int linux_dac_write(struct bladerf *dev, uint16_t val) return ret; } -/*------------------------------------------------------------------------------ - * Data transfer - *----------------------------------------------------------------------------*/ -static int linux_tx(struct bladerf *dev, bladerf_format format, - void *samples, int n, struct bladerf_metadata *metadata) -{ - ssize_t i, ret = 0; - size_t bytes_written = 0; - const size_t bytes_total = c16_samples_to_bytes(n); - struct bladerf_linux *backend = (struct bladerf_linux *)dev->backend; - int8_t *samples8 = (int8_t *)samples; - - while (bytes_written < bytes_total) { - - i = write(backend->fd, samples8 + bytes_written, bytes_total - bytes_written); - - if (i < 0 && errno != EINTR) { - int errno_val = errno; - bladerf_set_error(&dev->error, ETYPE_ERRNO, errno_val); - bytes_written = BLADERF_ERR_IO; - log_error("Failed to write with errno=%d: %s\n", - errno_val, strerror(errno_val)); - break; - } else if (i > 0) { - bytes_written += i; - } - } - - if (ret < 0) { - return ret; - } else { - return bytes_to_c16_samples(bytes_written); - } -} - -static int linux_rx(struct bladerf *dev, bladerf_format format, - void *samples, int n, struct bladerf_metadata *metadata) -{ - ssize_t i, ret = 0; - size_t bytes_read = 0; - const size_t bytes_total = c16_samples_to_bytes(n); - struct bladerf_linux *backend = (struct bladerf_linux *)dev->backend; - int8_t *samples8 = (int8_t *)samples; - - while (bytes_read < bytes_total) { - - i = read(backend->fd, samples8 + bytes_read, bytes_total - bytes_read); - - if (i < 0 && errno != EINTR) { - int errno_val = errno; - bladerf_set_error(&dev->error, ETYPE_ERRNO, errno_val); - ret = BLADERF_ERR_IO; - log_error("Read failed with errno=%d: %s\n", - errno_val, strerror(errno_val)); - break; - } else if (i > 0) { - bytes_read += i; - } - } - - if (ret < 0) { - return ret; - } else { - return bytes_to_c16_samples(bytes_read); - } -} - /*------------------------------------------------------------------------------ * Platform information *----------------------------------------------------------------------------*/ @@ -933,8 +866,6 @@ const struct bladerf_fn bladerf_linux_fn = { FIELD_INIT(.dac_write, linux_dac_write), FIELD_INIT(.enable_module, NULL), - FIELD_INIT(.rx, linux_rx), - FIELD_INIT(.tx, linux_tx), FIELD_INIT(.init_stream, linux_stream_init), FIELD_INIT(.stream, linux_stream), diff --git a/host/libraries/libbladeRF/src/bladerf.c b/host/libraries/libbladeRF/src/bladerf.c index e2682dd2..e6fc1e35 100644 --- a/host/libraries/libbladeRF/src/bladerf.c +++ b/host/libraries/libbladeRF/src/bladerf.c @@ -26,6 +26,7 @@ #include "libbladeRF.h" /* Public API */ #include "bladerf_priv.h" /* Implementation-specific items ("private") */ +#include "sync.h" #include "lms.h" #include "si5338.h" #include "file_ops.h" @@ -160,6 +161,10 @@ int bladerf_open(struct bladerf **device, const char *dev_id) void bladerf_close(struct bladerf *dev) { if (dev) { +#ifdef ENABLE_LIBBLADERF_SYNC + sync_deinit(dev->sync_rx); + sync_deinit(dev->sync_tx); +#endif dev->fn->close(dev); } } @@ -168,10 +173,27 @@ int bladerf_enable_module(struct bladerf *dev, bladerf_module m, bool enable) { int status; + log_debug("Enable Module: %s - %s\n", (m == BLADERF_MODULE_RX) ? "RX" : "TX", enable ? "True" : "False") ; +#ifdef ENABLE_LIBBLADERF_SYNC + if (enable == false) { + switch (m) { + case BLADERF_MODULE_TX: + sync_deinit(dev->sync_tx); + dev->sync_tx = NULL; + break; + + case BLADERF_MODULE_RX: + sync_deinit(dev->sync_rx); + dev->sync_rx = NULL; + break; + } + } +#endif + lms_enable_rffe(dev, m, enable); status = dev->fn->enable_module(dev, m, enable); @@ -458,46 +480,64 @@ int bladerf_get_frequency(struct bladerf *dev, return rv; } -int bladerf_set_transfer_timeout(struct bladerf *dev, bladerf_module module, - unsigned int timeout) { +int bladerf_set_stream_timeout(struct bladerf *dev, bladerf_module module, + unsigned int timeout) { if (dev) { dev->transfer_timeout[module] = timeout; return 0; } else { - return BLADERF_ERR_NODEV; + return BLADERF_ERR_INVAL; } } -int bladerf_get_transfer_timeout(struct bladerf *dev, bladerf_module module, - unsigned int *timeout) { +int bladerf_get_stream_timeout(struct bladerf *dev, bladerf_module module, + unsigned int *timeout) { if (dev) { *timeout = dev->transfer_timeout[module]; return 0; } else { - return BLADERF_ERR_NODEV; + return BLADERF_ERR_INVAL; } } -int bladerf_tx(struct bladerf *dev, bladerf_format format, void *samples, - int num_samples, struct bladerf_metadata *metadata) +int CALL_CONV bladerf_sync_config(struct bladerf *dev, + bladerf_module module, + bladerf_format format, + unsigned int num_buffers, + unsigned int buffer_size, + unsigned int num_transfers, + unsigned int stream_timeout) { - if (num_samples < 1024 || num_samples % 1024 != 0) { - log_debug("num_samples must be multiples of 1024\n"); - return BLADERF_ERR_INVAL; - } - - return dev->fn->tx(dev, format, samples, num_samples, metadata); +#ifdef ENABLE_LIBBLADERF_SYNC + return sync_init(dev, module, format, num_buffers, buffer_size, + num_transfers, stream_timeout); +#else + return BLADERF_ERR_UNSUPPORTED; +#endif } -int bladerf_rx(struct bladerf *dev, bladerf_format format, void *samples, - int num_samples, struct bladerf_metadata *metadata) +int bladerf_sync_tx(struct bladerf *dev, + void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, + unsigned int timeout_ms) { - if (num_samples < 1024 || num_samples % 1024 != 0) { - log_debug("num_samples must be multiples of 1024\n"); - return BLADERF_ERR_INVAL; - } +#ifdef ENABLE_LIBBLADERF_SYNC + return sync_tx(dev, samples, num_samples, metadata, timeout_ms); +#else + return BLADERF_ERR_UNSUPPORTED; +#endif +} - return dev->fn->rx(dev, format, samples, num_samples, metadata); +int bladerf_sync_rx(struct bladerf *dev, + void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, + unsigned int timeout_ms) +{ +#ifdef ENABLE_LIBBLADERF_SYNC + return sync_rx(dev, samples, num_samples, metadata, timeout_ms); +#else + return BLADERF_ERR_UNSUPPORTED; +#endif } int bladerf_init_stream(struct bladerf_stream **stream, diff --git a/host/libraries/libbladeRF/src/bladerf_priv.c b/host/libraries/libbladeRF/src/bladerf_priv.c index a9dc1f88..3db2c2cd 100644 --- a/host/libraries/libbladeRF/src/bladerf_priv.c +++ b/host/libraries/libbladeRF/src/bladerf_priv.c @@ -309,3 +309,25 @@ int bladerf_get_and_cache_fpga_size(struct bladerf *device) return status; } + +int populate_abs_timeout(struct timespec *t, unsigned int timeout_ms) +{ + static const int nsec_per_sec = 1000 * 1000 * 1000; + const unsigned int timeout_sec = timeout_ms / 1000; + int status; + + status = clock_gettime(CLOCK_REALTIME, t); + if (status != 0) { + return BLADERF_ERR_UNEXPECTED; + } else { + t->tv_sec += timeout_sec; + t->tv_nsec += (timeout_ms % 1000) * 1000 * 1000; + + if (t->tv_nsec >= nsec_per_sec) { + t->tv_sec += t->tv_nsec / nsec_per_sec; + t->tv_nsec %= nsec_per_sec; + } + + return 0; + } +} diff --git a/host/libraries/libbladeRF/src/bladerf_priv.h b/host/libraries/libbladeRF/src/bladerf_priv.h index 43b47dee..b5236650 100644 --- a/host/libraries/libbladeRF/src/bladerf_priv.h +++ b/host/libraries/libbladeRF/src/bladerf_priv.h @@ -32,6 +32,13 @@ #include #include #include "host_config.h" + +#if BLADERF_OS_WINDOWS || BLADERF_OS_OSX +#include "clock_gettime.h" +#else +#include +#endif + #include "minmax.h" #include "conversions.h" #include "devinfo.h" @@ -145,8 +152,6 @@ struct bladerf_fn { /* Sample stream */ int (*enable_module)(struct bladerf *dev, bladerf_module m, bool enable); - int (*rx)(struct bladerf *dev, bladerf_format format, void *samples, int n, struct bladerf_metadata *metadata); - int (*tx)(struct bladerf *dev, bladerf_format format, void *samples, int n, struct bladerf_metadata *metadata); int (*init_stream)(struct bladerf_stream *stream); int (*stream)(struct bladerf_stream *stream, bladerf_module module); @@ -185,7 +190,12 @@ struct bladerf { /* Driver-sppecific implementations */ const struct bladerf_fn *fn; + /* Stream transfer timeouts for RX and TX */ int transfer_timeout[2]; + + /* Synchronous interface handles */ + struct bladerf_sync *sync_rx; + struct bladerf_sync *sync_tx; }; /** @@ -298,5 +308,14 @@ int encode_field(char *ptr, int len, int *idx, const char *field, */ int add_field(char *buf, int len, const char *field, const char *val); +/** + * Populate the provided timeval structure for the specified timeout + * + * @param[out] t_abs Absolute timeout structure to populate + * @param[in] timeout_ms Desired timeout in ms. + * + * 0 on success, BLADERF_ERR_UNEXPECTED on failure + */ +int populate_abs_timeout(struct timespec *t_abs, unsigned int timeout_ms); #endif diff --git a/host/libraries/libbladeRF/src/lms.h b/host/libraries/libbladeRF/src/lms.h index 23a33929..a78984d5 100644 --- a/host/libraries/libbladeRF/src/lms.h +++ b/host/libraries/libbladeRF/src/lms.h @@ -550,8 +550,4 @@ int lms_config_init(struct bladerf *dev, struct lms_xcvr_config *config); int lms_select_band(struct bladerf *dev, bladerf_module module, unsigned int freq); -#ifdef __cplusplus -} -#endif - #endif /* LMS_H_ */ diff --git a/host/libraries/libbladeRF/src/sync.c b/host/libraries/libbladeRF/src/sync.c new file mode 100644 index 00000000..e2e636ee --- /dev/null +++ b/host/libraries/libbladeRF/src/sync.c @@ -0,0 +1,422 @@ +/* + * Copyright (C) 2014 Nuand LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef ENABLE_LIBBLADERF_SYNC +#error "Build configuration bug: this file should not be included in the build." +#endif + +#include + +/* Only switch on the verbose debug prints in this file when we *really* want + * them. Otherwise, compile them out to avoid excessive log level checks + * in our data path */ +#include "log.h" +#ifndef ENABLE_LIBBLADERF_SYNC_LOG_VERBOSE +#undef log_verbose +#define log_verbose(...) +#endif + +#include "bladerf_priv.h" +#include "sync.h" +#include "sync_worker.h" +#include "minmax.h" + +static inline size_t samples2bytes(struct bladerf_sync *s, unsigned int n) { + return s->stream_config.bytes_per_sample * n; +} + + +int sync_init(struct bladerf *dev, + bladerf_module module, + bladerf_format format, + unsigned int num_buffers, + unsigned int buffer_size, + unsigned int num_transfers, + unsigned int stream_timeout) + +{ + struct bladerf_sync *sync; + int status = 0; + size_t i, bytes_per_sample; + + if (num_transfers >= num_buffers) { + return BLADERF_ERR_INVAL; + } + + switch (format) { + case BLADERF_FORMAT_SC16_Q11: + bytes_per_sample = 4; + break; + + default: + return BLADERF_ERR_INVAL; + } + + /* bladeRF GPIF DMA requirement */ + if ((bytes_per_sample * buffer_size) % 4096 != 0) { + return BLADERF_ERR_INVAL; + } + + /* Deallocate any existing sync handle for this module */ + switch (module) { + case BLADERF_MODULE_RX: + sync_deinit(dev->sync_rx); + sync = dev->sync_rx = (struct bladerf_sync *) calloc(1, sizeof(struct bladerf_sync)); + if (dev->sync_rx == NULL) { + status = BLADERF_ERR_MEM; + } + break; + + case BLADERF_MODULE_TX: + sync_deinit(dev->sync_tx); + sync = dev->sync_tx = (struct bladerf_sync *) calloc(1, sizeof(struct bladerf_sync)); + if (dev->sync_tx == NULL) { + status = BLADERF_ERR_MEM; + } + break; + + default: + log_debug("Invalid bladerf_module value encountered: %d", module); + status = BLADERF_ERR_INVAL; + } + + if (status != 0) { + return status; + } + + sync->dev = dev; + + sync->stream_config.module = module; + sync->stream_config.format = format; + sync->stream_config.samples_per_buffer = buffer_size; + sync->stream_config.num_xfers = num_transfers; + sync->stream_config.timeout_ms = stream_timeout; + sync->stream_config.bytes_per_sample = bytes_per_sample; + + sync->buf_mgmt.num_buffers = num_buffers; + + pthread_mutex_init(&sync->buf_mgmt.lock, NULL); + pthread_cond_init(&sync->buf_mgmt.buf_consumed, NULL); + pthread_cond_init(&sync->buf_mgmt.buf_produced, NULL); + + sync->buf_mgmt.status = (sync_buffer_status*) malloc(num_buffers * sizeof(sync_buffer_status)); + if (sync->buf_mgmt.status == NULL) { + status = BLADERF_ERR_MEM; + } else { + switch (module) { + case BLADERF_MODULE_RX: + /* When starting up an RX stream, the first 'num_transfers' + * transfers will be submitted to the USB layer to grab data */ + sync->buf_mgmt.prod_i = num_transfers; + sync->buf_mgmt.cons_i = 0; + sync->buf_mgmt.partial_off = 0; + + for (i = 0; i < num_buffers; i++) { + if (i < num_transfers) { + sync->buf_mgmt.status[i] = SYNC_BUFFER_IN_FLIGHT; + } else { + sync->buf_mgmt.status[i] = SYNC_BUFFER_EMPTY; + } + } + break; + + case BLADERF_MODULE_TX: + sync->buf_mgmt.prod_i = 0; + sync->buf_mgmt.cons_i = 0; + sync->buf_mgmt.partial_off = 0; + + for (i = 0; i < num_buffers; i++) { + sync->buf_mgmt.status[i] = SYNC_BUFFER_EMPTY; + } + + break; + } + + status = sync_worker_init(sync); + } + + if (status != 0) { + switch (module) { + case BLADERF_MODULE_RX: + sync_deinit(dev->sync_rx); + dev->sync_rx = NULL; + break; + + case BLADERF_MODULE_TX: + sync_deinit(dev->sync_tx); + dev->sync_tx = NULL; + break; + } + } + + return status; +} + +void sync_deinit(struct bladerf_sync *sync) +{ + if (sync != NULL) { + + switch (sync->stream_config.module) { + case BLADERF_MODULE_RX: + sync_worker_deinit(sync->worker, + &sync->buf_mgmt.lock, + &sync->buf_mgmt.buf_consumed); + break; + + case BLADERF_MODULE_TX: + sync_worker_deinit(sync->worker, + &sync->buf_mgmt.lock, + &sync->buf_mgmt.buf_produced); + break; + + default: + assert(!"Invalid module encountered"); + break; + } + + /* De-allocate our buffer management resources */ + free(sync->buf_mgmt.status); + free(sync); + } +} + +static int check_worker(struct bladerf_sync *s) +{ + sync_worker_state state; + int status = 0; + const int max_retries = 8; + int retry = 0; + + do { + state = sync_worker_get_state(s->worker); + + if (state != SYNC_WORKER_STATE_RUNNING) { + + /* We need to start up the worker */ + log_debug("%s: Worker not running (state=%d)... %s\n", + __FUNCTION__, state, + retry == 0 ? "starting it." : "retrying."); + + sync_worker_submit_request(s->worker, SYNC_WORKER_START); + status = sync_worker_wait_for_state(s->worker, + SYNC_WORKER_STATE_RUNNING, 250); + if (status == 0) { + state = SYNC_WORKER_STATE_RUNNING; + log_debug("%s: Worker is now running.\n", __FUNCTION__); + } + } + } while ((state != SYNC_WORKER_STATE_RUNNING) && (++retry <= max_retries)); + + /* By this point, our worker should be running */ + if (status != 0 || state != SYNC_WORKER_STATE_RUNNING) { + if (status == 0) { + status = BLADERF_ERR_UNEXPECTED; + } + + log_debug("%s: %s worker failed to start (state=%d): %s\n", + __FUNCTION__, module2str(s->stream_config.module), + state, bladerf_strerror(status)); + } + + return status; +} + +int sync_rx(struct bladerf *dev, void *samples, unsigned num_samples, + struct bladerf_metadata *metadata, unsigned int timeout_ms) +{ + int status; + struct bladerf_sync *s = dev->sync_rx; + struct buffer_mgmt *b = &s->buf_mgmt; + unsigned int samples_returned = 0; + struct timespec timeout_abs; + + if (s == NULL) { + return BLADERF_ERR_INVAL; + } + + /* Check if our worker thread is running, and start it if it's not */ + status = check_worker(s); + + while(status == 0 && samples_returned < num_samples) { + pthread_mutex_lock(&b->lock); + + /* If we have a fresh buffer, mark that we're consuming it */ + if (b->status[b->cons_i] == SYNC_BUFFER_FULL) { + b->status[b->cons_i] = SYNC_BUFFER_PARTIAL; + b->partial_off = 0; + } + + if (b->status[b->cons_i] == SYNC_BUFFER_PARTIAL) { + /* We currently have a buffer to remove samples from */ + uint8_t *samples_dest = (uint8_t*)samples; + uint8_t *buf_src = (uint8_t*)b->buffers[b->cons_i]; + const unsigned int samples_to_copy = + uint_min(num_samples - samples_returned, + s->stream_config.samples_per_buffer - b->partial_off); + + memcpy(samples_dest + samples2bytes(s, samples_returned), + buf_src + samples2bytes(s, b->partial_off), + samples2bytes(s, samples_to_copy)); + + b->partial_off += samples_to_copy; + samples_returned += samples_to_copy; + + log_verbose("%s: Provided %u samples to caller\n", + __FUNCTION__, samples_to_copy); + + /* We've finished consuming this buffer and can start looking + * for available samples in the next buffer */ + if (b->partial_off >= s->stream_config.samples_per_buffer) { + log_verbose("%s: Marking buf[%u] empty.\n", + __FUNCTION__, b->cons_i); + + b->status[b->cons_i] = SYNC_BUFFER_EMPTY; + b->cons_i = (b->cons_i + 1) % b->num_buffers; + pthread_cond_signal(&b->buf_consumed); + } + + } else { + /* Need to wait for a buffer to become available */ + if (timeout_ms == 0) { + status = pthread_cond_wait(&b->buf_produced, &b->lock); + log_verbose("%s: Infinite wait for [%d] to fill.\n", + __FUNCTION__, b->cons_i); + } else { + log_verbose("%s: Timed wait for [%d] to fill.\n", + __FUNCTION__, b->cons_i); + status = populate_abs_timeout(&timeout_abs, timeout_ms); + if (status == 0) { + status = pthread_cond_timedwait(&b->buf_produced, &b->lock, + &timeout_abs); + } + } + } + pthread_mutex_unlock(&b->lock); + + if (status == -ETIMEDOUT) { + status = BLADERF_ERR_TIMEOUT; + } else if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + } else { + status = check_worker(s); + } + } + + return status; +} + +int sync_tx(struct bladerf *dev, void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, unsigned int timeout_ms) +{ + struct bladerf_sync *s = dev->sync_tx; + struct buffer_mgmt *b = &s->buf_mgmt; + struct timespec timeout_abs; + unsigned int samples_written = 0; + int status = 0; + + if (s == NULL) { + return BLADERF_ERR_INVAL; + } + + /* Check that our work thread is running, and start it if it's not */ + status = check_worker(s); + while (status == 0 && samples_written < num_samples) { + pthread_mutex_lock(&b->lock); + + /* If we've got an empty buffer, mark that we're producing it */ + if (b->status[b->prod_i] == SYNC_BUFFER_EMPTY) { + b->status[b->prod_i] = SYNC_BUFFER_PARTIAL; + b->partial_off = 0; + } + + if (b->status[b->prod_i] == SYNC_BUFFER_PARTIAL) { + /* We're currently filling a buffer */ + uint8_t *buf_dest = (uint8_t*)b->buffers[b->prod_i]; + uint8_t *samples_src = (uint8_t*)samples; + + const unsigned int samples_to_copy = + uint_min(num_samples - samples_written, + s->stream_config.samples_per_buffer - b->partial_off); + + memcpy(buf_dest + samples2bytes(s, b->partial_off), + samples_src + samples2bytes(s, samples_written), + samples2bytes(s, samples_to_copy)); + + b->partial_off += samples_to_copy; + samples_written += samples_to_copy; + + log_verbose("%s: Buffered %u samples from caller\n", + __FUNCTION__, samples_to_copy); + + if (b->partial_off >= s->stream_config.samples_per_buffer) { + log_verbose("%s: Marking buf[%u] full\n", + __FUNCTION__, b->prod_i); + + b->status[b->prod_i] = SYNC_BUFFER_FULL; + b->prod_i = (b->prod_i + 1) % b->num_buffers; + pthread_cond_signal(&b->buf_produced); + } + + } else { + /* We need to wait for a buffer to be emptied by the worker */ + if (timeout_ms == 0) { + log_verbose("%s: Infinite wait for [%d] to empty.\n", + __FUNCTION__, b->prod_i); + status = pthread_cond_wait(&b->buf_consumed, &b->lock); + } else { + status = populate_abs_timeout(&timeout_abs, timeout_ms); + if (status == 0) { + log_verbose("%s: Timed wait for [%d] to empty.\n", + __FUNCTION__, b->prod_i); + status = pthread_cond_timedwait(&b->buf_consumed, &b->lock, + &timeout_abs); + } + } + } + + pthread_mutex_unlock(&b->lock); + + if (status == -ETIMEDOUT) { + status = BLADERF_ERR_TIMEOUT; + } else if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + } else { + status = check_worker(s); + } + } + + return status; +} + +unsigned int sync_buf2idx(struct buffer_mgmt *b, void *addr) +{ + unsigned int i; + + for (i = 0; i < b->num_buffers; i++) { + if (b->buffers[i] == addr) { + return i; + } + } + + assert(!"Bug: Buffer not found."); + + /* Assertions are intended to always remain on. If someone turned them + * off, do the best we can...complain loudly and clobber a buffer */ + log_critical("Bug: Buffer not found."); + return 0; +} + diff --git a/host/libraries/libbladeRF/src/sync.h b/host/libraries/libbladeRF/src/sync.h new file mode 100644 index 00000000..9ec11be1 --- /dev/null +++ b/host/libraries/libbladeRF/src/sync.h @@ -0,0 +1,108 @@ +/* + * This file is part of the bladeRF project: + * http://www.github.com/nuand/bladeRF + * + * Copyright (C) 2014 Nuand LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#if !defined(BLADERF_SYNC_H_) && defined(ENABLE_LIBBLADERF_SYNC) +#define BLADERF_SYNC_H_ + +#include +#include + +#define MODULE_STR(s) module2str(s->stream_config.module) + +/* These parameters are only written during sync_init */ +struct stream_config +{ + bladerf_format format; + bladerf_module module; + + unsigned int samples_per_buffer; + unsigned int num_xfers; + unsigned int timeout_ms; + + size_t bytes_per_sample; +}; + +typedef enum { + SYNC_BUFFER_EMPTY = 0, /**< Buffer contains no data */ + SYNC_BUFFER_PARTIAL, /**< sync_rx/tx is currently emptying/filling */ + SYNC_BUFFER_FULL, /**< Buffer is full of data */ + SYNC_BUFFER_IN_FLIGHT, /**< Currently being transferred */ +} sync_buffer_status; + +struct buffer_mgmt { + sync_buffer_status *status; + + void **buffers; + unsigned int num_buffers; + + unsigned int prod_i; /**< Producer index - next buffer to fill */ + unsigned int cons_i; /**< Consumer index - next buffer to empty */ + unsigned int partial_off; /**< Current index into partial buffer */ + + pthread_mutex_t lock; + pthread_cond_t buf_consumed; + pthread_cond_t buf_produced; +}; + +struct bladerf_sync { + struct bladerf *dev; + struct buffer_mgmt buf_mgmt; + struct sync_worker *worker; + struct stream_config stream_config; +}; + +/** + * Create and initialize as synchronous interface handle for the specified + * device and module. If the synchronous handle is already initialized, this + * call will first deinitialize it. + * + * The associated stream will be started at the first RX or TX call + * + * @return 0 or BLADERF_ERR_* value on failure + */ +int sync_init(struct bladerf *dev, + bladerf_module module, + bladerf_format format, + unsigned int num_buffers, + unsigned int buffer_size, + unsigned int num_transfers, + unsigned int stream_timeout); + +/** + * Deinitialize the sync handle. This tears down and deallocates the underlying + * asynchronous stream. + * + * @param sync Handle to deinitialize. + */ +void sync_deinit(struct bladerf_sync *sync); + + +int sync_rx(struct bladerf *dev, void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, unsigned int timeout_ms); + +int sync_tx(struct bladerf *dev, void *samples, unsigned int num_samples, + struct bladerf_metadata *metadata, unsigned int timeout_ms); + +unsigned int sync_buf2idx(struct buffer_mgmt *b, void *addr); + +void * sync_idx2buf(struct buffer_mgmt *b, unsigned int idx); + +#endif diff --git a/host/libraries/libbladeRF/src/sync_worker.c b/host/libraries/libbladeRF/src/sync_worker.c new file mode 100644 index 00000000..61a91a09 --- /dev/null +++ b/host/libraries/libbladeRF/src/sync_worker.c @@ -0,0 +1,571 @@ +/* + * Copyright (C) 2014 Nuand LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef ENABLE_LIBBLADERF_SYNC +#error "Build configuration bug: this file should not be included in the build." +#endif + +#include +#include +#include + + +/* Only switch on the verbose debug prints in this file when we *really* want + * them. Otherwise, compile them out to avoid excessive log level checks + * in our data path */ +#include "log.h" +#ifndef ENABLE_LIBBLADERF_SYNC_LOG_VERBOSE +#undef log_verbose +#define log_verbose(...) +#endif + +#include "rel_assert.h" +#include "bladerf_priv.h" +#include "sync.h" +#include "sync_worker.h" +#include "conversions.h" + +void *sync_worker_task(void *arg); + +static void *rx_callback(struct bladerf *dev, + struct bladerf_stream *stream, + struct bladerf_metadata *meta, + void *samples, + size_t num_samples, + void *user_data) +{ + int status = 0; + unsigned int requests; /* Pending requests */ + unsigned int next_idx; + unsigned int samples_idx; + void *next_buf = NULL; /* Next buffer to submit for reception */ + + struct bladerf_sync *s = (struct bladerf_sync *)user_data; + struct sync_worker *w = s->worker; + struct buffer_mgmt *b = &s->buf_mgmt; + + /* Check if the caller has requested us to shut down. We'll keep the + * SHUTDOWN bit set through our transition into the IDLE state so we + * can act on it there. */ + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + + if (requests & SYNC_WORKER_STOP) { + log_verbose("%s worker: Got STOP request upon entering callback. " + "Ending stream.\n", MODULE_STR(s)); + return NULL; + } + + pthread_mutex_lock(&b->lock); + + /* Mark this buffer as full */ + samples_idx = sync_buf2idx(b, samples); + assert(b->status[samples_idx] == SYNC_BUFFER_IN_FLIGHT); + b->status[samples_idx] = SYNC_BUFFER_FULL; + + /* Update to our next buffer */ + next_idx = b->prod_i; + next_buf = b->buffers[next_idx]; + + /* Wait for a buffer to free up, if needed */ + if (s->stream_config.timeout_ms == 0) { + while (status == 0 && + b->status[next_idx] != SYNC_BUFFER_EMPTY && + (requests & SYNC_WORKER_STOP) == 0) { + + log_verbose("%s worker: Infinite wait for buf[%u] to empty\n", + MODULE_STR(s), next_idx); + + status = pthread_cond_wait(&b->buf_consumed, &b->lock); + + /* Fetch requests that we might have gotten while sleeping */ + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + } + } else { + struct timespec timeout_abs; + status = populate_abs_timeout(&timeout_abs, + s->stream_config.timeout_ms); + + while (status == 0 && + b->status[next_idx] != SYNC_BUFFER_EMPTY && + (requests & SYNC_WORKER_STOP) == 0) { + + log_verbose("%s worker: Timed wait for buf[%u] to empty\n", + MODULE_STR(s), next_idx); + + status = pthread_cond_timedwait(&b->buf_consumed, &b->lock, + &timeout_abs); + + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + } + } + + if (requests & SYNC_WORKER_STOP) { + next_buf = NULL; + log_verbose("%s worker: Got STOP request while waiting in callback. " + "Ending stream.\n", MODULE_STR(s)); + } else if (status == 0) { + b->status[next_idx] = SYNC_BUFFER_IN_FLIGHT; + b->prod_i = (next_idx + 1) % b->num_buffers; + + pthread_cond_signal(&b->buf_produced); + } + + pthread_mutex_unlock(&b->lock); + + if (status == 0) { + log_verbose("%s worker: buf[%u] = full, buf[%u] = in_flight\n", + MODULE_STR(s), samples_idx, next_idx); + } else { + next_buf = NULL; + if (status == ETIMEDOUT) { + log_debug("%s worker: Timed out. Shutting down.\n", + MODULE_STR(s), status); + } else { + log_debug("%s worker: Unexpected error (%d), shutting down.\n", + MODULE_STR(s), status); + } + + /* The API caller may be blocked waiting on us to produce a buffer, + * so we need to wake them and let them figure out what to do */ + pthread_mutex_lock(&b->lock); + pthread_cond_signal(&b->buf_produced); + pthread_mutex_unlock(&b->lock); + } + + return next_buf; +} + +static void *tx_callback(struct bladerf *dev, + struct bladerf_stream *stream, + struct bladerf_metadata *meta, + void *samples, + size_t num_samples, + void *user_data) +{ + int status = 0; + unsigned int requests; /* Pending requests */ + unsigned int completed_idx; /* Index of completed buffer */ + unsigned int next_idx; /* Index of next buffer to submit */ + void *next_buf = NULL; /* Next buffer to submit for transmission */ + + struct bladerf_sync *s = (struct bladerf_sync *)user_data; + struct sync_worker *w = s->worker; + struct buffer_mgmt *b = &s->buf_mgmt; + + /* Check if the caller has requested us to shut down. We'll keep the + * SHUTDOWN bit set through our transition into the IDLE state so we + * can act on it there. */ + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + + if (requests & SYNC_WORKER_STOP) { + log_verbose("%s worker: Got STOP request upon entering callback. " + "Ending stream.\n", MODULE_STR(s)); + return NULL; + } + + pthread_mutex_lock(&b->lock); + + /* Mark the last transfer as being completed. Note that the first + * callbacks we get have samples=NULL */ + if (samples != NULL) { + completed_idx = sync_buf2idx(b, samples); + assert(b->status[completed_idx] == SYNC_BUFFER_IN_FLIGHT); + b->status[completed_idx] = SYNC_BUFFER_EMPTY; + pthread_cond_signal(&b->buf_consumed); + } else { + completed_idx = UINT_MAX; /* Just for debug purposes */ + } + + /* Wait for a full buffer to become available for consumption */ + if (s->stream_config.timeout_ms == 0) { + while (status == 0 && + b->status[b->cons_i] != SYNC_BUFFER_FULL && + (requests & SYNC_WORKER_STOP) == 0) { + + log_verbose("%s worker: Infinite wait for buf[%u] to fill\n", + MODULE_STR(s), b->cons_i); + + status = pthread_cond_wait(&b->buf_produced, &b->lock); + + /* Fetch requests that we might have gotten while sleeping */ + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + + log_verbose("%s worker: Woke, requests are now: 0x%08x\n", + MODULE_STR(s), requests); + } + } else { + struct timespec timeout_abs; + status = populate_abs_timeout(&timeout_abs, + s->stream_config.timeout_ms); + + while (status == 0 && + b->status[b->cons_i] != SYNC_BUFFER_FULL && + (requests & SYNC_WORKER_STOP) == 0) { + + log_verbose("%s worker: Timed wait for buf[%u] to fill\n", + MODULE_STR(s), b->cons_i); + + status = pthread_cond_timedwait(&b->buf_produced, &b->lock, + &timeout_abs); + + pthread_mutex_lock(&w->request_lock); + requests = w->requests; + pthread_mutex_unlock(&w->request_lock); + } + } + + /* Mark this buffer as being sent and update our reference to the + * next buffer we'll use */ + if (status == 0) { + next_idx = b->cons_i; + b->status[next_idx] = SYNC_BUFFER_IN_FLIGHT; + next_buf = b->buffers[next_idx]; + b->cons_i = (b->cons_i + 1) % b->num_buffers; + } + + pthread_mutex_unlock(&b->lock); + + if (requests & SYNC_WORKER_STOP) { + next_buf = NULL; + log_verbose("%s worker: Got STOP request while waiting in callback. " + "Ending stream.\n", MODULE_STR(s)); + } else if (status == 0) { + log_verbose("%s worker: buf[%u] = in_flight, buf[%u] = empty\n", + MODULE_STR(s), next_idx, completed_idx); + } else { + next_buf = NULL; + + if (status == ETIMEDOUT) { + log_debug("%s worker: Timed out. Shutting down.\n", + MODULE_STR(s), status); + } else { + log_debug("%s worker: Unexpected error (%d), shutting down.\n", + MODULE_STR(s), status); + } + + /* The API caller may be blocked waiting on us to consume a buffer, + * so we need to wake them and let them figure out what to do */ + pthread_mutex_lock(&b->lock); + pthread_cond_signal(&b->buf_consumed); + pthread_mutex_unlock(&b->lock); + } + + return next_buf; +} + +int sync_worker_init(struct bladerf_sync *s) +{ + int status = 0; + s->worker = (struct sync_worker*) calloc(1, sizeof(*s->worker)); + + if (s->worker == NULL) { + status = BLADERF_ERR_MEM; + goto worker_init_out; + } + + s->worker->state = SYNC_WORKER_STATE_STARTUP; + s->worker->cb = s->stream_config.module == BLADERF_MODULE_RX ? + rx_callback : tx_callback; + + status = bladerf_init_stream(&s->worker->stream, + s->dev, + s->worker->cb, + &s->buf_mgmt.buffers, + s->buf_mgmt.num_buffers, + s->stream_config.format, + s->stream_config.samples_per_buffer, + s->stream_config.num_xfers, + s); + + if (status != 0) { + log_debug("%s worker: Failed to init stream: %s\n", MODULE_STR(s), + bladerf_strerror(status)); + goto worker_init_out; + } + + + status = pthread_mutex_init(&s->worker->state_lock, NULL); + if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + goto worker_init_out; + } + + status = pthread_cond_init(&s->worker->state_changed, NULL); + if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + goto worker_init_out; + } + + status = pthread_mutex_init(&s->worker->request_lock, NULL); + if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + goto worker_init_out; + } + + status = pthread_cond_init(&s->worker->requests_pending, NULL); + if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + goto worker_init_out; + } + + status = pthread_create(&s->worker->thread, NULL, sync_worker_task, s); + if (status != 0) { + status = BLADERF_ERR_UNEXPECTED; + goto worker_init_out; + } + + /* Wait until the worker thread has initialized and is ready to go */ + status = sync_worker_wait_for_state(s->worker, SYNC_WORKER_STATE_IDLE, 1000); + if (status != 0) { + status = BLADERF_ERR_TIMEOUT; + goto worker_init_out; + } + +worker_init_out: + if (status != 0) { + free(s->worker); + s->worker = NULL; + } + + return status; +} + +void sync_worker_deinit(struct sync_worker *w, + pthread_mutex_t *lock, pthread_cond_t *cond) +{ + int status; + + if (w == NULL) { + log_debug("%s called with NULL ptr\n", __FUNCTION__); + return; + } + + log_verbose("%s: Requesting worker %p to stop...\n", __FUNCTION__, w); + + sync_worker_submit_request(w, SYNC_WORKER_STOP); + + if (lock != NULL && cond != NULL) { + pthread_mutex_lock(lock); + pthread_cond_signal(cond); + pthread_mutex_unlock(lock); + } + + status = sync_worker_wait_for_state(w, SYNC_WORKER_STATE_STOPPED, 3000); + + if (status != 0) { + log_warning("Timed out while stopping worker. Canceling thread.\n"); + pthread_cancel(w->thread); + } + + pthread_join(w->thread, NULL); + log_verbose("%s: Worker joined.\n", __FUNCTION__); + + bladerf_deinit_stream(w->stream); + + free(w); +} + +void sync_worker_submit_request(struct sync_worker *w, unsigned int request) +{ + pthread_mutex_lock(&w->request_lock); + w->requests |= request; + pthread_cond_signal(&w->requests_pending); + pthread_mutex_unlock(&w->request_lock); +} + +int sync_worker_wait_for_state(struct sync_worker *w, sync_worker_state state, + unsigned int timeout_ms) +{ + int status = 0; + struct timespec timeout_abs; + const int nsec_per_sec = 1000 * 1000 * 1000; + + if (timeout_ms != 0) { + const unsigned int timeout_sec = timeout_ms / 1000; + + status = clock_gettime(CLOCK_REALTIME, &timeout_abs); + if (status != 0) { + return BLADERF_ERR_UNEXPECTED; + } + + timeout_abs.tv_sec += timeout_sec; + timeout_abs.tv_nsec += (timeout_ms % 1000) * 1000 * 1000; + + if (timeout_abs.tv_nsec >= nsec_per_sec) { + timeout_abs.tv_sec += timeout_abs.tv_nsec / nsec_per_sec; + timeout_abs.tv_nsec %= nsec_per_sec; + } + + pthread_mutex_lock(&w->state_lock); + status = 0; + while (w->state != state && status == 0) { + status = pthread_cond_timedwait(&w->state_changed, + &w->state_lock, + &timeout_abs); + } + pthread_mutex_unlock(&w->state_lock); + + } else { + pthread_mutex_lock(&w->state_lock); + while (w->state != state) { + log_verbose(": Waiting for state change, current = %d\n", w->state); + status = pthread_cond_wait(&w->state_changed, + &w->state_lock); + } + pthread_mutex_unlock(&w->state_lock); + } + + if (status != 0) { + log_debug("%s: Wait on state change failed: %s\n", + __FUNCTION__, strerror(status)); + + if (status == ETIMEDOUT) { + status = BLADERF_ERR_TIMEOUT; + } else { + status = BLADERF_ERR_UNEXPECTED; + } + } + + return status; +} + +sync_worker_state sync_worker_get_state(struct sync_worker *w) +{ + sync_worker_state ret; + + pthread_mutex_lock(&w->state_lock); + ret = w->state; + pthread_mutex_unlock(&w->state_lock); + + return ret; +} + +static void set_state(struct sync_worker *w, sync_worker_state state) +{ + pthread_mutex_lock(&w->state_lock); + w->state = state; + pthread_cond_signal(&w->state_changed); + pthread_mutex_unlock(&w->state_lock); +} + + +static sync_worker_state exec_idle_state(struct bladerf_sync *s) +{ + sync_worker_state next_state = SYNC_WORKER_STATE_IDLE; + + pthread_mutex_lock(&s->worker->request_lock); + + while (s->worker->requests == 0) { + log_verbose("%s worker: Waiting for pending requests\n", MODULE_STR(s)); + + pthread_cond_wait(&s->worker->requests_pending, + &s->worker->request_lock); + } + + if (s->worker->requests & SYNC_WORKER_STOP) { + log_verbose("%s worker: Got request to stop\n", + module2str(s->stream_config.module)); + + next_state = SYNC_WORKER_STATE_SHUTTING_DOWN; + + } else if (s->worker->requests & SYNC_WORKER_START) { + log_verbose("%s worker: Got request to start\n", + module2str(s->stream_config.module)); + + next_state = SYNC_WORKER_STATE_RUNNING; + } else { + log_warning("Invalid request value encountered: 0x%08X\n", + s->worker->requests); + } + + s->worker->requests = 0; + pthread_mutex_unlock(&s->worker->request_lock); + + return next_state; +} + +static void exec_running_state(struct bladerf_sync *s) +{ + int status; + + status = bladerf_stream(s->worker->stream, s->stream_config.module); + + log_verbose("%s worker: stream ended with: %s\n", + MODULE_STR(s), bladerf_strerror(status)); + + /* Suppress warning if log_verbose is disabled */ + (void)status; +} + +void *sync_worker_task(void *arg) +{ + sync_worker_state state = SYNC_WORKER_STATE_IDLE; + struct bladerf_sync *s = (struct bladerf_sync *)arg; + + log_verbose("%s worker: task started\n", MODULE_STR(s)); + set_state(s->worker, state); + log_verbose("%s worker: task state set\n", MODULE_STR(s)); + + while (state != SYNC_WORKER_STATE_STOPPED) { + + switch (state) { + case SYNC_WORKER_STATE_STARTUP: + assert(!"Worker in unexepected state, shutting down. (STARTUP)"); + set_state(s->worker, SYNC_WORKER_STATE_SHUTTING_DOWN); + break; + + case SYNC_WORKER_STATE_IDLE: + state = exec_idle_state(s); + set_state(s->worker, state); + break; + + case SYNC_WORKER_STATE_RUNNING: + exec_running_state(s); + state = SYNC_WORKER_STATE_IDLE; + set_state(s->worker, state); + break; + + case SYNC_WORKER_STATE_SHUTTING_DOWN: + log_verbose("%s worker: Shutting down...\n", MODULE_STR(s)); + + state = SYNC_WORKER_STATE_STOPPED; + set_state(s->worker, state); + break; + + case SYNC_WORKER_STATE_STOPPED: + assert(!"Worker in unexepected state: STOPPED"); + break; + + default: + assert(!"Worker in unexepected state, shutting down. (UNKNOWN)"); + set_state(s->worker, SYNC_WORKER_STATE_SHUTTING_DOWN); + break; + } + } + + return NULL; +} diff --git a/host/libraries/libbladeRF/src/sync_worker.h b/host/libraries/libbladeRF/src/sync_worker.h new file mode 100644 index 00000000..0eed2bbe --- /dev/null +++ b/host/libraries/libbladeRF/src/sync_worker.h @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2014 Nuand LLC + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#if !defined(BLADERF_SYNC_WORKER_H_) && defined(ENABLE_LIBBLADERF_SYNC) +#define BLADERF_SYNC_WORKER_H_ + +#include "host_config.h" +#include +#include +#include "sync.h" + +#if BLADERF_OS_WINDOWS || BLADERF_OS_OSX +#include "clock_gettime.h" +#else +#include +#endif + +/* Worker lifetime: + * + * STARTUP --+--> IDLE --> RUNNING --+--> SHUTTING_DOWN --> STOPPED + * ^----------------------/ + */ + +/* Request flags */ +#define SYNC_WORKER_START (1 << 0) +#define SYNC_WORKER_STOP (1 << 1) + +typedef enum { + SYNC_WORKER_STATE_STARTUP, + SYNC_WORKER_STATE_IDLE, + SYNC_WORKER_STATE_RUNNING, + SYNC_WORKER_STATE_SHUTTING_DOWN, + SYNC_WORKER_STATE_STOPPED +} sync_worker_state; + +struct sync_worker { + pthread_t thread; + + struct bladerf_stream *stream; + bladerf_stream_cb cb; + + sync_worker_state state; + pthread_mutex_t state_lock; + pthread_cond_t state_changed; /* Worker thread uses this to inform a + * waiting main thread about a state + * change */ + + /* The requests lock should always be acquired AFTER + * the sync->buf_mgmg.lock + */ + unsigned int requests; + pthread_cond_t requests_pending; + pthread_mutex_t request_lock; +}; + +/** + * Create a launch a worker thread. It will enter the IDLE state upon + * executing. + * + * @param[in] s Sync handle containing worker to initialize + * + * @return 0 on success, BLADERF_ERR_* on failure + */ +int sync_worker_init(struct bladerf_sync *s); + +/** + * Shutdown and deinitialize + * + * @param[in] w Worker to deinitialize + * @param[in] lock Acquired to signal `cond` if non-NULL + * @param[in] cond If non-NULL, this is signaled after requesting the + * worker to shut down, waking a potentially blocked + * workers. + */ +void sync_worker_deinit(struct sync_worker *w, + pthread_mutex_t *lock, pthread_cond_t *cond); + +/** + * Wait for state change with optional timeout + * + * @param w Worker to wait for + * @param state State to wait for + * @param timeout_ms Timeout in ms. 0 implies "wait forever" + * + * @return 0 on success, + * BLADERF_ERR_TIMEOUT on timeout, + * BLADERF_ERR_UNKNOWN on other errors + */ +int sync_worker_wait_for_state(struct sync_worker *w, + sync_worker_state state, + unsigned int timeout_ms); + +/** + * Get the worker's current state. + * + * @param w Worker to query + * + * @return Worker's current state + */ +sync_worker_state sync_worker_get_state(struct sync_worker *w); + +/** + * Submit a request to the worker task + * + * @param w Worker to send request to + * @param request Bitmask of requests to submit + */ +void sync_worker_submit_request(struct sync_worker *w, unsigned int request); + +#endif diff --git a/host/libraries/libbladeRF/tests/CMakeLists.txt b/host/libraries/libbladeRF/tests/CMakeLists.txt index 80020453..84b5cf69 100644 --- a/host/libraries/libbladeRF/tests/CMakeLists.txt +++ b/host/libraries/libbladeRF/tests/CMakeLists.txt @@ -1,3 +1,4 @@ cmake_minimum_required(VERSION 2.8) add_subdirectory(test_async) +add_subdirectory(test_sync) add_subdirectory(test_repeater) diff --git a/host/libraries/libbladeRF/tests/test_async/main.c b/host/libraries/libbladeRF/tests/test_async/main.c index fb9d587a..970fa3c8 100644 --- a/host/libraries/libbladeRF/tests/test_async/main.c +++ b/host/libraries/libbladeRF/tests/test_async/main.c @@ -72,8 +72,8 @@ int str2int(const char *str, int min, int max, bool *ok) } void *stream_callback(struct bladerf *dev, struct bladerf_stream *stream, - struct bladerf_metadata *metadata, void *samples, - size_t num_samples, void *user_data) + struct bladerf_metadata *metadata, void *samples, + size_t num_samples, void *user_data) { struct test_data *my_data = (struct test_data *)user_data; @@ -260,7 +260,7 @@ int main(int argc, char *argv[]) test_data.samples_per_buffer, test_data.num_buffers, &test_data - ) ; + ); /* Populate buffers with test data */ if( test_data.module == BLADERF_MODULE_TX ) { diff --git a/host/libraries/libbladeRF/tests/test_sync/CMakeLists.txt b/host/libraries/libbladeRF/tests/test_sync/CMakeLists.txt new file mode 100644 index 00000000..f47d6cde --- /dev/null +++ b/host/libraries/libbladeRF/tests/test_sync/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 2.8) +project(libbladeRF_test_sync C) + +include_directories(${libbladeRF_SOURCE_DIR}/include) +include_directories(${libbladeRF_sync_SOURCE_DIR}/include) + +set(SRC + src/main.c + src/test.c + ${BLADERF_HOST_COMMON_SOURCE_DIR}/conversions.c + ${BLADERF_HOST_COMMON_SOURCE_DIR}/log.c +) + +if(MSVC) + set(SRC ${SRC} + ${BLADERF_HOST_COMMON_SOURCE_DIR}/windows/getopt_long.c + ) +endif() + +add_executable(libbladeRF_test_sync ${SRC}) +target_link_libraries(libbladeRF_test_sync libbladerf_shared) diff --git a/host/libraries/libbladeRF/tests/test_sync/src/main.c b/host/libraries/libbladeRF/tests/test_sync/src/main.c new file mode 100644 index 00000000..e6fa6d5a --- /dev/null +++ b/host/libraries/libbladeRF/tests/test_sync/src/main.c @@ -0,0 +1,364 @@ +/* + * This file is part of the bladeRF project: + * http://www.github.com/nuand/bladeRF + * + * Copyright (C) 2014 Nuand LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "conversions.h" +#include "log.h" +#include "test.h" + +/* FIXME these should be provided in libbladeRF.h */ +#define SAMPLERATE_MIN 160000 +#define SAMPLERATE_MAX 40000000 +#define FREQ_MIN 300000000 +#define FREQ_MAX 3000000000 + +#define OPTSTR "hd:s:f:i:o:r:c:b:X:B:C:T:" +const struct option long_options[] = { + { "help", no_argument, 0, 'h' }, + + /* Device configuration */ + { "device", required_argument, 0, 'd' }, + { "samplerate", required_argument, 0, 's' }, + { "frequency", required_argument, 0, 'f' }, + + /* Test configuration */ + { "input", required_argument, 0, 'i' }, + { "output", required_argument, 0, 'o' }, + { "tx-repetitions", required_argument, 0, 'r' }, + { "rx-count", required_argument, 0, 'c' }, + { "block-size", required_argument, 0, 'b' }, + + /* Stream configuration */ + { "num-xfers", required_argument, 0, 'X' }, + { "buffer-size", required_argument, 0, 'B' }, + { "buffer-count", required_argument, 0, 'C' }, + { "timeout", required_argument, 0, 'T' }, + + /* Verbosity options */ + { "verbosity", required_argument, 0, 1, }, + { "lib-verbosity", required_argument, 0, 2, }, + { 0, 0, 0, 0 }, +}; + +const struct numeric_suffix freq_suffixes[] = { + { "K", 1000 }, + { "kHz", 1000 }, + { "M", 1000000 }, + { "MHz", 1000000 }, + { "G", 1000000000 }, + { "GHz", 1000000000 }, +}; + +const unsigned int num_freq_suffixes = sizeof(freq_suffixes) / sizeof(freq_suffixes[0]); + +const struct numeric_suffix size_suffixes[] = { + { "K", 1024 }, + { "M", 1024 * 1024 }, + { "G", 1024 * 1024 * 1024 }, +}; + +const unsigned int num_size_suffixes = sizeof(size_suffixes) / sizeof(size_suffixes[0]); + +const struct numeric_suffix count_suffixes[] = { + { "K", 1000 }, + { "M", 1000000 }, + { "G", 1000000000 }, +}; + +const unsigned int num_count_suffixes = sizeof(count_suffixes) / sizeof(count_suffixes[0]); + + +static void print_usage(const char *argv0) +{ + printf("Usage: %s [options]\n", argv0); + printf("libbladeRF_sync_test: RX/TX samples to/from specified files.\n"); + printf("\n"); + + printf("Device configuration options:\n"); + printf(" -d. --device Use the specified device. By default,\n"); + printf(" any device found will be used.\n"); + printf(" -f, --frequency Set the specified frequency. Default = %u.\n", DEFAULT_FREQUENCY); + printf(" -s, --samplerate Set the specified sample rate. Default = %u.\n", DEFAULT_SAMPLERATE); + printf("\n"); + + printf("Test configuration options:\n"); + printf(" -i, --input File to transmit samples from.\n"); + printf(" -o, --output File to receive samples to.\n"); + printf(" -r, --tx-repetitions # of times to repeat input file. Default = %u\n", DEFAULT_TX_REPETITIONS); + printf(" -c, --rx-count # of samples to receive. Defauilt = %u.\n", DEFAULT_RX_COUNT); + printf(" -b, --block-size # samples to RX/TX per sync call. Default = %u.\n", DEFAULT_BLOCK_SIZE); + printf("\n"); + + printf("Stream configuration options:\n"); + printf(" -X, --num-xfers # in-flight transfers. Default = %u.\n", DEFAULT_STREAM_XFERS); + printf(" -B, --buffer-size # samples per stream buffer. Default = %u.\n", DEFAULT_STREAM_SAMPLES); + printf(" -C, --buffer-count # of stream buffers. Default = %u.\n", DEFAULT_STREAM_BUFFERS); + printf(" -T, --timeout Stream timeout, in ms. Default = %u.\n", DEFAULT_STREAM_TIMEOUT); + + printf("\n"); + + printf("Misc options:\n"); + printf(" -h, --help Show this help text\n"); + printf(" --verbosity Set test verbosity (Default: warning)\n"); + printf(" --sync-verbosity Set libbladeRF_sync verbosity (Default: warning)\n"); + printf(" --lib-verbosity Set libbladeRF verbosity (Default: warning)\n"); + printf("\n"); + + printf("Notes:\n"); + printf(" The provided files must contain binary SC16 Q11 samples.\n"); + printf(" The -f and -s options are applied to both RX and TX modules.\n"); + printf("\n"); +} + +int handle_cmdline(int argc, char *argv[], struct test_params *p) +{ + int c; + int idx; + bool ok; + bladerf_log_level level; + + test_init_params(p); + + while ((c = getopt_long(argc, argv, OPTSTR, long_options, &idx)) >= 0) { + switch (c) { + + case 1: + level = str2loglevel(optarg, &ok); + if (!ok) { + log_error("Invalid log level provided: %s\n", optarg); + return -1; + } else { + log_set_verbosity(level); + } + break; + + case 2: + level = str2loglevel(optarg, &ok); + if (!ok) { + log_error("Invalid log level provided: %s\n", optarg); + return -1; + } else { + bladerf_log_set_verbosity(level); + } + break; + + case 'h': + return 1; + + case 'd': + if (p->device_str != NULL) { + log_error("Device was already specified.\n"); + return -1; + } + + p->device_str = strdup(optarg); + if (p->device_str == NULL) { + perror("strdup"); + return -1; + } + break; + + case 's': + p->samplerate = str2uint_suffix(optarg, + SAMPLERATE_MIN, SAMPLERATE_MAX, + freq_suffixes, + num_freq_suffixes, + &ok); + if (!ok) { + log_error("Invalid sample rate: %s\n", optarg); + return -1; + } + break; + + case 'f': + p->frequency = str2uint_suffix(optarg, + FREQ_MIN, FREQ_MAX, + freq_suffixes, + num_freq_suffixes, + &ok); + if (!ok) { + log_error("Invalid frequency: %s\n", optarg); + return -1; + } + + + case 'i': + if (p->in_file) { + log_error("Input file already provided.\n"); + return -1; + } + + p->in_file = fopen(optarg, "rb"); + if (p->in_file == NULL) { + log_error("Failed to open input file - %s\n", + strerror(errno)); + return -1; + } + break; + + case 'o': + if (p->out_file) { + log_error("Output file already provided.\n"); + return -1; + } + + p->out_file = fopen(optarg, "wb"); + if (p->out_file == NULL) { + log_error("Failed to open output file - %s\n", + strerror(errno)); + return -1; + } + break; + + case 'r': + p->tx_repetitions = str2uint_suffix(optarg, 1, UINT_MAX, + count_suffixes, + num_count_suffixes, + &ok); + if (!ok) { + log_error("Invalid TX repetition value: %s\n", optarg); + return -1; + } + + break; + + case 'c': + p->rx_count = str2uint_suffix(optarg, 1, UINT_MAX, + count_suffixes, + num_count_suffixes, + &ok); + if (!ok) { + log_error("Invalid RX count: %s\n", optarg); + return -1; + } + + break; + + case 'b': + p->block_size = str2uint_suffix(optarg, 1, UINT_MAX, + size_suffixes, + num_size_suffixes, + &ok); + + if (!ok) { + log_error("Invalid block size: %s\n", optarg); + return -1; + } + break; + + case 'X': + p->num_xfers = str2uint(optarg, 1, UINT_MAX, &ok); + if (!ok) { + log_error("Invalid stream transfer count: %s\n", optarg); + return -1; + } + break; + + case 'B': + p->stream_buffer_size = str2uint(optarg, 1, UINT_MAX, &ok); + if (!ok) { + log_error("Invalid stream buffer size: %s\n", optarg); + return -1; + } + break; + + case 'C': + p->stream_buffer_count = str2uint(optarg, 1, UINT_MAX, &ok); + if (!ok) { + log_error("Invalid stream buffer count: %s\n", optarg); + return -1; + } + break; + + case 'T': + p->timeout_ms = str2uint(optarg, 0, UINT_MAX, &ok); + if (!ok) { + log_error("Invalid stream timeout: %s\n", optarg); + return -1; + } + break; + } + } + + if (p->in_file == NULL && p->out_file == NULL) { + log_error("An input or output file is required.\n"); + return -1; + } + + if (p->frequency == 0) { + p->frequency = DEFAULT_FREQUENCY; + } + + if (p->samplerate == 0) { + p->samplerate = DEFAULT_SAMPLERATE; + } + + if (p->tx_repetitions == 0) { + p->tx_repetitions = DEFAULT_TX_REPETITIONS; + } + + if (p->rx_count == 0) { + p->rx_count = DEFAULT_RX_COUNT; + } + + if (p->block_size == 0) { + p->block_size = DEFAULT_BLOCK_SIZE; + } + + return 0; +} + +int main(int argc, char *argv[]) +{ + int status; + struct test_params p; + + status = handle_cmdline(argc, argv, &p); + + if (status == 0) { + status = test_run(&p); + } else if (status > 0) { + print_usage(argv[0]); + status = 0; + } + + if (p.in_file) { + fclose(p.in_file); + } + + if (p.out_file) { + fclose(p.out_file); + } + + return status; +} diff --git a/host/libraries/libbladeRF/tests/test_sync/src/test.c b/host/libraries/libbladeRF/tests/test_sync/src/test.c new file mode 100644 index 00000000..e2b0aec0 --- /dev/null +++ b/host/libraries/libbladeRF/tests/test_sync/src/test.c @@ -0,0 +1,293 @@ +/* + * This file is part of the bladeRF project: + * http://www.github.com/nuand/bladeRF + * + * Copyright (C) 2014 Nuand LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include +#include +#include +#include +#include + +#include + +#include "test.h" +#include "log.h" + +void test_init_params(struct test_params *p) +{ + memset(p, 0, sizeof(*p)); + + p->rx_count = DEFAULT_RX_COUNT; + p->block_size = DEFAULT_BLOCK_SIZE; + + p->num_xfers = DEFAULT_STREAM_XFERS; + p->stream_buffer_count = DEFAULT_STREAM_BUFFERS; + p->stream_buffer_size = DEFAULT_STREAM_SAMPLES; + p->timeout_ms = DEFAULT_STREAM_TIMEOUT; +} + +static int init_module(struct bladerf *dev, struct test_params *p, + bladerf_module m) +{ + const char *m_str = m == BLADERF_MODULE_RX ? "RX" : "TX"; + int status; + unsigned int samplerate_actual; + unsigned int frequency_actual; + + status = bladerf_set_sample_rate(dev, m, p->samplerate, &samplerate_actual); + + if (status != 0) { + log_error("Failed to set %s samplerate: %s\n", + m_str, bladerf_strerror(status)); + return status; + } + + status = bladerf_set_frequency(dev, m, p->frequency); + + if (status != 0) { + log_error("Failed to set %s frequency: %s\n", + m_str, bladerf_strerror(status)); + return status; + } + + status = bladerf_get_frequency(dev, m, &frequency_actual); + if (status != 0) { + log_error("Failed to read back %s frequency: %s\n", + m_str, bladerf_strerror(status)); + return status; + } + + log_debug("%s Frequency = %u, %s Samplerate = %u\n", + m_str, frequency_actual, m_str, samplerate_actual); + + return status; +} + +static struct bladerf * initialize_device(struct test_params *p) +{ + struct bladerf *dev; + int status = bladerf_open(&dev, p->device_str); + int fpga_loaded; + + if (status != 0) { + log_error("Failed to open device: %s\n", + bladerf_strerror(status)); + return NULL; + } + + fpga_loaded = bladerf_is_fpga_configured(dev); + if (fpga_loaded < 0) { + log_error("Failed to check FPGA state: %s\n", + bladerf_strerror(fpga_loaded)); + status = -1; + goto initialize_device_out; + } else if (fpga_loaded == 0) { + log_error("The device's FPGA is not loaded.\n"); + status = -1; + goto initialize_device_out; + } + + if (p->out_file) { + status = init_module(dev, p, BLADERF_MODULE_RX); + if (status != 0) { + goto initialize_device_out; + } + } + + if (p->in_file) { + status = init_module(dev, p, BLADERF_MODULE_TX); + } + +initialize_device_out: + if (status != 0) { + bladerf_close(dev); + dev = NULL; + } + + return dev; +} + +/* For the sake of simplicity, we'll just bounce back and forth between + * RX and TX when doing both. */ +int test_run(struct test_params *p) +{ + int status; + size_t n; + + struct bladerf *dev; + + uint8_t *buf_rx= NULL; + uint8_t *buf_tx= NULL; + + bool rx_done = true; + bool tx_done = true; + + unsigned int to_rx, to_tx; + + dev = initialize_device(p); + if (dev == NULL) { + return -1; + } + + if (p->out_file) { + buf_rx = (uint8_t*) calloc(p->block_size, 2 * sizeof(int16_t)); + if (buf_rx == NULL) { + status = -1; + perror("calloc"); + goto test_run_out; + } + + status = bladerf_sync_config(dev, + BLADERF_MODULE_RX, + BLADERF_FORMAT_SC16_Q11, + p->stream_buffer_count, + p->stream_buffer_size, + p->num_xfers, + p->timeout_ms + ); + + if (status != 0) { + log_error("Failed to intialize RX sync handle: %s\n", + bladerf_strerror(status)); + goto test_run_out; + } + + status = bladerf_enable_module(dev, BLADERF_MODULE_RX, true); + if (status != 0) { + log_error("Failed to enable RX module: %s\n", + bladerf_strerror(status)); + goto test_run_out; + } + + rx_done = false; + } + + if (p->in_file) { + buf_tx = (uint8_t*) calloc(p->block_size, 2 * sizeof(int16_t)); + if (buf_tx == NULL) { + status = -1; + perror("calloc"); + goto test_run_out; + } + + status = bladerf_sync_config(dev, + BLADERF_MODULE_TX, + BLADERF_FORMAT_SC16_Q11, + p->stream_buffer_count, + p->stream_buffer_size, + p->num_xfers, + p->timeout_ms + ); + + if (status != 0) { + log_error("Failed to initialize TX sync handle: %s\n", + bladerf_strerror(status)); + goto test_run_out; + } + + status = bladerf_enable_module(dev, BLADERF_MODULE_TX, true); + if (status != 0) { + log_error("Failed to enable RX module: %s\n", + bladerf_strerror(status)); + goto test_run_out; + } + + tx_done = false; + } + + while (!rx_done || !tx_done) { + if (!rx_done) { + to_rx = (unsigned int)(p->rx_count > p->block_size ? p->block_size : p->rx_count); + + status = bladerf_sync_rx(dev, buf_rx, to_rx, NULL, 0); + + if (status != 0) { + rx_done = true; + log_error("RX failed: %s\n", bladerf_strerror(status)); + } else { + log_verbose("RX'd %llu samples.\n", (unsigned long long)to_rx); + + n = fwrite(buf_rx, SAMPLE_SIZE_BYTES, to_rx, p->out_file); + if (n != to_rx) { + rx_done = true; + + status = ferror(p->out_file); + if (status != 0) { + log_error("Failed to write RX data to file: %s\n", + strerror(status)); + } + } else { + p->rx_count -= to_rx; + rx_done = p->rx_count == 0; + } + } + } + + if (!tx_done) { + to_tx = (unsigned int) fread(buf_tx, SAMPLE_SIZE_BYTES, p->block_size, p->in_file); + + if (to_tx != 0) { + status = bladerf_sync_tx(dev, buf_tx, to_tx, NULL, 0); + if (status != 0) { + tx_done = true; + log_error("TX failed: %s\n", bladerf_strerror(status)); + } else { + log_verbose("TX'd %llu samples.\n", + (unsigned long long)to_tx); + } + + } else { + if (--p->tx_repetitions != 0 && feof(p->in_file) && + !ferror(p->in_file)) { + fseek(p->in_file, 0, SEEK_SET); + log_debug("TX repetitions remaining: %u\n", + p->tx_repetitions); + } else { + tx_done = true; + } + } + } + } + +test_run_out: + log_verbose("Disablng RX.\n"); + status = bladerf_enable_module(dev, BLADERF_MODULE_RX, false); + if (status != 0) { + log_error("Failed to disable RX module: %s\n", + bladerf_strerror(status)); + } + + log_verbose("Disablng TX.\n"); + status = bladerf_enable_module(dev, BLADERF_MODULE_TX, false); + if (status != 0) { + log_error("Failed to disable RX module: %s\n", + bladerf_strerror(status)); + } + + free(buf_rx); + free(buf_tx); + + bladerf_close(dev); + + return status; +} diff --git a/host/libraries/libbladeRF/tests/test_sync/src/test.h b/host/libraries/libbladeRF/tests/test_sync/src/test.h new file mode 100644 index 00000000..3c965cae --- /dev/null +++ b/host/libraries/libbladeRF/tests/test_sync/src/test.h @@ -0,0 +1,63 @@ +/* + * This file is part of the bladeRF project: + * http://www.github.com/nuand/bladeRF + * + * Copyright (C) 2014 Nuand LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#define SAMPLE_SIZE_BYTES (2 * sizeof(int16_t)) + +/* Device config defaults */ +#define DEFAULT_SAMPLERATE 1000000 +#define DEFAULT_FREQUENCY 1000000000 + +/* Test defaults */ +#define DEFAULT_TX_REPETITIONS 1 +#define DEFAULT_RX_COUNT 10000000 +#define DEFAULT_BLOCK_SIZE 2048 + +/* Stream defaults */ +#define DEFAULT_STREAM_XFERS 16 +#define DEFAULT_STREAM_BUFFERS 32 +#define DEFAULT_STREAM_SAMPLES 8192 +#define DEFAULT_STREAM_TIMEOUT 1000 + +struct test_params { + const char *device_str; + unsigned int samplerate; + unsigned int frequency; + + FILE *in_file; + FILE *out_file; + unsigned int tx_repetitions; + uint64_t rx_count; + unsigned int block_size; + + /* Stream config */ + unsigned int num_xfers; + unsigned int stream_buffer_count; + unsigned int stream_buffer_size; /* Units of samples */ + unsigned int timeout_ms; +}; + +void test_init_params(struct test_params *p); + +int test_run(struct test_params *p); diff --git a/host/utilities/bladeRF-cli/CMakeLists.txt b/host/utilities/bladeRF-cli/CMakeLists.txt index 4198b806..164a523d 100644 --- a/host/utilities/bladeRF-cli/CMakeLists.txt +++ b/host/utilities/bladeRF-cli/CMakeLists.txt @@ -81,14 +81,13 @@ endif() if(MSVC) set(CLI_INCLUDE_DIRS ${CLI_INCLUDE_DIRS} ${BLADERF_HOST_COMMON_INCLUDE_DIRS}/windows - ${UTILITIES_COMMON_INC_DIR}/windows ${LIBPTHREADSWIN32_INCLUDE_DIRS} ) endif() if(APPLE) set(CLI_INCLUDE_DIRS ${CLI_INCLUDE_DIRS} - ${UTILITIES_COMMON_INC_DIR}/osx + ${BLADERF_HOST_COMMON_INCLUDE_DIRS}/osx ) endif() @@ -146,13 +145,13 @@ endif() if(MSVC) set(BLADERF_CLI_SOURCE ${BLADERF_CLI_SOURCE} ${BLADERF_HOST_COMMON_SOURCE_DIR}/windows/getopt_long.c - ${UTILITIES_COMMON_SRC}/windows/clock_gettime.c + ${BLADERF_HOST_COMMON_SOURCE_DIR}/windows/clock_gettime.c ) endif() if(APPLE) set(BLADERF_CLI_SOURCE ${BLADERF_CLI_SOURCE} - ${UTILITIES_COMMON_SRC}/osx/clock_gettime.c + ${BLADERF_HOST_COMMON_SOURCE_DIR}/osx/clock_gettime.c ) endif() diff --git a/host/utilities/bladeRF-cli/src/cmd/rx.c b/host/utilities/bladeRF-cli/src/cmd/rx.c index b4144596..effbdc12 100644 --- a/host/utilities/bladeRF-cli/src/cmd/rx.c +++ b/host/utilities/bladeRF-cli/src/cmd/rx.c @@ -334,8 +334,8 @@ static int rx_cmd_start(struct cli_state *s) /* Set our stream timeout */ pthread_mutex_lock(&s->rx->data_mgmt.lock); - status = bladerf_set_transfer_timeout(s->dev, BLADERF_MODULE_RX, - s->rx->data_mgmt.timeout_ms); + status = bladerf_set_stream_timeout(s->dev, BLADERF_MODULE_RX, + s->rx->data_mgmt.timeout_ms); pthread_mutex_unlock(&s->rx->data_mgmt.lock); if (status != 0) { diff --git a/host/utilities/bladeRF-cli/src/cmd/tx.c b/host/utilities/bladeRF-cli/src/cmd/tx.c index 5ea2cb74..b2e61098 100644 --- a/host/utilities/bladeRF-cli/src/cmd/tx.c +++ b/host/utilities/bladeRF-cli/src/cmd/tx.c @@ -445,8 +445,8 @@ static int tx_cmd_start(struct cli_state *s) /* Set our stream timeout */ - status = bladerf_set_transfer_timeout(s->dev, BLADERF_MODULE_TX, - s->tx->data_mgmt.timeout_ms); + status = bladerf_set_stream_timeout(s->dev, BLADERF_MODULE_TX, + s->tx->data_mgmt.timeout_ms); if (status != 0) { s->last_lib_error = status;