/*++
"This software program is available to you under a choice of one of two
licenses.  You may choose to be licensed under either the GNU General Public
License (GPL) Version 2, June 1991, available at
http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License,
the text of which follows:

"Recipient" has requested a license and Intel Corporation ("Intel") is willing
to grant a license for the software entitled InfiniBand(tm) System Software
(the "Software") being provided by Intel Corporation.

The following definitions apply to this License:

"Licensed Patents" means patent claims licensable by Intel Corporation which
are necessarily infringed by the use or sale of the Software alone or when
combined with the operating system referred to below.

"Recipient" means the party to whom Intel delivers this Software.
"Licensee" means Recipient and those third parties that receive a license to
any operating system available under the GNU Public License version 2.0 or
later.

Copyright (c) 1996-2003 Intel Corporation. All rights reserved.

The license is provided to Recipient and Recipient's Licensees under the
following terms.

Redistribution and use in source and binary forms of the Software, with or
without modification, are permitted provided that the following conditions are
met:
Redistributions of source code of the Software may retain the above copyright
notice, this list of conditions and the following disclaimer.

Redistributions in binary form of the Software may reproduce the above
copyright notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

Neither the name of Intel Corporation nor the names of its contributors shall
be used to endorse or promote products derived from this Software without
specific prior written permission.

Intel hereby grants Recipient and Licensees a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell, offer
to sell, import and otherwise transfer the Software, if any, in source code
and object code form. This license shall include changes to the Software that
are error corrections or other minor changes to the Software that do not add
functionality or features when the Software is incorporated in any version of
a operating system that has been distributed under the GNU General Public
License 2.0 or later.  This patent license shall apply to the combination of
the Software and any operating system licensed under the GNU Public License
version 2.0 or later if, at the time Intel provides the Software to Recipient,
such addition of the Software to the then publicly available versions of such
operating system available under the GNU Public License version 2.0 or later
(whether in gold, beta or alpha form) causes such combination to be covered by
the Licensed Patents. The patent license shall not apply to any other
combinations which include the Software. No hardware per se is licensed
hereunder.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
--*/

/*
 * Abstract:
 *	Implements Memory allocatation, deallocation, Memory Locking
 *	Allocate Contiguous memory for drivers in Linux Kernel Mode.
 *
 * Environment
 *	Linux Kernel Mode
 *
 * $Revision: 1.1 $
 */

#include <complib/cl_memory.h>
#include <complib/cl_debug.h>
#include <complib/cl_math.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/highmem.h>
#include "cl_memtrack.h"
#include <linux/proc_fs.h>
#include <complib/cl_math.h>

/* Internal Definitions  */
#define		KMALLOC_THRESHOLD		(131072)
#define		SIZE_PER_ENTRY			(80)
#define		MAX_MEMINFO_PROCSIZE	(4096)

static char *p_meminfo_buf = NULL;
uint32_t meminfo_size = 0;
struct proc_dir_entry *p_proc_meminfo = NULL;

void *
__cl_malloc_priv(IN const size_t bytes)
{
	CL_ASSERT(bytes);

	if (bytes <= KMALLOC_THRESHOLD)
		return (kmalloc(bytes, GFP_ATOMIC));

	return (vmalloc(bytes));
}

void
__cl_free_priv(IN void *const p_memory)
{
	CL_ASSERT(p_memory != NULL);

#ifndef CONFIG_PPC
	if (((uintn_t) p_memory >= VMALLOC_START)
	    && ((uintn_t) p_memory < VMALLOC_END))
#else
	/* Warning, this is a workaround for Linux PPC, because
	 * the kernel does not export the VMALLOC_END (ioremap_bot)
	 * symbol. Other option is to have a kernel patch to
	 * export this symbol */
	if (((uintn_t) p_memory >= VMALLOC_START))
#endif
	{
		vfree(p_memory);
	} else {
		kfree(p_memory);
	}
}

void
cl_memset(IN void *const p_memory, IN const uint8_t fill, IN const size_t count)
{
	memset(p_memory, fill, count);
}

void *
cl_memcpy(IN void *const p_dest,
	  IN const void *const p_src, IN const size_t count)
{
	return (memcpy(p_dest, p_src, count));
}

int32_t
cl_memcmp(IN const void *const p_mem,
	  IN const void *const p_ref, IN const size_t count)
{
	return (memcmp(p_mem, p_ref, count));
}

uint64_t
cl_get_physaddr(IN void *vaddr)
{
	return ((uint64_t) __pa(vaddr));
}

