Opencl clWaitEvent() after clFinish() cause memory leak - memory-leaks

I have some problem of memory leak due to the function clWaitEvent().
I use clWaitEvent() for compute the execution time of my kernel :
ciErrNum = clEnqueueNDRangeKernel(this->commandQueue, this-> kernel_calcHash, 1, NULL, &globalWorkSize, &localWorkSize, 0, NULL, &prof_event);
clFinish(this->commandQueue);
ciErrNum = clWaitForEvents(1, &prof_event);
ciErrNum |= clGetEventProfilingInfo(prof_event, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &ev_start_time, NULL);
ciErrNum |= clGetEventProfilingInfo(prof_event, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &ev_end_time, NULL);
ciErrNum |= clReleaseEvent(prof_event);
oclCheckError(ciErrNum, CL_SUCCESS);
with valgrind, i find some memory leak which its remove if I comment the clWaitForEvents() function.
I release the event after this method, so I don't know why, this happen. Anybody have an idea ?

Try this afer clEnqueueNDRangeKernel
clFinish(CommandQueue);

Related

Kernel API to get Physical RAM Offset

I'm writing a device driver (for Linux kernel 2.6.x) that interacts directly with physical RAM using physical addresses. For my device's memory layout (according to the output of cat /proc/iomem), System RAM begins at physical address 0x80000000; however, this code may run on other devices with different memory layouts so I don't want to hard-code that offset.
Is there a function, macro, or constant which I can use from within my device driver that gives me the physical address of the first byte of System RAM?
Is there a function, macro, or constant which I can use from within my device driver that gives me the physical address of the first byte of System RAM?
It doesn't matter, because you're asking an XY question.
You should not be looking for or trying to use the "first byte of System RAM" in a device driver.
The driver only needs knowledge of the address (and length) of its register block (that is what this "memory" is for, isn't it?).
In 2.6 kernels (i.e. before Device Tree), this information was typically passed to drivers through struct resource and struct platform_device definitions in a board_devices.c file.
The IORESOURCE_MEM property in the struct resource is the mechanism to pass the device's memory block start and end addresses to the device driver.
The start address is typically hardcoded, and taken straight from the SoC datasheet or the board's memory map.
If you change the SoC, then you need new board file(s).
As an example, here's code from arch/arm/mach-at91/at91rm9200_devices.c to configure and setup the MMC devices for a eval board (AT91RM9200_BASE_MCI is the physical memory address of this device's register block):
#if defined(CONFIG_MMC_AT91) || defined(CONFIG_MMC_AT91_MODULE)
static u64 mmc_dmamask = DMA_BIT_MASK(32);
static struct at91_mmc_data mmc_data;
static struct resource mmc_resources[] = {
[0] = {
.start = AT91RM9200_BASE_MCI,
.end = AT91RM9200_BASE_MCI + SZ_16K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = AT91RM9200_ID_MCI,
.end = AT91RM9200_ID_MCI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device at91rm9200_mmc_device = {
.name = "at91_mci",
.id = -1,
.dev = {
.dma_mask = &mmc_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(32),
.platform_data = &mmc_data,
},
.resource = mmc_resources,
.num_resources = ARRAY_SIZE(mmc_resources),
};
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data)
{
if (!data)
return;
/* input/irq */
if (data->det_pin) {
at91_set_gpio_input(data->det_pin, 1);
at91_set_deglitch(data->det_pin, 1);
}
if (data->wp_pin)
at91_set_gpio_input(data->wp_pin, 1);
if (data->vcc_pin)
at91_set_gpio_output(data->vcc_pin, 0);
/* CLK */
at91_set_A_periph(AT91_PIN_PA27, 0);
if (data->slot_b) {
/* CMD */
at91_set_B_periph(AT91_PIN_PA8, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_B_periph(AT91_PIN_PA9, 1);
if (data->wire4) {
at91_set_B_periph(AT91_PIN_PA10, 1);
at91_set_B_periph(AT91_PIN_PA11, 1);
at91_set_B_periph(AT91_PIN_PA12, 1);
}
} else {
/* CMD */
at91_set_A_periph(AT91_PIN_PA28, 1);
/* DAT0, maybe DAT1..DAT3 */
at91_set_A_periph(AT91_PIN_PA29, 1);
if (data->wire4) {
at91_set_B_periph(AT91_PIN_PB3, 1);
at91_set_B_periph(AT91_PIN_PB4, 1);
at91_set_B_periph(AT91_PIN_PB5, 1);
}
}
mmc_data = *data;
platform_device_register(&at91rm9200_mmc_device);
}
#else
void __init at91_add_device_mmc(short mmc_id, struct at91_mmc_data *data) {}
#endif
ADDENDUM
i'm still not seeing how this is an xy question.
I consider it an XY question because:
You conflate "System RAM" with physical memory address space.
"RAM" would be actual (readable/writable) memory that exists in the address space.
"System memory" is the RAM that the Linux kernel manages (refer to your previous question).
Peripherals can have registers and/or device memory in (physical) memory address space, but this should not be called "System RAM".
You have not provided any background on how or why your driver "interacts directly with physical RAM using physical addresses." in a manner that is different from other Linux drivers.
You presume that a certain function is the solution for your driver, but you don't know the name of that function. That's a prototype for an XY question.
can't i call a function like get_platform_device (which i just made up) to get the struct platform_device and then find the struct resource that represents System RAM?
The device driver would call platform_get_resource() (in its probe function) to retrieve its struct resource that was defined in the board file.
To continue the example started above, the driver's probe routune has:
static int __init at91_mci_probe(struct platform_device *pdev)
{
struct mmc_host *mmc;
struct at91mci_host *host;
struct resource *res;
int ret;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENXIO;
if (!request_mem_region(res->start, resource_size(res), DRIVER_NAME))
return -EBUSY;
...
/*
* Map I/O region
*/
host->baseaddr = ioremap(res->start, resource_size(res));
if (!host->baseaddr) {
ret = -ENOMEM;
goto fail1;
}
that would allow me to write code that can always access the nth byte of RAM, without assumptions of how RAM is arranged in relation to other parts of memory.
That reads like a security hole or a potential bug.
I challenge you to to find a driver in the mainline Linux kernel that uses the "physical address of the first byte of System RAM".
Your title is "Kernel API to get Physical RAM Offset".
The API you are looking would seem to be the struct resource.
What you want to do seems to fly in the face of Linux kernel conventions. For the integrity and security of the system, drivers do not try to access any/every part of memory.
The driver will request and can be given exclusive access to the address space of its registers and/or device memory.
All RAM under kernel management is only accessed through well-defined conventions, such as buffer addresses for copy_to_user() or the DMA API.
A device driver simply does not have free reign to access any part of memory it chooses.
Once a driver is started by the kernel, there is absolutely no way it can disregard "assumptions of how RAM is arranged".
RAM memory mapping is based identical to each SOC or processor. Vendor usually provide their memory mapping related documents to the user.
Probably you need to refer your processor datasheet related document.
As you said memory is hard-coded. In most cases memory mapping is hard-coded over device-tree or in SDRAM driver itself.
Maybe you could look into memblock struct and memblock_start_of_DRAM().
/sys/kernel/debug/memblock/memory represent memory banks.
0: 0x0000000940000000..0x0000000957bb5fff
RAM bank 0: 0x0000000940000000 0x0000000017bb6000
1: 0x0000000980000000..0x00000009ffffffff
RAM bank 1: 0x0000000980000000 0x0000000080000000

How to implement select function call

I have created a virtual node "/dev/abc" and there are 2 applications a.c and b.c
a.c will write data in to the node,
b.c will read data from the node
In b.c I am opening the node and using select function
to verify whether data is available in the node.
I am using below code for checking the data.
But with out writing data from a.c, b.c is reading the
data.
Code:
fd_set read set;
int result;
fd=open ("/dev/abc", O_RDWR);
FD_SET (fd, &readset);
result=select (fd+1,&readset, NULL, NULL, NULL);
if(result> 0)
{
if (FD_ISSET (fd, &readset))
{
read (fd, buffer, 100);
}
}
Please suggest me how to use select function call for
the above scenario.
Regards,
Ajith Kumsi
You should call FD_ZERO() before FD_SET() to clear your readset. That's probably the reason. There is a clear example near the bottom of select man page and you can just follow it.

memory leaks with function

___Below program should crash when MyClass::processing is called after "delete p" and "p = NULL" but it crashes when "MyClass::a" is tried to access. Why so???
#include <iostream>
using namespace std;
class MyClass
{
public:
int a;
void processing()
{
cout<<"Processing"<<endl;
}
};
int main(void)
{
MyClass* p(new MyClass);
MyClass* q = p;
p->a = 10;
cout<<"p:: "<<p<<" q:: "<<q<<endl;
cout<<"p->a"<<p->a<<"q->a"<<q->a<<endl;
delete p;
p->processing(); // Watch out! p is now dangling!
cout<<"\n\nAfter Deletion::"<<endl;
cout<<"p:: "<<p<<" q:: "<<q<<endl;
cout<<"p->a"<<p->a<<"q->a"<<q->a<<endl;
p = NULL; // p is no longer dangling
cout<<"\n\nAfter Assigning null"<<endl;
p->processing(); // Watch out! p is now dangling!
q->processing(); // Ouch! q is still dangling!
cout<<"p:: "<<p<<" q:: "<<q<<endl;
}
Calling a method after you've deleted the instance is undefined behaviour. Anything could happen.
A sample of possible behaviours:
You get "lucky": free just released the memory but didn't invalidate it. The instance is partially intact, and the call succeeds by accident.
free overwrites the memory with garbage (or sentinel values), causing you to jump to some crazy address and segfault.
free deallocates the whole block and you segfault on trying to access *p.
Some other thread puts the address of system in the now-unused block of memory. Your stack happens to contain a pointer to "rm -rf /". Your hard-drive is erased, hilarity ensues.
Never, ever, ever rely on undefined behaviour.

What is the valid address space for a user process? (OS X and Linux)

The mmap system call documentation says that the function will fail if:
MAP_FIXED was specified and the addr
argument was not page aligned, or part
of the desired address space resides
out of the valid address space for a
user process.
I can't find documentation anywhere saying what would be a valid address to map. (I'm interested in doing this on OS X and linux, ideally the same address would be valid for both...).
Linux kernel reserves part of virtual address space for itself to where userspace have (almost) no access and can't map anything. You're looking for what's called "userspace/kernelspace split".
On i386 arch default is 3G/1G one -- userspace gets lower 3 GB of virtual address space, kernel gets upper 1 GB, additionally there are 2G/2G and 1G/3G splits:
config PAGE_OFFSET
hex
default 0xB0000000 if VMSPLIT_3G_OPT
default 0x80000000 if VMSPLIT_2G
default 0x78000000 if VMSPLIT_2G_OPT
default 0x40000000 if VMSPLIT_1G
default 0xC0000000
depends on X86_32
On x86_64, userspace lives in lower half of (currently) 48-bit of virtual address space:
/*
* User space process size. 47bits minus one guard page.
*/
#define TASK_SIZE_MAX ((1UL << 47) - PAGE_SIZE)
This varies based on a number of factors, many of which aren't under your control. As adobriyan mentioned, depending on the OS, you have various fixed upper limits, beyond which kernel code and data lies. Usually this upper limit is at least 2GB on 32-bit OSes; some OSes provide additional address space. 64-bit OSes generally provide an upper limit controlled by the number of virtual address bits supported by your CPU (usually at least 40 bits worth of address space). However there are yet other factors beyond your control:
On recent version of linux, mmap mappings below the address configured in /proc/sys/vm/mmap_min_addr will be denied.
You cannot make mappings which overlap with any existing mappings. Since the dynamic linker is free to map anywhere that does not overlap with your executable's fixed sections, this means potentially any address may be denied.
The kernel may inject other additional mappings, such as the system call gate.
malloc may perform mmaps on its own, which are placed in a somewhat arbitrary location
As such, there is no way to absolutely guarentee that MAP_FIXED will succeed, and so it should normally be avoided.
The only place I've seen where MAP_FIXED is necessary is in the wine startup code, which reserves (using MAP_FIXED) all addresses above 2G, in order to avoid confusing windows code which assumes no mappings will ever show up with a negative address. This is, of course, a highly specialized use of the flag.
If you're trying to do this in order to avoid having to deal with offsets in shared memory, one option would be to wrap pointers in a class to automatically handle offsets:
template<typename T>
class offset_pointer {
private:
ptrdiff_t offset;
public:
typedef T value_type, *ptr_type;
typedef const T const_type, *const_ptr_type;
offset_ptr(T *p) { set(p); }
offset_ptr() { set(NULL); }
void set(T *p) {
if (p == NULL)
offset = 1;
else
offset = (char *)p - (char *)this;
}
T *get() {
if (offset == 1) return NULL;
return (T*)( (char *)this + offset );
}
const T *get() const { return const_cast<offset_pointer>(this)->get(); }
T &operator*() { return *get(); }
const T &operator*() const { return *get(); }
T *operator->() { return get(); }
const T *operator->() const { return get(); }
operator T*() { return get(); }
operator const T*() const { return get(); }
offset_pointer operator=(T *p) { set(p); return *this; }
offset_pointer operator=(const offset_pointer &other) {
offset = other.offset;
return *this;
}
};
Note: This is untested code, but should give you the basic idea.

Managed C++ Memory leak

I am getting a memory leak whenver a new RPC thread in a DCOM server (c++ DCOM server) invokes the following managed C++ method
void CToolDataClient::SetLotManagerActive(bool bLotManagerActive)
{
if( m_toolDataManager != nullptr)
{
m_toolDataManager->LotActive = bLotManagerActive;
}
}
I get the managed C++ object pointer using the floowing code
typedef bool (*FPTR_CREATEINTERFACE)(CToolDataInterface ** ppInterface);
FPTR_CREATEINTERFACE fnptr = (FPTR_CREATEINTERFACE)GetProcAddress(hModule,(LPTSTR)"CreateInstance");
if ( NULL != fnptr )
{
CICELogger::Instance()->LogMessage("CToolDataManager::CToolDataManager", Information,
"Created instance of DataManagerBridge");
fnptr(&m_pToolDataInterface);
}
This is how I invoke the managed call in the DCOME server C++ portion
void CToolDataManager::SetLotManagerActive(bool bLotManagerActive)
{
if(m_pToolDataInterface != NULL)
{
m_pToolDataInterface->SetLotManagerActive(bLotManagerActive);
}
}
The callstack given below indicate the location of the memory leak . Is there any ways to solve this memory leak? Please help me
ntdll!RtlDebugAllocateHeap+000000E1
ntdll!RtlAllocateHeapSlowly+00000044
ntdll!RtlAllocateHeap+00000E64
mscorwks!EEHeapAlloc+00000142
mscorwks!EEHeapAllocInProcessHeap+00000052
**mscorwks!operator new[]+00000025
mscorwks!SetupThread+00000238
mscorwks!IJWNOADThunk::FindThunkTarget+00000019
mscorwks!IJWNOADThunkJumpTargetHelper+0000000B
mscorwks!IJWNOADThunkJumpTarget+00000048
ICEScheduler!CToolDataManager::SetLotManagerActive+00000025** (e:\projects\ice\ice_dev\trunk\source\application source\iceschedulersystem\icescheduler\tooldatamanager.cpp, 250)
ICEScheduler!SetLotManagerActive+00000014 (e:\projects\ice\ice_dev\trunk\source\application source\iceschedulersystem\icescheduler\schddllapi.cpp, 589)
ICELotControl!CLotDetailsHandler::SetLotManagerStatus+0000006C (e:\projects\ice\ice_dev\source\application source\icelotsystem\icelotcontrol\lotdetailshandler.cpp, 1823)
ICELotControl!CLotManager::StartJob+00000266 (e:\projects\ice\ice_dev\source\application source\icelotsystem\icelotcontrol\lotmanager.cpp, 205)
RPCRT4!Invoke+00000030
RPCRT4!NdrStubCall2+00000297
RPCRT4!CStdStubBuffer_Invoke+0000003F
OLEAUT32!CUnivStubWrapper::Invoke+000000C5
ole32!SyncStubInvoke+00000033
ole32!StubInvoke+000000A7
ole32!CCtxComChnl::ContextInvoke+000000E3
ole32!MTAInvoke+0000001A
ole32!AppInvoke+0000009C
ole32!ComInvokeWithLockAndIPID+000002E0
ole32!ThreadInvoke+000001CD
RPCRT4!DispatchToStubInC+00000038
RPCRT4!RPC_INTERFACE::DispatchToStubWorker+00000113
RPCRT4!RPC_INTERFACE::DispatchToStub+00000084
RPCRT4!RPC_INTERFACE::DispatchToStubWithObject+000000C0
RPCRT4!LRPC_SCALL::DealWithRequestMessage+000002CD
RPCRT4!LRPC_ADDRESS::DealWithLRPCRequest+0000016D
RPCRT4!LRPC_ADDRESS::ReceiveLotsaCalls+0000028F
First, is LotActive a member variable/field (pure data) or a property?
I think that it is a property, and before it can be set, the JIT has to compile the code for the setter. In desktop .NET, native code produced by the JIT compilation process is not garbage collected, instead it exists for the lifetime of the AppDomain, so it could look like a leak.
Can you check whether each call to this function leaks another object, or the leak just occurs once?

Resources