Processor implementation - riscv

Can you help me about the code below.
Is it writing 1 to the data memory or to the internal memory.
there are only 32 internal registers
The processor is 32 bit risc-v based
thanks in advance
#include "string.h"
#define DEBUG_IF_ADDR 0x00002010
void bubble_sort(int* arr, int len)
{
int sort_num;
do
{
sort_num = 0;
for(int i=0;i<len-1;i++)
{
if(*(arr+i) > *(arr+i+1))
{
int tmp = *(arr+i);
*(arr+i) = *(arr+i+1);
*(arr+i+1) = tmp;
sort_num++;
}
}
}
while(sort_num!=0);
}
int main()
{
int unsorted_arr[] = {195,14,176,103,54,32,128};
int sorted_arr[] = {14,32,54,103,128,176,195};
bubble_sort(unsorted_arr,7);
int *addr_ptr = DEBUG_IF_ADDR;
if(memcmp((char*) sorted_arr, (char*) unsorted_arr, 28) == 0)
{
//success
*addr_ptr = 1;
}
else
{
//failure
*addr_ptr = 0;
}
return 0;
}

Related

how to parallel or multithreading 2 function in C++?

I'm a beginner at parallel programming. I have 2 function in my code that I want run this 2 function in parallel (multiThread). can you help me?
func 1:
void Navigation::test_end(Graph::Node *node, dtPolyRef endRef, const float *endPos, int endIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(endRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,endIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
==========
func 2:
void Navigation::test_start(Graph::Node *node, dtPolyRef startRef, const float *startPos, int startIdPos)
{
int k=0;
//std::ofstream fout("v4.txt", std::ios_base::app | std::ios_base::out);
auto it2 = myMap2.equal_range(startRef);
for (auto it = it2.first; it != it2.second; ++it) {
int m_npolys = 0;
int n=0;
dtPolyRef m_polys[MAX_POLYS];
int j = it->second.size();
for(int i=0;i<j-1;i++){
if(it->second[i]>0){
m_polys[m_npolys++] =it->second[i];
// fout <<it->second[i]<<" ";
}
currentGraph.AddIntraEdge(node->idNode,startIdPos, node->edges[k].idPos, it->second[j-1], m_polys ,m_npolys); //n=m_npolys
k++;
}
}
now i want to run this 2 function in parallel mode in the main function :
test_start(sNode,startRef,startPos,startIdPos);
test_end(eNode,endRef,endPos, endIdPos);

C, convert hex number to decimal number without functions

i'm trying to convert hexadecimal number to decimal number. What i've come up so far is:
#include <unistd.h>
#include <stdio.h>
long convert(char *input, short int *status){
int length = 0;
while(input[length])
{
length++;
}
if(length = 0)
{
*status = 0;
return 0;
}
else
{
int index;
int converter;
int result = 0;
int lastNumber = length-1;
int currentNumber;
for(index = 0; index < length; index++){
if(index == 0)
{
converter = 1;
}
else if(index == 1)
{
converter = 16;
}
else{
converter *= 16;
}
if(input[lastNumber] < 45 || input[lastNumber] > 57)
{
*status = 0;
return 0;
}
else if(input[lastNumber] > 45 && input[lastNumber] < 48)
{
*status = 0;
return 0;
}
else{
if(input[lastNumber] == 45)
{
*status = -1;
return result *= -1;
}
currentNumber = input[lastNumber] - 48;
result += currentNumber * converter;
lastNumber--;
}
}
*status = -1;
return result;
}
}
int main(int argc, char **argv)
{
char *input=0;
short int status=0;
long rezult=0;
if(argc!=2)
{
status=0;
}
else
{
input=argv[1];
rezult=convert(input,&status);
}
printf("result: %ld\n", rezult);
printf("status: %d\n", status);
return 0;
}
Somehow i always get resoult 0. Ia am also not allowed to use any other outher functions (except printf). What could be wrong with my code above?
This:
if(dolzina = 0)
{
*status = 0;
return 0;
}
is not merely testing dolzina, it's first setting it to 0. This causes the else clause to run, but with dolzina equal to 0 which is not the expected outcome.
You should just use == to compare, of course.

libusb bulk transfer

I am trying to implement user space usb driver using libusb1.0.9. I have lpc2148 blueboard(ARM7) with me..This board is loaded with opensource USB stack/firmware by Mr. Bertrik Sikken. Now my user space driver is trying read write with board. I am getting garbage data.
I want to know about the flow of bulk tranfer.
For any transfer/transaction is there kernel device driver involved??
and do we need usb gadget device driver also??
I am not able to understand that where the data gets copied.
Important thing is that when I read/write interrupt gets generated and I can see correct data on LCD. Do I need to read/write USBRxData/USBTxData?
Please do the needfull.
I tried the below code for bulk transfer read and write..
int usb_read(struct libusb_device *dev,struct libusb_device_handle *hDevice)
{
char *data,*data1;
struct libusb_endpoint_descriptor *ep;
struct libusb_interface_descriptor *id;
int len=64,r,ret_alt,ret_clm,ret_rst,i;
struct libusb_device **list;
data = (char *)malloc(512); //allocation of buffers
data1 = (char *)malloc(512);
memset(data,'\0',512);
memset(data1,'\0',512);
if(hDevice==NULL)
{
printf("\nNO device found\n");
return 0;
}
int ret_open = libusb_open(dev,&hDevice);
if(ret_open!=0)
{
printf("Error in libusb_open\n");
libusb_free_device_list(list,1);
return -1;
}
char str_tx[512]="G"; //data to send to device
char str_rx[512]; //receive string
data = str_tx;
printf("data::%s\t,str::%s\n",data,str_tx);
//printf("%c\n",data);
ep = active_config(dev,hDevice);
printf("after ep\n");
//printf("alt_interface = %d\n",alt_interface);
ret_rst = libusb_reset_device(hDevice);
if(ret_rst < 0)
{
printf("Error in reset :: %d",ret_rst);
return -1;
}
printf("original data1 : %s\n",data1);
r = libusb_bulk_transfer(hDevice,0x08,str_tx,512,&len,0);
//write to device buffer from data
printf("Error number :: %d\n",r);
int le = ep->bEndpointAddress;
int ty = ep->bDescriptorType;
int y = ep->bmAttributes;
printf("y::%d\tatt:: %d\n",y,ep->bmAttributes);
if(r==-1)
printf("Error in io\n");
if(r==0)
{
printf("data returned :: %s\n",data);
printf("len= %d\n",len);
printf("Device Button Pressed!!!!\n");
}
else
{
printf("Error in bulk transfer\n");
return -1;
}
r = libusb_bulk_transfer(hDevice,0x82,data1,512,&len,0);
//read from device buffer to data1
//str_rx = data1;
//printf("End point address::%d\n",le);
//printf("End point desc.type::%d\n",ty);
if(r==-1)
printf("Error in io\n");
if(r==0)
{
printf("data1 returned::%s\n",data1); //received string in data1
printf("len= %d\n",len);
printf("Device Button Pressed!!!!\n");
}
else
{
printf("Error in bulk transfer\n");
return -1;
}
return 0;
}
Try the code given below and it should work on lpc2148.
I have tested this with a lpc2148 configured to receive an interrupt from USB after a write happens (from user-space) and RTC starts running.
Answering to your question whether it involves kernel driver in read/write or not, as far as I have studied, You have to detach the kernel driver and claim the interface using libusb APIs. Though I am not sure whether it can be done without detaching it or not.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include </usr/local/include/libusb-1.0/libusb.h>
#define BULK_EP_OUT 0x82
#define BULK_EP_IN 0x08
int interface_ref = 0;
int alt_interface,interface_number;
int print_configuration(struct libusb_device_handle *hDevice,struct libusb_config_descriptor *config)
{
char *data;
int index;
data = (char *)malloc(512);
memset(data,0,512);
index = config->iConfiguration;
libusb_get_string_descriptor_ascii(hDevice,index,data,512);
printf("\nInterface Descriptors: ");
printf("\n\tNumber of Interfaces : %d",config->bNumInterfaces);
printf("\n\tLength : %d",config->bLength);
printf("\n\tDesc_Type : %d",config->bDescriptorType);
printf("\n\tConfig_index : %d",config->iConfiguration);
printf("\n\tTotal length : %lu",config->wTotalLength);
printf("\n\tConfiguration Value : %d",config->bConfigurationValue);
printf("\n\tConfiguration Attributes : %d",config->bmAttributes);
printf("\n\tMaxPower(mA) : %d\n",config->MaxPower);
free(data);
data = NULL;
return 0;
}
struct libusb_endpoint_descriptor* active_config(struct libusb_device *dev,struct libusb_device_handle *handle)
{
struct libusb_device_handle *hDevice_req;
struct libusb_config_descriptor *config;
struct libusb_endpoint_descriptor *endpoint;
int altsetting_index,interface_index=0,ret_active;
int i,ret_print;
hDevice_req = handle;
ret_active = libusb_get_active_config_descriptor(dev,&config);
ret_print = print_configuration(hDevice_req,config);
for(interface_index=0;interface_index<config->bNumInterfaces;interface_index++)
{
const struct libusb_interface *iface = &config->interface[interface_index];
for(altsetting_index=0;altsetting_index<iface->num_altsetting;altsetting_index++)
{
const struct libusb_interface_descriptor *altsetting = &iface->altsetting[altsetting_index];
int endpoint_index;
for(endpoint_index=0;endpoint_index<altsetting->bNumEndpoints;endpoint_index++)
{
const struct libusb_endpoint_desriptor *ep = &altsetting->endpoint[endpoint_index];
endpoint = ep;
alt_interface = altsetting->bAlternateSetting;
interface_number = altsetting->bInterfaceNumber;
}
printf("\nEndPoint Descriptors: ");
printf("\n\tSize of EndPoint Descriptor : %d",endpoint->bLength);
printf("\n\tType of Descriptor : %d",endpoint->bDescriptorType);
printf("\n\tEndpoint Address : 0x0%x",endpoint->bEndpointAddress);
printf("\n\tMaximum Packet Size: %x",endpoint->wMaxPacketSize);
printf("\n\tAttributes applied to Endpoint: %d",endpoint->bmAttributes);
printf("\n\tInterval for Polling for data Tranfer : %d\n",endpoint->bInterval);
}
}
libusb_free_config_descriptor(NULL);
return endpoint;
}
int main(void)
{
int r = 1;
struct libusb_device **devs;
struct libusb_device_handle *handle = NULL, *hDevice_expected = NULL;
struct libusb_device *dev,*dev_expected;
struct libusb_device_descriptor desc;
struct libusb_endpoint_descriptor *epdesc;
struct libusb_interface_descriptor *intdesc;
ssize_t cnt;
int e = 0,config2;
int i = 0,index;
char str1[64], str2[64];
char found = 0;
// Init libusb
r = libusb_init(NULL);
if(r < 0)
{
printf("\nfailed to initialise libusb\n");
return 1;
}
else
printf("\nInit Successful!\n");
// Get a list os USB devices
cnt = libusb_get_device_list(NULL, &devs);
if (cnt < 0)
{
printf("\nThere are no USB devices on bus\n");
return -1;
}
printf("\nDevice Count : %d\n-------------------------------\n",cnt);
while ((dev = devs[i++]) != NULL)
{
r = libusb_get_device_descriptor(dev, &desc);
if (r < 0)
{
printf("failed to get device descriptor\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
break;
}
e = libusb_open(dev,&handle);
if (e < 0)
{
printf("error opening device\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
break;
}
printf("\nDevice Descriptors: ");
printf("\n\tVendor ID : %x",desc.idVendor);
printf("\n\tProduct ID : %x",desc.idProduct);
printf("\n\tSerial Number : %x",desc.iSerialNumber);
printf("\n\tSize of Device Descriptor : %d",desc.bLength);
printf("\n\tType of Descriptor : %d",desc.bDescriptorType);
printf("\n\tUSB Specification Release Number : %d",desc.bcdUSB);
printf("\n\tDevice Release Number : %d",desc.bcdDevice);
printf("\n\tDevice Class : %d",desc.bDeviceClass);
printf("\n\tDevice Sub-Class : %d",desc.bDeviceSubClass);
printf("\n\tDevice Protocol : %d",desc.bDeviceProtocol);
printf("\n\tMax. Packet Size : %d",desc.bMaxPacketSize0);
printf("\n\tNo. of Configuraions : %d\n",desc.bNumConfigurations);
e = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, (unsigned char*) str1, sizeof(str1));
if (e < 0)
{
libusb_free_device_list(devs,1);
libusb_close(handle);
break;
}
printf("\nManufactured : %s",str1);
e = libusb_get_string_descriptor_ascii(handle, desc.iProduct, (unsigned char*) str2, sizeof(str2));
if(e < 0)
{
libusb_free_device_list(devs,1);
libusb_close(handle);
break;
}
printf("\nProduct : %s",str2);
printf("\n----------------------------------------");
if(desc.idVendor == 0xffff && desc.idProduct == 0x4)
{
found = 1;
break;
}
}//end of while
if(found == 0)
{
printf("\nDevice NOT found\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
return 1;
}
else
{
printf("\nDevice found");
dev_expected = dev;
hDevice_expected = handle;
}
e = libusb_get_configuration(handle,&config2);
if(e!=0)
{
printf("\n***Error in libusb_get_configuration\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
return -1;
}
printf("\nConfigured value : %d",config2);
if(config2 != 1)
{
libusb_set_configuration(handle, 1);
if(e!=0)
{
printf("Error in libusb_set_configuration\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
return -1;
}
else
printf("\nDevice is in configured state!");
}
libusb_free_device_list(devs, 1);
if(libusb_kernel_driver_active(handle, 0) == 1)
{
printf("\nKernel Driver Active");
if(libusb_detach_kernel_driver(handle, 0) == 0)
printf("\nKernel Driver Detached!");
else
{
printf("\nCouldn't detach kernel driver!\n");
libusb_free_device_list(devs,1);
libusb_close(handle);
return -1;
}
}
e = libusb_claim_interface(handle, 0);
if(e < 0)
{
printf("\nCannot Claim Interface");
libusb_free_device_list(devs,1);
libusb_close(handle);
return -1;
}
else
printf("\nClaimed Interface\n");
active_config(dev_expected,hDevice_expected);
// Communicate
char *my_string, *my_string1;
int transferred = 0;
int received = 0;
int length = 0;
my_string = (char *)malloc(nbytes + 1);
my_string1 = (char *)malloc(nbytes + 1);
memset(my_string,'\0',64);
memset(my_string1,'\0',64);
strcpy(my_string,"prasad divesd");
length = strlen(my_string);
printf("\nTo be sent : %s",my_string);
e = libusb_bulk_transfer(handle,BULK_EP_IN,my_string,length,&transferred,0);
if(e == 0 && transferred == length)
{
printf("\nWrite successful!");
printf("\nSent %d bytes with string: %s\n", transferred, my_string);
}
else
printf("\nError in write! e = %d and transferred = %d\n",e,transferred);
sleep(3);
i = 0;
for(i = 0; i < length; i++)
{
e = libusb_bulk_transfer(handle,BULK_EP_OUT,my_string1,64,&received,0); //64 : Max Packet Lenght
if(e == 0)
{
printf("\nReceived: ");
printf("%c",my_string1[i]); //will read a string from lcp2148
sleep(1);
}
else
{
printf("\nError in read! e = %d and received = %d\n",e,received);
return -1;
}
}
e = libusb_release_interface(handle, 0);
libusb_close(handle);
libusb_exit(NULL);
printf("\n");
return 0;
}
To handle kernal detaching.
if(libusb_kernel_driver_active(dev_handle, 0) == 1) //find out if kernel driver is attached
{
cout << "Kernel Driver Active" << endl;
if(libusb_detach_kernel_driver(dev_handle, 0) == 0) //detach it
{
cout << "Kernel Driver Detached!" << endl;
}
}

boost::shared_array assignment crashes application(VC++ 2010)

Modified the below circular queue code for my app.
This queue can hold 32 elements max and I have declared the elements as a structure array inside the class. For adding an element to the queue you have to call CreateElement() functions, which checks for a free element and returns an index. When I reuse an element after processing the following line in the CreateElement functions crashes
boost::shared_array<char> tData(new char[bufferSize]);
m_QueueStructure[queueElems].data = tData;
As per documentation, the assignment operator is supposed to destroy the earlier object and assign the new one. Why is it crashing? Can someone tell me where am I screwing?
#include "boost/thread/condition.hpp"
#include "boost/smart_ptr/shared_array.hpp"
#include <queue>
#define MAX_QUEUE_ELEMENTS 32
typedef struct queue_elem
{
bool inUse;
int index;
int packetType;
unsigned long compressedLength;
unsigned long uncompressedLength;
boost::shared_array<char> data;
}Data;
class CQueue
{
private:
int m_CurrentElementsOfQueue;
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
Data m_QueueStructure[MAX_QUEUE_ELEMENTS];
public:
CQueue()
{
m_CurrentElementsOfQueue = 0;
for(int i = 0; i < MAX_QUEUE_ELEMENTS; i++)
{
m_QueueStructure[i].inUse = false;
m_QueueStructure[i].index = i;
}
}
~CQueue()
{
for(int i = 0; i < m_CurrentElementsOfQueue; i++)
{
int index = wait_and_pop();
Data& popped_value = m_QueueStructure[index];
popped_value.inUse = false;
}
m_CurrentElementsOfQueue = 0;
}
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
int wait_and_pop()
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
Data& popped_value=the_queue.front();
the_queue.pop();
return popped_value.index;
}
int CreateElement(int bufferSize, unsigned long _compressedLength,
unsigned long _uncompressedLength, int _packetType) /* Send data length for this function */
{
int queueElems = 0;
if(m_CurrentElementsOfQueue == 32)
{
CCommonException ex(QERROR, QUEUE_FULL, "Circular Buffer Queue is full");
throw ex;
}
for(queueElems = 0; queueElems < MAX_QUEUE_ELEMENTS; queueElems++)
{
if(m_QueueStructure[queueElems].inUse == false)
break;
}
boost::shared_array<char> tData(new char[bufferSize]);
m_QueueStructure[queueElems].data = tData;
m_QueueStructure[queueElems].inUse = true;
m_QueueStructure[queueElems].compressedLength = _compressedLength;
m_QueueStructure[queueElems].uncompressedLength = _uncompressedLength;
m_QueueStructure[queueElems].packetType = _packetType;
m_CurrentElementsOfQueue++;
return queueElems;
}
Data& GetElement(int index)
{
Data& DataElement = m_QueueStructure[index];
return DataElement;
}
void ClearElementIndex(Data& delValue)
{
m_CurrentElementsOfQueue--;
delValue.inUse = false;
}
};
for(queueElems = 0; queueElems < MAX_QUEUE_ELEMENTS; queueElems++) after looping queueElems has value 32 but in your m_QueueStructure only 32 elements so you trying to access m_QueueStructure[queueElems].data to 33rd element. That the problem.
EDIT: try use m_QueueStructure[queueElems].data.reset(new char[bufferSize]);
Solved the problem. Two changes I did. In the wait_and_pop function, I was returning an index rather than a Data&. When I returned Data&, that solved the assignment problem. Another crash was happening due to a memset of a shared_array.get(). Lesson learnt, never memset a shared_array or a shared_ptr.

VC++ threads deadlocked

The following program goes into a deadlock. Can anyone please tell me why?
#include<cstdlib>
#include<windows.h>
#include<iostream>
using namespace std;
class CircularQueue
{
public:
CircularQueue(int s)
{
size = s;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
CircularQueue(void)
{
size = default_size;
array = (int*)malloc(sizeof(int) * size);
head = tail = -1;
InitializeCriticalSection(&critical_section);
}
void initialize(int s)
{
EnterCriticalSection(&critical_section);
size = s;
array = (int*)realloc(array, sizeof(int) * size);
head = tail = -1;
LeaveCriticalSection(&critical_section);
}
void enqueue(int n)
{
EnterCriticalSection(&critical_section);
tail = (tail + 1) % size;
array[tail] = n;
LeaveCriticalSection(&critical_section);
}
int dequeue(void)
{
EnterCriticalSection(&critical_section);
head = (head + 1) % size;
return array[head];
LeaveCriticalSection(&critical_section);
}
private:
int *array;
int size;
int head, tail;
CRITICAL_SECTION critical_section;
bool initialized;
static const int default_size = 10;
};
DWORD WINAPI thread1(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(2);
cout << cqueue->dequeue() << endl;
return 0;
}
DWORD WINAPI thread2(LPVOID param)
{
CircularQueue* cqueue = (CircularQueue*)param;
cqueue->enqueue(3);
cout << cqueue->dequeue() << endl;
return 0;
}
int main(void)
{
HANDLE thread1_handle;
HANDLE thread2_handle;
CircularQueue cqueue;
HANDLE array[2];
thread1_handle = CreateThread(NULL, 0, thread1, &cqueue, 0, NULL);
thread2_handle = CreateThread(NULL, 0, thread2, &cqueue, 0, NULL);
array[0] = thread1_handle;
array[1] = thread2_handle;
WaitForMultipleObjects(1, array, TRUE, INFINITE);
CloseHandle(thread1_handle);
CloseHandle(thread2_handle);
printf("end\n");
return 0;
}
In dequeue(), you have a return statement before the LeaveCriticalSection() call. If you had compiler warnings turned up higher, it would probably have told you about this!

Resources