void *
allocate_meminfo(void)
{
	uint32_t entry_count;

	if (gp_mem_tracker) {
		cl_spinlock_acquire(&gp_mem_tracker->lock);
		entry_count = cl_qmap_count(&gp_mem_tracker->alloc_map);
		cl_spinlock_release(&gp_mem_tracker->lock);
		entry_count += ROUNDUP((entry_count * SIZE_PER_ENTRY),
				       MAX_MEMINFO_PROCSIZE);
	} else {
		entry_count = MAX_MEMINFO_PROCSIZE;
	}

	/*
	 * First Time.... Set the size
	 */
	if (!meminfo_size) {
		meminfo_size = MAX(MAX_MEMINFO_PROCSIZE, entry_count);
	}

	/*
	 * Check if current buffer size if good to go
	 */
	if (meminfo_size < entry_count) {
		if (p_meminfo_buf)
			cl_free(p_meminfo_buf);
		p_meminfo_buf = NULL;
		meminfo_size = entry_count;
	}

	if (!p_meminfo_buf)
		p_meminfo_buf = cl_malloc(meminfo_size);

	/*
	 * Trap allocate failures
	 */
	if (!p_meminfo_buf) {
		meminfo_size = 0;
		cl_msg_out("Cannot allocate memory for memory tracking\n");
	}

	return (p_meminfo_buf);
}

uint32_t
print_mem_entry(cl_malloc_hdr_t * p_hdr, char *p_buf)
{
	uint32_t size = 0;
	char *slash_ptr = NULL;

	slash_ptr = strrchr(p_hdr->file_name, '/');
	if (!slash_ptr)
		slash_ptr = p_hdr->file_name;
	else
		slash_ptr++;
	size = sprintf(p_buf, "%-p %-15.15s %-4.4d\n",
		       p_hdr->p_mem, slash_ptr, p_hdr->line_num);

	return size;
}

uint32_t
generate_meminfo_data(char **data)
{
	char *buf;
	uint32_t len = 0, size = 0;
	cl_map_item_t *p_map_item;
	cl_malloc_hdr_t *p_hdr;

	buf = allocate_meminfo();

	if (!buf)
		return 0;

	len = sprintf(buf, "Memory Allocation Info : %s",
		      (!gp_mem_tracker ? "Tracking not turned on\n" : "\n"));

	size += len;

	if (gp_mem_tracker) {
		len = sprintf(buf + size, "Address  FileName        Line\n"
			      "-------  --------        ----\n");
	} else {
		goto end;
	}
	cl_spinlock_acquire(&gp_mem_tracker->lock);
	p_map_item = cl_qmap_head(&gp_mem_tracker->alloc_map);
	while (p_map_item != cl_qmap_end(&gp_mem_tracker->alloc_map)) {
		p_hdr = PARENT_STRUCT(p_map_item, cl_malloc_hdr_t, map_item);
		len = print_mem_entry(p_hdr, buf + size);
		size += len;
		p_map_item = cl_qmap_next(p_map_item);
	}
	cl_spinlock_release(&gp_mem_tracker->lock);

      end:
	*data = buf;
	return size;
}

int
disp_meminfo(char *buffer, char **start, off_t offset, int maxlen)
{
	static char *data = NULL;
	static int total_size = 0;
	int cur_size;

	/*
	 * Generate data on first call
	 */
	if (!data)
		total_size = generate_meminfo_data(&data);

	/*
	 * How much data is available for read: OS splits reads into 512b
	 * blocks and asks each individually via a separate call.
	 */
	cur_size = (total_size <= maxlen ? total_size : maxlen);

	/*
	 * Is this the last read.. do something to generate
	 * an EOF
	 */
	if (cur_size <= 0) {
		data = NULL;
		return 0;
	}
	cl_memcpy((void *) buffer, (void *) data, cur_size);

	/*
	 * Set up for next call
	 */
	total_size -= cur_size;	/* Compute #bytes left to deliver */
	data += cur_size;

	*start = (char *) ((ssize_t) cur_size);
	return cur_size;
}

void
create_cl_proc_mem(IN struct proc_dir_entry *p_dir)
{
	p_proc_meminfo = create_proc_info_entry("complib/meminfo",
						0, 0, disp_meminfo);
}

void
destroy_cl_proc_mem(void)
{
	remove_proc_entry("complib/meminfo", 0);

	if (p_meminfo_buf) {
		cl_free(p_meminfo_buf);
		p_meminfo_buf = 0;
	}
}
