/*
*===============================================================================
*
* d/wilson_d520/memory.c
*
*-------------------------------------------------------------------------------
*
* Copyright (C) 2010 Thomas Streuer 
*
* This file is part of BQCD -- Berlin Quantum ChromoDynamics program
*
* BQCD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BQCD 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with BQCD.  If not, see <http:*www.gnu.org/licenses/>.
*
*-------------------------------------------------------------------------------
*/
#include "globals.h"
#include "memory.h"
#include "neighb.h"

#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>

static unsigned char* shm_base;
static unsigned char* shm_curr;

static double* malloc_aligned(int size)
{
  double* r;
  posix_memalign(&r, 4096, size);
  return r;
}

double* new_vec()
{
  return malloc_aligned(sizeof(double) * 24 * volume);
}

double* new_gc()
{
  return malloc_aligned(sizeof(double)*18*(4*volume+tot_bnd_size));
}

double* new_gc_dbl()
{
  unsigned sz = (sizeof(double) * 18 + sizeof(uint16_t)) * 8 * (volume+4);
  return malloc_aligned(sz);
}

void init_shmem()
{
  errno = 0;
  int fd = shm_open(SHMEM_FILE, O_RDWR | O_CREAT, 0600);
  if (errno)
    die("Cannot open shmem: %s", strerror(errno));
  ftruncate(fd, SHMEM_SIZE);
  shm_base = mmap(0, SHMEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (errno)
    die("Cannot mmap: %s", strerror(errno));
  shm_curr = shm_base + which_cpu * sizeof(double) * 24 * volume;
}

double* new_vec_shmem()
{
  double* r = (double*) shm_curr;
  shm_curr += sizeof(double) * 24 * volume * num_procs;
  return r;
}
