Example #1
1
static pointer
mapVidMemSparse(int ScreenNum, unsigned long Base, unsigned long Size, int flags)
{
    int fd, prot;
    unsigned long ret, rets = 0;

    static Bool was_here = FALSE;

    if (!was_here) {
      was_here = TRUE;

      xf86WriteMmio8 = writeSparse8;
      xf86WriteMmio16 = writeSparse16;
      xf86WriteMmio32 = writeSparse32;
      xf86WriteMmioNB8 = writeSparseNB8;
      xf86WriteMmioNB16 = writeSparseNB16;
      xf86WriteMmioNB32 = writeSparseNB32;
      xf86ReadMmio8 = readSparse8;
      xf86ReadMmio16 = readSparse16;
      xf86ReadMmio32 = readSparse32;
    }
	
    fd = open(DEV_MEM, (flags & VIDMEM_READONLY) ? O_RDONLY : O_RDWR);
    if (fd < 0) {
        FatalError("xf86MapVidMem: failed to open " DEV_MEM " (%s)\n",
		   strerror(errno));
    }

#if 0
    xf86Msg(X_INFO,"mapVidMemSparse: try Base 0x%lx size 0x%lx flags 0x%x\n",
	    Base, Size, flags);
#endif

    if (flags & VIDMEM_READONLY)
	prot = PROT_READ;
    else
	prot = PROT_READ | PROT_WRITE;

    /* This requirers linux-0.99.pl10 or above */

    /*
     * Always do DENSE mmap, since read32/write32 currently require it.
     */
    ret = (unsigned long)mmap((caddr_t)(DENSE_BASE + Base), Size,
		   prot, MAP_SHARED, fd,
		   (off_t) (bus_base + Base));

    /*
     * Do SPARSE mmap only when MMIO and not MMIO_32BIT, or FRAMEBUFFER
     * and SPARSE (which should require the use of read/write macros).
     *
     * By not SPARSE mmapping an 8MB framebuffer, we can save approx. 256K
     * bytes worth of pagetable (32 pages).
     */
    if (((flags & VIDMEM_MMIO) && !(flags & VIDMEM_MMIO_32BIT)) ||
	((flags & VIDMEM_FRAMEBUFFER) && (flags & VIDMEM_SPARSE)))
    {
        rets = (unsigned long)mmap((caddr_t)(SPARSE_BASE + (Base << 5)),
				   Size << 5, prot, MAP_SHARED, fd,
				   (off_t) _bus_base_sparse() + (Base << 5));
    }

    close(fd);
      
    if (ret == (unsigned long)MAP_FAILED) {
        FatalError("xf86MapVidMemSparse: Could not (dense) mmap fb (%s)\n",
		   strerror(errno));
    }

    if (((flags & VIDMEM_MMIO) && !(flags & VIDMEM_MMIO_32BIT)) ||
	((flags & VIDMEM_FRAMEBUFFER) && (flags & VIDMEM_SPARSE)))
    {
        if (rets == (unsigned long)MAP_FAILED ||
	    rets != (SPARSE_BASE + (Base << 5)))
	{
	    FatalError("mapVidMemSparse: Could not (sparse) mmap fb (%s)\n",
		       strerror(errno));
	}
    }

#if 1
    if (rets)
        xf86Msg(X_INFO,"mapVidMemSparse: mapped Base 0x%lx size 0x%lx"
		" to DENSE at 0x%lx and SPARSE at 0x%lx\n",
		Base, Size, ret, rets);
    else
        xf86Msg(X_INFO,"mapVidMemSparse: mapped Base 0x%lx size 0x%lx"
		" to DENSE only at 0x%lx\n",
		Base, Size, ret);

#endif
    return (pointer) ret;
}
Example #2
1
/**
 * Sets the webcam to capture at the given width and height
 */
void webcam_resize(webcam_t *w, uint16_t width, uint16_t height)
{
    uint32_t i;
    struct v4l2_format fmt;
    struct v4l2_buffer buf;

    // Use YUYV as default for now
    CLEAR(fmt);
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = width;
    fmt.fmt.pix.height = height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
    fmt.fmt.pix.colorspace = V4L2_COLORSPACE_REC709;
    fprintf(stderr, "%s: requesting image format %ux%u\n", w->name, width, height);
    _ioctl(w->fd, VIDIOC_S_FMT, &fmt);

    // Storing result
    w->width = fmt.fmt.pix.width;
    w->height = fmt.fmt.pix.height;
    w->colorspace = fmt.fmt.pix.colorspace;

    char *pixelformat = calloc(5, sizeof(char));
    memcpy(pixelformat, &fmt.fmt.pix.pixelformat, 4);
    fprintf(stderr, "%s: set image format to %ux%u using %s\n", w->name, w->width, w->height, pixelformat);

    // Buffers have been created before, so clear them
    if (NULL != w->buffers) {
        for (i = 0; i < w->nbuffers; i++) {
            munmap(w->buffers[i].start, w->buffers[i].length);
        }

        free(w->buffers);
    }

    // Request the webcam's buffers for memory-mapping
    struct v4l2_requestbuffers req;
    CLEAR(req);

    req.count = 4;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_MMAP;

    if (-1 == _ioctl(w->fd, VIDIOC_REQBUFS, &req)) {
        if (EINVAL == errno) {
            fprintf(stderr, "%s does not support memory mapping\n", w->name);
            return;
        } else {
            fprintf(stderr, "Unknown error with VIDIOC_REQBUFS: %d\n", errno);
            return;
        }
    }

    // Needs at least 2 buffers
    if (req.count < 2) {
        fprintf(stderr, "Insufficient buffer memory on %s\n", w->name);
        return;
    }

    // Storing buffers in webcam structure
    fprintf(stderr, "Preparing %d buffers for %s\n", req.count, w->name);
    w->nbuffers = req.count;
    w->buffers = calloc(w->nbuffers, sizeof(struct buffer));

    if (!w->buffers) {
        fprintf(stderr, "Out of memory\n");
        return;
    }

    // Prepare buffers to be memory-mapped
    for (i = 0; i < w->nbuffers; ++i) {
        CLEAR(buf);

        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;

        if (-1 == _ioctl(w->fd, VIDIOC_QUERYBUF, &buf)) {
            fprintf(stderr, "Could not query buffers on %s\n", w->name);
            return;
        }

        w->buffers[i].length = buf.length;
        w->buffers[i].start = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, w->fd, buf.m.offset);

        if (MAP_FAILED == w->buffers[i].start) {
            fprintf(stderr, "Mmap failed\n");
            return;
        }
    }
}
Example #3
0
int main(void)
{

#ifdef _POSIX_MEMORY_PROTECTION
  char tmpfname[256];
  int total_size = 1024;

  void *pa = NULL;
  void *addr = NULL;
  size_t size = total_size;
  int flag = MAP_SHARED;
  int fd;
  off_t off = 0;
  int prot;

  char * ch;

  pid_t child;
  int status;
  int sig_num;

  snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_mmap_6_3_%d",
           getpid());
  unlink(tmpfname);
  fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL,
            S_IRUSR | S_IWUSR);
  if (fd == -1)
  {
    printf(TNAME " Error at open(): %s\n",
           strerror(errno));
    exit(PTS_UNRESOLVED);
  }
  unlink(tmpfname);

  child = fork();

  if (child == 0)
  {
    fflush (NULL);
    if (ftruncate(fd, total_size) == -1)
    {
      printf(TNAME "Error at ftruncate(): %s\n",
              strerror(errno));
      exit(PTS_UNRESOLVED);
    }

    prot = PROT_NONE;
    pa = mmap(addr, size, prot, flag, fd, off);
    if (pa == MAP_FAILED)
    {
      printf("Test Fail: " TNAME " Error at mmap: %s\n",
            strerror(errno));
      exit(PTS_FAIL);
    }

    ch = pa;

    /* Write acess */
    *ch = 'b';
    exit(0);
  }
  else if (child > 0)
  {
    waitpid(child, &status, 0);
    close(fd);
    if (WIFSTOPPED(status))
    {
      sig_num = WSTOPSIG(status);
      if (sig_num == SIGSEGV)
      {
        printf("Test Pass: "******" Got SIGSEGV when writing the mapped memory, "
                "setting PROT_NONE\n");
        return PTS_PASS;
      }
      printf("Child process stopped by signal %d\n", sig_num);
    }
    if (WIFSIGNALED(status))
    {
      sig_num = WTERMSIG(status);
      if (sig_num == SIGSEGV)
      {
        printf ("Test Pass: "******" Got SIGSEGV when writing the mapped memory, "
                " setting PROT_NOTE\n");
        return PTS_PASS;
      }
      printf("Child process terminated by signal %d\n", sig_num);
    }
    if (WIFEXITED(status))
    {
      if (WEXITSTATUS(status) == 0)
      {
        printf ("Test FAIL: " TNAME
                " Did not got SIGSEGV when writing the mapped memory,"
                " setting PROT_NOTE\n");
        return PTS_FAIL;
      }

    }
    printf ("Test Unresolved\n");
    return PTS_UNRESOLVED;
  }

#else
    printf ("Test Unresolved: " TNAME
            " _POSIX_MEMORY_PROTECTION not defined\n");
    return PTS_UNRESOLVED;
#endif
}
int main(int argc, char *argv[]) {
   int fd_encrypt, fd_keys;
   char * fdata_encrypt, *fdata_keys;
   struct stat finfo_encrypt, finfo_keys;
   char * fname_encrypt, *fname_keys;

	 /* Option to provide the encrypted words in a file as opposed to source code */
   //fname_encrypt = "encrypt.txt";
   
   if (argv[1] == NULL)
   {
      printf("USAGE: %s <keys filename>\n", argv[0]);
      exit(1);
   }
   fname_keys = argv[1];

   struct timeval starttime,endtime;
   srand( (unsigned)time( NULL ) );

   /*// Read in the file
   CHECK_ERROR((fd_encrypt = open(fname_encrypt,O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd_encrypt, &finfo_encrypt) < 0);
   // Memory map the file
   CHECK_ERROR((fdata_encrypt= mmap(0, finfo_encrypt.st_size + 1,
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_encrypt, 0)) == NULL);*/

   // Read in the file
   CHECK_ERROR((fd_keys = open(fname_keys,O_RDONLY)) < 0);
   // Get the file info (for file length)
   CHECK_ERROR(fstat(fd_keys, &finfo_keys) < 0);
   // Memory map the file
   CHECK_ERROR((fdata_keys= mmap(0, finfo_keys.st_size + 1,
      PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_keys, 0)) == NULL);

   // Setup splitter args

	//dprintf("Encrypted Size is %ld\n",finfo_encrypt.st_size);
	dprintf("Keys Size is %ld\n",finfo_keys.st_size);

   str_data_t str_data;

   str_data.keys_file_len = finfo_keys.st_size;
   str_data.encrypted_file_len = 0;
   str_data.bytes_comp = 0;
   str_data.keys_file  = ((char *)fdata_keys);
   str_data.encrypt_file  = NULL;
   //str_data.encrypted_file_len = finfo_encrypt.st_size;
   //str_data.encrypt_file  = ((char *)fdata_encrypt);    

   printf("String Match: Calling Serial String Match\n");

   gettimeofday(&starttime,0);
   string_match_splitter(&str_data);
   gettimeofday(&endtime,0);

   printf("String Match: Completed %ld\n",(endtime.tv_sec - starttime.tv_sec));

   /*CHECK_ERROR(munmap(fdata_encrypt, finfo_encrypt.st_size + 1) < 0);
   CHECK_ERROR(close(fd_encrypt) < 0);*/

   CHECK_ERROR(munmap(fdata_keys, finfo_keys.st_size + 1) < 0);
   CHECK_ERROR(close(fd_keys) < 0);

   return 0;
}
static void test_mmap_wrong_format_version (const char * tmpFile)
{
	// first write a mmap file
	{
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = simpleTestKeySet ();
		succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 1, "kdbSet was not successful");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}

	// set wrong version number in mmap header
	FILE * fp;
	if ((fp = fopen (tmpFile, "r+")) == 0)
	{
		yield_error ("fopen() error");
	}
	struct stat sbuf;
	if (stat (tmpFile, &sbuf) == -1)
	{
		yield_error ("stat() error");
	}

	int fd = fileno (fp);
	char * mappedRegion = mmap (0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (mappedRegion == MAP_FAILED)
	{
		ELEKTRA_LOG_WARNING ("error mapping file %s\nmmapSize: " ELEKTRA_STAT_ST_SIZE_F, tmpFile, sbuf.st_size);
		yield_error ("mmap() error");
		return;
	}
	if (fp)
	{
		fclose (fp);
	}

	MmapHeader * mmapHeader = (MmapHeader *) mappedRegion;
	mmapHeader->formatVersion = ELEKTRA_MMAP_FORMAT_VERSION + 1;

	if (msync ((void *) mappedRegion, sbuf.st_size, MS_SYNC) != 0)
	{
		yield_error ("msync() error");
		return;
	}

	if (munmap (mappedRegion, sbuf.st_size) != 0)
	{
		yield_error ("munmap() error");
		return;
	}

	// wrong format version should be detected now
	{
		// we expect an error here
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = ksNew (0, KS_END);
		succeed_if (plugin->kdbGet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
			    "kdbGet did not detect wrong format version");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}
}
Example #6
0
// "Let us say that after performing the aformentioned memory write, one
// then increased the size of the file beyond the written area, without
// over-writing the intervening contents (e.g. by using lseek(2) and then
// write(2) with a size of 1), thus creating a 'hole' in the file. What
// happens to the data that had been written to this hole previously via
// the memory-map? Are they visible in the file?"
void e()
{
	fprintf(stderr, "Part E:\n");
	int fd;
	struct stat st;
	char *fileName = "test.txt";
	char *addr;
	size_t sizeBefore, sizeAfter1, sizeAfter2;

	openStatFile(&fd, fileName, &st);
	sizeBefore = st.st_size;

	addr = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (addr == MAP_FAILED)
	{
		fprintf(stderr, "Error mapping file into memory: %s\n", strerror(errno));
		exit(1);
	}
	char *beforeWrite = (char*)malloc(strlen(addr));
	strcpy(beforeWrite,addr);
	sprintf(addr + strlen(addr), "Write this beyond the buffer.");

	char *attemptWrite = (char*)malloc(strlen(addr));
	strcpy(attemptWrite,addr);

	//Update stat
	if(fstat(fd, &st) < 0)
	{
		fprintf(stderr, "Error getting file information: %s\n", strerror(errno));
		exit(1);		
	}

	sizeAfter1 = st.st_size;

	if(lseek(fd,(int)strlen(addr), SEEK_END) < 0)
	{
		fprintf(stderr, "Error occurred during lseek(2): %s\n", strerror(errno));
		exit(1);
	}

	if(write(fd, "0", 1) != 1)
	{
		fprintf(stderr, "Error occurred during write: %s\n", strerror(errno));
		exit(1);
	}

	if(lseek(fd, 0, SEEK_SET) < 0)
	{
		fprintf(stderr, "Error occurred during lseek(2): %s\n", strerror(errno));
		exit(1);
	}

	char *afterWrite = (char*)malloc(strlen(addr));
	strcpy(afterWrite, readFile(fd, strlen(addr)));

	//Update stat
	if(fstat(fd, &st) < 0)
	{
		fprintf(stderr, "Error getting file information: %s\n", strerror(errno));
		exit(1);		
	}

	sizeAfter2 = st.st_size;

	fprintf(stderr, "Report:\n");
	fprintf(stderr, "Before the write:\n");
	fprintf(stderr, "\tThe file size was: %zu\n", sizeBefore);
	fprintf(stderr, "\tThe length of the virtual address was: %zu\n", strlen(beforeWrite));
	fprintf(stderr, "After the first write:\n");
	fprintf(stderr, "\tThe file size was: %zu\n", sizeAfter1);
	fprintf(stderr, "\tThe length of the virtual address was: %zu\n", strlen(attemptWrite));
	fprintf(stderr, "After the second write:\n");
	fprintf(stderr, "\tThe file size was: %zu\n", sizeAfter2);
	fprintf(stderr, "\tThe length of the virtual address was: %zu\n", strlen(afterWrite));

	if(strlen(attemptWrite) > strlen(beforeWrite))
	{
		fprintf(stderr, "The data that had been written to the hole previously\n");
		fprintf(stderr, "via the memory-map was saved in the virtual address space.\n");
	}
	else
	{
		fprintf(stderr, "The data that had been written to the hole previously\n");
		fprintf(stderr, "via the memory-map was not saved in the virtual address space.\n");
	}

	if(strlen(attemptWrite) > strlen(afterWrite))
	{
		fprintf(stderr, "The data that had been written to the hole previously\n");
		fprintf(stderr, "via the memory-map is not visible in the file.\n");
	}
	else
	{
		fprintf(stderr, "The data that had been written to the hole previously\n");
		fprintf(stderr, "via the memory-map is visible in the file.\n");
	}

	//printf("%zu %zu %zu\n", sizeBefore, sizeAfter1, sizeAfter2);
	//printf("%zu %zu %zu\n", strlen(beforeWrite), strlen(attemptWrite), strlen(afterWrite));

	return;
}
Example #7
0
static int get_framebuffer(GGLSurface *fb)
{
    int fd;
    void *bits;

    fd = open("/dev/graphics/fb0", O_RDWR);
    if (fd < 0) {
        perror("cannot open fb0");
        return -1;
    }

    if (ioctl(fd, FBIOGET_VSCREENINFO, &vi) < 0) {
        perror("failed to get fb0 info");
        close(fd);
        return -1;
    }

       vi.bits_per_pixel = PIXEL_SIZE * 8;
       if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_BGRA_8888) {
         vi.red.offset     = 8;
         vi.red.length     = 8;
         vi.green.offset   = 16;
         vi.green.length   = 8;
         vi.blue.offset    = 24;
         vi.blue.length    = 8;
         vi.transp.offset  = 0;
         vi.transp.length  = 8;
       } else if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_RGBX_8888) {
         vi.red.offset     = 24;
         vi.red.length     = 8;
         vi.green.offset   = 16;
         vi.green.length   = 8;
         vi.blue.offset    = 8;
         vi.blue.length    = 8;
         vi.transp.offset  = 0;
         vi.transp.length  = 8;
    } else if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_RGB_565) {
#ifndef RECOVERY_BGR_565
		fprintf(stderr, "Pixel format: RGB_565\n");
		vi.blue.offset    = 0;
		vi.green.offset   = 5;
		vi.red.offset     = 11;
#else
        fprintf(stderr, "Pixel format: BGR_565\n");
		vi.blue.offset    = 11;
		vi.green.offset   = 5;
		vi.red.offset     = 0;
#endif
		if (PIXEL_SIZE != 2)    fprintf(stderr, "E: Pixel Size mismatch!\n");
		vi.blue.length    = 5;
		vi.green.length   = 6;
		vi.red.length     = 5;
        vi.blue.msb_right = 0;
        vi.green.msb_right = 0;
        vi.red.msb_right = 0;
        vi.transp.offset  = 0;
        vi.transp.length  = 0;
    }
    else
    {
        perror("unknown pixel format");
        close(fd);
        return -1;
    }

    vi.vmode = FB_VMODE_NONINTERLACED;
    vi.activate = FB_ACTIVATE_NOW | FB_ACTIVATE_FORCE;
       if (ioctl(fd, FBIOPUT_VSCREENINFO, &vi) < 0) {
           perror("failed to put fb0 info");
           close(fd);
           return -1;
       }
       if (ioctl(fd, FBIOGET_FSCREENINFO, &fi) < 0) {
           perror("failed to get fb0 info");
           close(fd);
           return -1;
       }

       bits = mmap(0, fi.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
       if (bits == MAP_FAILED) {
           perror("failed to mmap framebuffer");
           close(fd);
           return -1;
       }

    overscan_offset_x = vi.xres * overscan_percent / 100;
    overscan_offset_y = vi.yres * overscan_percent / 100;

    fb->version = sizeof(*fb);
    fb->width = vi.xres;
    fb->height = vi.yres;
    fb->stride = fi.line_length/PIXEL_SIZE;
    fb->data = bits;
    fb->format = PIXEL_FORMAT;
    memset(fb->data, 0, vi.yres * fi.line_length);

    fb++;

    /* check if we can use double buffering */
    if (vi.yres * fi.line_length * 2 > fi.smem_len)
        return fd;

    double_buffering = 1;

    fb->version = sizeof(*fb);
    fb->width = vi.xres;
    fb->height = vi.yres;
    fb->stride = fi.line_length/PIXEL_SIZE;
    fb->data = (void*) (((unsigned) bits) + vi.yres * fi.line_length);
    fb->format = PIXEL_FORMAT;
    memset(fb->data, 0, vi.yres * fi.line_length);

    return fd;
}
static void *
tf (void *arg)
{
  struct flock fl =
    {
      .l_type = F_WRLCK,
      .l_start = 0,
      .l_whence = SEEK_SET,
      .l_len = 10
    };
  if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0)
    {
      puts ("fourth fcntl failed");
      exit (1);
    }

  pthread_mutex_unlock (&lock);

  pthread_mutex_lock (&lock2);

  return NULL;
}


static int
do_test (void)
{
  char tmp[] = "/tmp/tst-flock2-XXXXXX";

  fd = mkstemp (tmp);
  if (fd == -1)
    {
      puts ("mkstemp failed");
      return 1;
    }

  unlink (tmp);

  int i;
  for (i = 0; i < 20; ++i)
    write (fd, "foobar xyzzy", 12);

  pthread_barrier_t *b;
  b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE,
	    MAP_SHARED, fd, 0);
  if (b == MAP_FAILED)
    {
      puts ("mmap failed");
      return 1;
    }

  pthread_barrierattr_t ba;
  if (pthread_barrierattr_init (&ba) != 0)
    {
      puts ("barrierattr_init failed");
      return 1;
    }

  if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0)
    {
      puts ("barrierattr_setpshared failed");
      return 1;
    }

  if (pthread_barrier_init (b, &ba, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  if (pthread_barrierattr_destroy (&ba) != 0)
    {
      puts ("barrierattr_destroy failed");
      return 1;
    }

  struct flock fl =
    {
      .l_type = F_WRLCK,
      .l_start = 0,
      .l_whence = SEEK_SET,
      .l_len = 10
    };
  if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0)
    {
      puts ("first fcntl failed");
      return 1;
    }

  pid_t pid = fork ();
  if (pid == -1)
    {
      puts ("fork failed");
      return 1;
    }

  if (pid == 0)
    {
      /* Make sure the child does not stay around indefinitely.  */
      alarm (10);

      /* Try to get the lock.  */
      if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0)
	{
	  puts ("child:  second flock succeeded");
	  return 1;
	}
    }

  pthread_barrier_wait (b);

  if (pid != 0)
    {
      fl.l_type = F_UNLCK;
      if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0)
	{
	  puts ("third fcntl failed");
	  return 1;
	}
    }

  pthread_barrier_wait (b);

  pthread_t th;
  if (pid == 0)
    {
      if (pthread_mutex_lock (&lock) != 0)
	{
	  puts ("1st locking of lock failed");
	  return 1;
	}

      if (pthread_mutex_lock (&lock2) != 0)
	{
	  puts ("1st locking of lock2 failed");
	  return 1;
	}

      if (pthread_create (&th, NULL, tf, NULL) != 0)
	{
	  puts ("pthread_create failed");
	  return 1;
	}

      if (pthread_mutex_lock (&lock) != 0)
	{
	  puts ("2nd locking of lock failed");
	  return 1;
	}

      puts ("child locked file");
    }

  pthread_barrier_wait (b);

  if (pid != 0)
    {
      fl.l_type = F_WRLCK;
      if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0)
	{
	  puts ("fifth fcntl succeeded");
	  return 1;
	}

      puts ("file locked by child");
    }

  pthread_barrier_wait (b);

  if (pid == 0)
    {
      if (pthread_mutex_unlock (&lock2) != 0)
	{
	  puts ("unlock of lock2 failed");
	  return 1;
	}

      if (pthread_join (th, NULL) != 0)
	{
	  puts ("join failed");
	  return 1;
	}

      puts ("child's thread terminated");
    }

  pthread_barrier_wait (b);

  if (pid != 0)
    {
      fl.l_type = F_WRLCK;
      if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLK, &fl)) == 0)
	{
	  puts ("fifth fcntl succeeded");
	  return 1;
	}

      puts ("file still locked");
    }

  pthread_barrier_wait (b);

  if (pid == 0)
    {
      _exit (0);
    }

  int status;
  if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid)
    {
      puts ("waitpid failed");
      return 1;
    }
  puts ("child terminated");

  if (TEMP_FAILURE_RETRY (fcntl (fd, F_SETLKW, &fl)) != 0)
    {
      puts ("sixth fcntl failed");
      return 1;
    }

  return status;
}
int main (int argc, char * argv[])
{
   int fd;
   void *filememory_1;
   void *filememory_2;
   void *filememory_3;
   unsigned int pg_sz = sysconf(_SC_PAGESIZE);
   char fname[] = "/tmp/test-mmap.XXXXXX";

   fd = mkstemp(fname);
   if (fd < 0)
   {
      fprintf (stderr, "Couldn't open %s for writing\n", fname);
      return (1);
   }

   unlink(fname);

   write (fd, TESTSTRING0, sizeof TESTSTRING0);

   ftruncate(fd, pg_sz);
   lseek(fd, pg_sz, SEEK_SET);
   write(fd, TESTSTRING1, sizeof TESTSTRING1);

   ftruncate(fd, 2*pg_sz);

   /*
      Try mmapping the newly created file...
   */

   filememory_1 = mmap (NULL, 0x0100, PROT_READ, MAP_PRIVATE, fd, 0);
   
   if (filememory_1 == (void *) -1)
   {
      perror("mmap returned error");
      return (1);
   }

   /*
      Test mapping at a given offset
    */

   filememory_3 = mmap (NULL, 0x0100, PROT_READ, MAP_PRIVATE, fd, pg_sz);

   if (filememory_3 == (void *) -1)
   {
      perror("mmap (pg_sz) returned error");
      return (1);
   }

   /*
      Try mmapping with a bogus file descriptor... (should fail)
   */

   filememory_2 = mmap (NULL, 0x0100, PROT_READ, MAP_PRIVATE, fd+10, 0);
   
   if ((filememory_2 != (void *) -1) || (errno != 9))
   {
      fprintf (stderr, "mmap allowed a bogus file descriptor...\n");
      return (1);
   }
   
   /*
      Check that we can read back from the file OK
   */

   if (memcmp(filememory_1, TESTSTRING0, sizeof TESTSTRING0) != 0)
   {
      fprintf (stderr, "mmap doesn't give expected data...\n");
      return (1);
   }

   if (memcmp(filememory_3, TESTSTRING1, sizeof TESTSTRING1) != 0)
   {
      fprintf (stderr, "mmap (pg_sz) doesn't give expected data...\n");
      return (1);
   }

   if (munmap(filememory_3, 0x0100) < 0 ||
       munmap(filememory_1, 0x0100) < 0)
   {
      perror("munmap()");
      return 1;
   }

   /*
      Clean up.
   */
   close (fd);

   return (0);
}
static int
DMA_OpenDevice(_THIS, const char *devname, int iscapture)
{
    const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT);
    int format;
    int stereo;
    int value;
    SDL_AudioFormat test_format;
    struct audio_buf_info info;

    /* We don't care what the devname is...we'll try to open anything. */
    /*  ...but default to first name in the list... */
    if (devname == NULL) {
        if (((iscapture) && (inputDeviceCount == 0)) ||
            ((!iscapture) && (outputDeviceCount == 0))) {
            SDL_SetError("No such audio device");
            return 0;
        }
        devname = ((iscapture) ? inputDevices[0] : outputDevices[0]);
    }

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        SDL_OutOfMemory();
        return 0;
    }
    SDL_memset(this->hidden, 0, (sizeof *this->hidden));

    /* Open the audio device */
    audio_fd = open(devname, flags, 0);
    if (audio_fd < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
        return 0;
    }
    dma_buf = NULL;
    ioctl(audio_fd, SNDCTL_DSP_RESET, 0);

    /* Get a list of supported hardware formats */
    if (ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't get audio format list");
        return 0;
    }

    /* Try for a closest match on audio format */
    format = 0;
    for (test_format = SDL_FirstAudioFormat(this->spec.format);
         !format && test_format;) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
        switch (test_format) {
        case AUDIO_U8:
            if (value & AFMT_U8) {
                format = AFMT_U8;
            }
            break;
        case AUDIO_S8:
            if (value & AFMT_S8) {
                format = AFMT_S8;
            }
            break;
        case AUDIO_S16LSB:
            if (value & AFMT_S16_LE) {
                format = AFMT_S16_LE;
            }
            break;
        case AUDIO_S16MSB:
            if (value & AFMT_S16_BE) {
                format = AFMT_S16_BE;
            }
            break;
        case AUDIO_U16LSB:
            if (value & AFMT_U16_LE) {
                format = AFMT_U16_LE;
            }
            break;
        case AUDIO_U16MSB:
            if (value & AFMT_U16_BE) {
                format = AFMT_U16_BE;
            }
            break;
        default:
            format = 0;
            break;
        }
        if (!format) {
            test_format = SDL_NextAudioFormat();
        }
    }
    if (format == 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't find any hardware audio formats");
        return 0;
    }
    this->spec.format = test_format;

    /* Set the audio format */
    value = format;
    if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't set audio format");
        return 0;
    }

    /* Set mono or stereo audio (currently only two channels supported) */
    stereo = (this->spec.channels > 1);
    ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo);
    if (stereo) {
        this->spec.channels = 2;
    } else {
        this->spec.channels = 1;
    }

    /* Because some drivers don't allow setting the buffer size
       after setting the format, we must re-open the audio device
       once we know what format and channels are supported
     */
    if (DMA_ReopenAudio(this, devname, format, stereo) < 0) {
        DMA_CloseDevice(this);
        /* Error is set by DMA_ReopenAudio() */
        return 0;
    }

    /* Memory map the audio buffer */
    if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't get OSPACE parameters");
        return 0;
    }
    this->spec.size = info.fragsize;
    this->spec.samples = this->spec.size / ((this->spec.format & 0xFF) / 8);
    this->spec.samples /= this->spec.channels;
    num_buffers = info.fragstotal;
    dma_len = num_buffers * this->spec.size;
    dma_buf = (Uint8 *) mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED,
                             audio_fd, 0);
    if (dma_buf == MAP_FAILED) {
        DMA_CloseDevice(this);
        SDL_SetError("DMA memory map failed");
        dma_buf = NULL;
        return 0;
    }
    SDL_memset(dma_buf, this->spec.silence, dma_len);

    /* Check to see if we need to use select() workaround */
    {
        char *workaround;
        workaround = SDL_getenv("SDL_DSP_NOSELECT");
        if (workaround) {
            frame_ticks =
                (float) (this->spec.samples * 1000) / this->spec.freq;
            next_frame = SDL_GetTicks() + frame_ticks;
        }
    }

    /* Trigger audio playback */
    value = 0;
    ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value);
    value = PCM_ENABLE_OUTPUT;
    if (ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't trigger audio output");
        return 0;
    }

    /* Get the parent process id (we're the parent of the audio thread) */
    parent = getpid();

    /* We're ready to rock and roll. :-) */
    return 1;
}
Example #11
0
	int main(int argc, char *argv[])
	{
	//argv[1] = name of the shared memory
	//argv[2] = number of clients

	/*confirmação da existencia de memoria partilhada*/
		char memPath[DEFAULT_STRING_SIZE];

		sprintf(memPath,"%s",argv[1]);

		int shmfd = shm_open(memPath,O_RDWR,0600); 

		if (argc != 3){
			fprintf( stderr, "Usage: %s <memoriaPartilhada> <numdeClientes>\n", argv[0]);
			exit(1);
		}

		int numberOfCli;

		sscanf(argv[2],"%i",&numberOfCli);

		if(numberOfCli <= 0)
		{
			fprintf(stderr, "Numero de Clientes Invalido\n");
			exit(2);
		}


		if(shmfd == -1){
			printf("Não há memória partilhada aberta!\n");
			exit(3);
		}

		if (ftruncate(shmfd,SHM_SIZE) < 0)
		{
			fprintf(stderr, "Erro ao executar truncate da SHM -> %s\n", strerror(errno));
			exit(4);
		};

		int *pt = (int *) mmap(0,SHM_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,shmfd,0);
		if(pt == MAP_FAILED)
		{
			fprintf(stderr, "Erro ao executar o mapeamento da SHM -> %s\n", strerror(errno));
			exit(5);
		} 

		if(pt[NUMOFOPENBALCOES] == 0){
			printf("Não há balcoes abertos!\n");
			exit(6);
		};

		char semName[DEFAULT_STRING_SIZE];

		sprintf(semName,"/%s",memPath);

		sem_t *sem = sem_open(semName,0,0600,1);
		if(sem == SEM_FAILED)
		{
			perror("WRITER failure in sem_open()");
			exit(4);
		}

		pid_t pid;

/*Add number of clients to process
Is used to stop the balcao from closing while its being chosen*/

		sem_wait(sem);

		pt[NUMBEROFCLIENTS] = pt[NUMBEROFCLIENTS] + numberOfCli;

		sem_post(sem);


//cycle to generate the multiple clients
		while(numberOfCli > 0){

			pid = fork();

			if(pid < 0){
				printf("Erro ao executar o fork de criação de Clientes\n");
				exit(7);
			}
			else if(pid == 0){

				/*Create client FIFO*/
				char privateFIFOPathname[DEFAULT_STRING_SIZE], balcaoFIFO[DEFAULT_STRING_SIZE], balcaoAnswer[DEFAULT_STRING_SIZE];
				int currentPID = getpid();
				sprintf(privateFIFOPathname,"/tmp/fc_%d",currentPID);
				if(mkfifo(privateFIFOPathname,0660) < 0){
					printf("Erro ao criar o fifo privado do Cliente\n");
					exit(8);
				}

				

				pthread_t tid;
			void *retval; //return value of the chosen balcao
			sem_wait(sem);//using this semaphore to acess the shm, if not used the chosen balcao might be wrong
			pthread_create(&tid,NULL,chooseBalcao,pt);//choose what balcao to join
			pthread_join(tid,&retval);
			int chosenBalcao = *(int *)retval;
			free (retval);// free the malloc in chooseBalcao
			pt[BALCAODEFINING + NUMOFBALCAOVARIABLES*(chosenBalcao-1) + 4]++;
			sprintf(balcaoFIFO,"/tmp/fb_%d",pt[BALCAODEFINING + NUMOFBALCAOVARIABLES*(chosenBalcao-1) + 3]);//getting the chosen balcao FIFO ID
			int fdBalcao = open(balcaoFIFO,O_WRONLY);
			write(fdBalcao,privateFIFOPathname,strlen(privateFIFOPathname)+1);//writing to the chosen balcao the client FIFO ID
			close(fdBalcao);
			writeLOG(memPath,time(NULL),CLIENT,chosenBalcao,CLIASKSSERVICE,privateFIFOPathname);
			sem_post(sem);
			int fd = open(privateFIFOPathname,O_RDONLY);
			read(fd,balcaoAnswer,FIMDEATENDIMENTOSIZE+1);
			if(strcmp(balcaoAnswer,FIMDEATENDIMENTO) == 0)
				writeLOG(memPath,time(NULL),CLIENT,chosenBalcao,CLIENTENDSERVICE,privateFIFOPathname);
			unlink(privateFIFOPathname);
			sem_close(sem);
			return 0;
		}
		else{
			numberOfCli--;
		}
	}
	exit(0);
}
void init_camara()
{
	//Estos son para el Thread de la camara
	int err, i;
	char errMsj[1024];//posible mensaje de error

	//1) Open a descriptor to the device. This is done UNIX-style, basic I/O.
	//camara_fds[i-(cantPuertos+1)]
	camara_fd = open("/dev/video0", O_RDWR);
	if(camara_fd == -1) closeWithError("Unable to open camera");
	puts("1) camera open");

	//2) Retrieve the device’s capabilities
	struct v4l2_capability cap;
	if(ioctl(camara_fd, VIDIOC_QUERYCAP, &cap) < 0) closeWithError("VIDIOC_QUERYCAP");
	puts("2) The v4l2_capability structure if filled with information about the device");
	// http://linuxtv.org/downloads/v4l-dvb-apis/vidioc-querycap.html#device-capabilities

	if(!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
		closeWithError("The device does not handle single-planar video capture.");

	//3) Set our video format
	//To see a list with all available formats in your device:
	//v4l2-ctl -d /dev/video0 --list-formats-ext
	//chose MJPEG because it is extremely easy to display using the SDL
	format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	format.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
	format.fmt.pix.width = 640;
	format.fmt.pix.height = 480;
	if(ioctl(camara_fd, VIDIOC_S_FMT, &format) < 0) closeWithError("VIDIOC_S_FMT");

	//4) Inform the device about your future buffers
	//we’ll use a single buffer, and map our memory using mmap.
	//All this information is sent using the VIDIOC_REQBUFS call and a v4l2_requestbuffers structure:
	struct v4l2_requestbuffers bufrequest;
	bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	bufrequest.memory = V4L2_MEMORY_MMAP; //Hay mas opciones: http://linuxtv.org/downloads/v4l-dvb-apis/buffer.html#v4l2-memory
	bufrequest.count = 1;
	if(ioctl(camara_fd, VIDIOC_REQBUFS, &bufrequest) < 0) closeWithError("VIDIOC_REQBUFS");

	//5) Allocate your buffers
	memset(&bufferinfo, 0, sizeof(bufferinfo));
	bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	bufferinfo.memory = V4L2_MEMORY_MMAP;
	bufferinfo.index = 0;
	if(ioctl(camara_fd, VIDIOC_QUERYBUF, &bufferinfo) < 0) closeWithError("VIDIOC_QUERYBUF");

	//Here again, think about cleaning up the area.
	//Your frame is going to be stored in there, you don’t want garbage messing around.
	buffer_start = mmap(NULL, bufferinfo.length, PROT_READ | PROT_WRITE, MAP_SHARED, camara_fd, bufferinfo.m.offset);
	if(buffer_start == MAP_FAILED) closeWithError("mmap");
	memset(buffer_start, 0, bufferinfo.length);

	//7) Activate streaming
	type = bufferinfo.type;
	if(ioctl(camara_fd, VIDIOC_STREAMON, &type) < 0) closeWithError("VIDIOC_STREAMON");

	//Aqui se crea el thread de lectura
	continuar=true;
	err = pthread_create(&(tcamara), NULL, &tomarCamara, NULL);
  if(err != 0)
  {
		sprintf(errMsj,"Can't create thread:[%s]", strerror(err));
		closeWithError(errMsj);
  }
  else printf("Thread created successfully\n");
  printf(KCYN"___________________________\n"RESET);
}
Example #13
0
int main(int argc, char **argv) {
	int fd = -1;
	int retval = EXIT_SUCCESS;

	if(argc < 2) {
		fprintf(stderr,
                        "%s version %s-%s\n"
			"\nUsage:\n"
			"\tread addr: address\n"
                        "\twrite addr: address value\n"
			"\tread analog mixed signals: -ams\n"
			"\tset slow DAC: -sdac AO0 AO1 AO2 AO3 [V]\n",
                        argv[0], VERSION_STR, REVISION_STR);
		return EXIT_FAILURE;
	}

	if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;

	/* Read from standard input */
	if (strncmp(argv[1], "-ams", 4) == 0) {
		uint32_t addr = c_addrAms;
		amsReg_t* ams=NULL;
		// Map one page
		map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, addr & ~MAP_MASK);
		if(map_base == (void *) -1) FATAL;

		ams = map_base + (addr & MAP_MASK);
		AmsList(ams);

		if (map_base != (void*)(-1)) {
			if(munmap(map_base, MAP_SIZE) == -1) FATAL;
			map_base = (void*)(-1);
		}
	}
	else if (strncmp(argv[1], "-sdac", 5) == 0) {
		uint32_t addr = c_addrAms;
		amsReg_t* ams=NULL;

		double *val = NULL;
		ssize_t val_count = 0;
		parse_from_argv_par(argc, argv, &val, &val_count);

		if(val_count>SLOW_DAC_NUM){
			val_count=SLOW_DAC_NUM;
		}

		// Map one page
		map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, addr & ~MAP_MASK);
		if(map_base == (void *) -1) FATAL;

		ams = map_base + (addr & MAP_MASK);

		if (val_count == 0) {
			DacRead(ams);
		}
		else{
			DacWrite(ams, val, val_count);
		}

		if (map_base != (void*)(-1)) {
			if(munmap(map_base, MAP_SIZE) == -1) FATAL;
			map_base = (void*)(-1);
		}

	}
	else if (strncmp(argv[1], "-", 1) == 0) {
		unsigned long addr;
		unsigned long *val = NULL;
		int access_type = 'w';
		ssize_t val_count = 0;
		while ( parse_from_stdin(&addr, &access_type, &val, &val_count) != -1) {
			if (addr == 0) {
				continue;
			}
			/* Map one page */
			map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, addr & ~MAP_MASK);
			if(map_base == (void *) -1) FATAL;

			if (val_count == 0) {
				read_value(addr);
			}
			else {
				write_values(addr, access_type, val, val_count);
			}
			if (map_base != (void*)(-1)) {
				if(munmap(map_base, MAP_SIZE) == -1) FATAL;
				map_base = (void*)(-1);
			}
#if DEBUG_MONITOR
			printf("addr/type: %lu/%c\n", addr, access_type);

			printf("val (%ld):", val_count);
			for (ssize_t i = 0; i < val_count; ++i) {
				printf("%lu ", val[i]);
			}
			if (val != NULL) {
				free(val);
				val = NULL;
			}
			printf("\n");
#endif
		}
		goto exit;
	}
	/* Read from command line */
	else {
		unsigned long addr;
		unsigned long *val = NULL;
		int access_type = 'w';
		ssize_t val_count = 0;
		parse_from_argv(argc, argv, &addr, &access_type, &val, &val_count);

		/* Map one page */
		map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, addr & ~MAP_MASK);
		if(map_base == (void *) -1) FATAL;
			
		if (addr != 0) {
			if (val_count == 0) {
				read_value(addr);
			}
			else {
				write_values(addr, access_type, val, val_count);
			}
		}
		if (map_base != (void*)(-1)) {
			if(munmap(map_base, MAP_SIZE) == -1) FATAL;
			map_base = (void*)(-1);
		}
#if DEBUG_MONITOR
		printf("addr/type: %lu/%c\n", addr, access_type);

		printf("val (%ld):", val_count);
		for (ssize_t i = 0; i < val_count; ++i) {
			printf("%lu ", val[i]);
		}
		
		if (val != NULL) {
			free(val);
			val = NULL;
		}
		printf("\n");
#endif
	}

exit:

	if (map_base != (void*)(-1)) {
		if(munmap(map_base, MAP_SIZE) == -1) FATAL;
	}
	if (fd != -1) {
		close(fd);
	}
	
	return retval;
}
Example #14
0
static int get_framebuffer(GGLSurface *fb)
{
    int fd, index = 0;
    void *bits;

    fd = open("/dev/graphics/fb0", O_RDWR);
    
    while (fd < 0 && index < 30) {
        usleep(1000);
        fd = open("/dev/graphics/fb0", O_RDWR);
        index++;
    }
    if (fd < 0) {
        perror("cannot open fb0\n");
        return -1;
    }

    if (ioctl(fd, FBIOGET_VSCREENINFO, &vi) < 0) {
        perror("failed to get fb0 info");
        close(fd);
        return -1;
    }

    fprintf(stderr, "Pixel format: %dx%d @ %dbpp\n", vi.xres, vi.yres, vi.bits_per_pixel);

    vi.bits_per_pixel = PIXEL_SIZE * 8;
    if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_BGRA_8888) {
        fprintf(stderr, "Pixel format: BGRA_8888\n");
        if (PIXEL_SIZE != 4)    fprintf(stderr, "E: Pixel Size mismatch!\n");
        vi.red.offset     = 8;
        vi.red.length     = 8;
        vi.green.offset   = 16;
        vi.green.length   = 8;
        vi.blue.offset    = 24;
        vi.blue.length    = 8;
        vi.transp.offset  = 0;
        vi.transp.length  = 8;
    } else if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_RGBX_8888) {
        fprintf(stderr, "Pixel format: RGBX_8888\n");
        if (PIXEL_SIZE != 4)    fprintf(stderr, "E: Pixel Size mismatch!\n");
        vi.red.offset     = 24;
        vi.red.length     = 8;
        vi.green.offset   = 16;
        vi.green.length   = 8;
        vi.blue.offset    = 8;
        vi.blue.length    = 8;
        vi.transp.offset  = 0;
        vi.transp.length  = 8;
    } else if (PIXEL_FORMAT == GGL_PIXEL_FORMAT_RGB_565) {
#ifdef RECOVERY_RGB_565
		fprintf(stderr, "Pixel format: RGB_565\n");
		vi.blue.offset    = 0;
		vi.green.offset   = 5;
		vi.red.offset     = 11;
#else
        fprintf(stderr, "Pixel format: BGR_565\n");
		vi.blue.offset    = 11;
		vi.green.offset   = 5;
		vi.red.offset     = 0;
#endif
		if (PIXEL_SIZE != 2)    fprintf(stderr, "E: Pixel Size mismatch!\n");
		vi.blue.length    = 5;
		vi.green.length   = 6;
		vi.red.length     = 5;
        vi.blue.msb_right = 0;
        vi.green.msb_right = 0;
        vi.red.msb_right = 0;
        vi.transp.offset  = 0;
        vi.transp.length  = 0;
    }
    else
    {
        perror("unknown pixel format");
        close(fd);
        return -1;
    }

    vi.vmode = FB_VMODE_NONINTERLACED;
    vi.activate = FB_ACTIVATE_NOW | FB_ACTIVATE_FORCE;

    if (ioctl(fd, FBIOPUT_VSCREENINFO, &vi) < 0) {
        perror("failed to put fb0 info");
        close(fd);
        return -1;
    }

    if (ioctl(fd, FBIOGET_FSCREENINFO, &fi) < 0) {
        perror("failed to get fb0 info");
        close(fd);
        return -1;
    }

#ifdef MSM_BSP
    has_overlay = target_has_overlay(fi.id);

    if (isTargetMdp5())
        setDisplaySplit();
#else
    has_overlay = false;
#endif

    if (!has_overlay) {
        printf("Not using qualcomm overlay, '%s'\n", fi.id);
        bits = mmap(0, fi.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
        if (bits == MAP_FAILED) {
            perror("failed to mmap framebuffer");
            close(fd);
            return -1;
        }
    } else {
        printf("Using qualcomm overlay\n");
    }

#ifdef RECOVERY_GRAPHICS_USE_LINELENGTH
    vi.xres_virtual = fi.line_length / PIXEL_SIZE;
#endif

    fb->version = sizeof(*fb);
    fb->width = vi.xres;
    fb->height = vi.yres;
#ifdef BOARD_HAS_JANKY_BACKBUFFER
    printf("setting JANKY BACKBUFFER\n");
    fb->stride = fi.line_length/2;
#else
    fb->stride = vi.xres_virtual;
#endif
    fb->format = PIXEL_FORMAT;
    if (!has_overlay) {
        fb->data = bits;
        memset(fb->data, 0, vi.yres * fb->stride * PIXEL_SIZE);
    }

    fb++;

#ifndef TW_DISABLE_DOUBLE_BUFFERING
    /* check if we can use double buffering */
    if (vi.yres * fi.line_length * 2 > fi.smem_len)
#else
    printf("TW_DISABLE_DOUBLE_BUFFERING := true\n");
#endif
        return fd;

    double_buffering = 1;

    fb->version = sizeof(*fb);
    fb->width = vi.xres;
    fb->height = vi.yres;
#ifdef BOARD_HAS_JANKY_BACKBUFFER
    fb->stride = fi.line_length/2;
    fb->data = (GGLubyte*) (((unsigned long) bits) + vi.yres * fi.line_length);
#else
    fb->stride = vi.xres_virtual;
    fb->data = (GGLubyte*) (((unsigned long) bits) + vi.yres * fb->stride * PIXEL_SIZE);
#endif
    fb->format = PIXEL_FORMAT;
    if (!has_overlay) {
        memset(fb->data, 0, vi.yres * fb->stride * PIXEL_SIZE);
    }

#ifdef PRINT_SCREENINFO
	print_fb_var_screeninfo();
#endif

    return fd;
}
Example #15
0
int
main(int argc, char **argv)
{
	int fd, pfd, ret;
	char *buf;
	/*
	 * gcc -O2 will optimize foo's storage, prevent reproducing
	 * this issue.
	 * foo is never actually used after fault in value stored.
	 */
	volatile char foo __attribute__((__unused__));
	int pagesize = getpagesize();

	if (argc < 3) {
		printf("Usage: %s <file> <pmem file>\n", basename(argv[0]));
		exit(0);
	}

	 /* O_DIRECT is necessary for reproduce this bug. */
	fd = open(argv[1], O_RDONLY|O_DIRECT);
	if (fd < 0)
		err_exit("open");

	pfd = open(argv[2], O_RDONLY);
	if (pfd < 0)
		err_exit("pmem open");

	buf = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, pfd, 0);
	if (buf == MAP_FAILED)
		err_exit("mmap");

	/*
	 * Read from the DAX mmap to populate the first page in the
	 * address_space with a read-only mapping.
	 */
	foo = *buf;

	/*
	 * Now write to the DAX mmap.  This *should* fail, but if the bug is
	 * present in __get_user_pages_fast(), it will succeed.
	 */
	ret = read(fd, buf, pagesize);
	if (ret != pagesize)
		err_exit("read");

	ret = msync(buf, pagesize, MS_SYNC);
	if (ret != 0)
		err_exit("msync");

	ret = munmap(buf, pagesize);
	if (ret < 0)
		err_exit("munmap");

	ret = close(fd);
	if (ret < 0)
		err_exit("clsoe fd");

	ret = close(pfd);
	if (ret < 0)
		err_exit("close pfd");

	exit(0);
}
bool CIrrDeviceFB::createWindow(const core::dimension2d<u32>& windowSize, u32 bits)
{
	char buf[256];
	CreationParams.WindowSize.Width = windowSize.Width;
	CreationParams.WindowSize.Height = windowSize.Height;

	KeyboardDevice = open("/dev/tty", O_RDWR);
	if (KeyboardDevice == -1)
		perror("Open keyboard");
	if (ioctl(KeyboardDevice, KDGETMODE, &KeyboardMode) <0)
		perror("Read keyboard mode");
	if (ioctl(KeyboardDevice, KDSETMODE, KD_GRAPHICS) <0)
		perror("Set keyboard mode");

	Framebuffer=open("/dev/fb/0", O_RDWR);
	if (Framebuffer == -1)
	{
		Framebuffer=open("/dev/fb0", O_RDWR);
		if (Framebuffer == -1)
		{
			perror("Open framebuffer");
			return false;
		}
	}
	EventDevice = open("/dev/input/event0", O_RDONLY | O_NONBLOCK);
	if (EventDevice == -1)
		perror("Open event device");

	// make format settings
	ioctl(Framebuffer, FBIOGET_FSCREENINFO, &fbfixscreeninfo);
	ioctl(Framebuffer, FBIOGET_VSCREENINFO, &oldscreeninfo);
snprintf(buf, 256, "Original resolution: %d x %d\nARGB%d%d%d%d\n",oldscreeninfo.xres,oldscreeninfo.yres,
		oldscreeninfo.transp.length,oldscreeninfo.red.length,oldscreeninfo.green.length,oldscreeninfo.blue.length);
		os::Printer::log(buf);
	memcpy(&fbscreeninfo, &oldscreeninfo, sizeof(struct fb_var_screeninfo));
	if (CreationParams.DriverType != video::EDT_NULL)
	{
		fbscreeninfo.xres = fbscreeninfo.xres_virtual = CreationParams.WindowSize.Width;
		fbscreeninfo.yres = fbscreeninfo.yres_virtual = CreationParams.WindowSize.Height;
		fbscreeninfo.bits_per_pixel = 16;
		fbscreeninfo.red.offset = 10;
		fbscreeninfo.red.length = 5;
		fbscreeninfo.green.offset = 5;
		fbscreeninfo.green.length = 5;
		fbscreeninfo.blue.offset = 0;
		fbscreeninfo.blue.length = 5;
		fbscreeninfo.transp.offset = 15;
		fbscreeninfo.transp.length = 1;
		ioctl(Framebuffer, FBIOPUT_VSCREENINFO, &fbscreeninfo);
		ioctl(Framebuffer, FBIOGET_VSCREENINFO, &fbscreeninfo);

snprintf(buf, 256, "New resolution: %d x %d (%d x %d)\nARGB%d%d%d%d\n",fbscreeninfo.xres,fbscreeninfo.yres,fbscreeninfo.xres_virtual,fbscreeninfo.yres_virtual,
		fbscreeninfo.transp.length,fbscreeninfo.red.length,fbscreeninfo.green.length,fbscreeninfo.blue.length);
		os::Printer::log(buf);

		CreationParams.WindowSize.Width = fbscreeninfo.xres;
		CreationParams.WindowSize.Height = fbscreeninfo.yres;
		CreationParams.Bits = fbscreeninfo.bits_per_pixel;
		Pitch = fbfixscreeninfo.line_length;
		if (fbscreeninfo.bits_per_pixel == 16)
		{
			if (fbscreeninfo.transp.length == 0)
				FBColorFormat = video::ECF_R5G6B5;
			else
				FBColorFormat = video::ECF_A1R5G5B5;
		}
		else
		{
			if (fbscreeninfo.transp.length == 0)
				FBColorFormat = video::ECF_R8G8B8;
			else
				FBColorFormat = video::ECF_A8R8G8B8;
		}
		if (MAP_FAILED==(SoftwareImage=(u8*)mmap(0, CreationParams.WindowSize.Height*Pitch, PROT_READ|PROT_WRITE, MAP_SHARED, Framebuffer, 0)))
		{
			perror("mmap render target");
			return false;
		}
	}
	return true;
}
Example #17
0
// "If one maps a file with MAP_SHARED(part = 0) or MAP_PRIVATE(part = 1)
// and then writes to the mapped memory, is that update visible when
// accessing the file through the traditional lseek(2)/read(2) system calls?"
void bc(int part)
{
	int fd;
	struct stat st;
	int status;
	char *fileName = "test.txt";
	char *addr;

	char *beforeWrite, *afterWrite;

	openStatFile(&fd, fileName, &st);

	switch(part)
	{
		case 0: //Execute Part B
			fprintf(stderr, "Part B:\n");
			addr = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
			break;
		case 1: //Execute Part C
			fprintf(stderr, "Part C:\n");
			addr = mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
			break;
	}

	if (addr == MAP_FAILED)
	{
		fprintf(stderr, "Error mapping file into memory: %s\n", strerror(errno));
		exit(1);
	}

	beforeWrite = (char*)malloc(strlen(addr));
	if (!beforeWrite)
	{
		fprintf(stderr, "Error occurred allocating memory.\n");
		exit(1);
	}
	strcpy(beforeWrite, addr);

	fprintf(stderr, "Contents of mapped memory before write:\n%s\n", addr);
	fprintf(stderr, "Now writing to the mapped memory...\n");
	sprintf(addr, "Hello!");
	afterWrite = (char*)malloc(strlen(addr));
	if (!afterWrite)
	{
		fprintf(stderr, "Error occurred allocating memory.\n");
		exit(1);
	}
	fprintf(stderr, "Contents of mapped memory after write:\n");

	strcpy(afterWrite, readFile(fd, strlen(addr)));
	fprintf(stderr, "%s\n", afterWrite);

	if(strcmp(beforeWrite,afterWrite) == 0)
	{
		fprintf(stderr, "The update is not visible when accessing the file\n");
		fprintf(stderr, "through traditional lseek(2)/read(2) system calls.\n");
	}
	else
	{
		fprintf(stderr, "The update is visible when accessing the file through\n");
		fprintf(stderr, "traditional lseek(2)/read(2) system calls.\n");
	}

	if(close(fd) < 0)
	{
		fprintf(stderr, "Error closing file: %s\n", strerror(errno));
		exit(1);
	}

	return;
}
Example #18
0
void *
hwloc_alloc_mmap(hwloc_topology_t topology __hwloc_attribute_unused, size_t len)
{
    return mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
}
Example #19
0
File: OSMem.c Project: kod3r/ghc
static void *
my_mmap (void *addr, W_ size)
{
    void *ret;

#if defined(solaris2_HOST_OS) || defined(irix_HOST_OS)
    { 
        int fd = open("/dev/zero",O_RDONLY);
        ret = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
        close(fd);
    }
#elif hpux_HOST_OS
    ret = mmap(addr, size, PROT_READ | PROT_WRITE, 
               MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
#elif darwin_HOST_OS
    // Without MAP_FIXED, Apple's mmap ignores addr.
    // With MAP_FIXED, it overwrites already mapped regions, whic
    // mmap(0, ... MAP_FIXED ...) is worst of all: It unmaps the program text
    // and replaces it with zeroes, causing instant death.
    // This behaviour seems to be conformant with IEEE Std 1003.1-2001.
    // Let's just use the underlying Mach Microkernel calls directly,
    // they're much nicer.
    
    kern_return_t err = 0;
    ret = addr;
    if(addr)    // try to allocate at address
        err = vm_allocate(mach_task_self(),(vm_address_t*) &ret, size, FALSE);
    if(!addr || err)    // try to allocate anywhere
        err = vm_allocate(mach_task_self(),(vm_address_t*) &ret, size, TRUE);
        
    if(err) {
        // don't know what the error codes mean exactly, assume it's
        // not our problem though.
        errorBelch("memory allocation failed (requested %" FMT_Word " bytes)", size);
        stg_exit(EXIT_FAILURE);
    } else {
        vm_protect(mach_task_self(),(vm_address_t)ret,size,FALSE,VM_PROT_READ|VM_PROT_WRITE);
    }
#elif linux_HOST_OS
    ret = mmap(addr, size, PROT_READ | PROT_WRITE,
               MAP_ANON | MAP_PRIVATE, -1, 0);
    if (ret == (void *)-1 && errno == EPERM) {
        // Linux may return EPERM if it tried to give us
        // a chunk of address space below mmap_min_addr,
        // See Trac #7500.
        if (addr != 0) {
            // Try again with no hint address.
            // It's not clear that this can ever actually help,
            // but since our alternative is to abort, we may as well try.
            ret = mmap(0, size, PROT_READ | PROT_WRITE,
                       MAP_ANON | MAP_PRIVATE, -1, 0);
        }
        if (ret == (void *)-1 && errno == EPERM) {
            // Linux is not willing to give us any mapping,
            // so treat this as an out-of-memory condition
            // (really out of virtual address space).
            errno = ENOMEM;
        }
    }
#else
    ret = mmap(addr, size, PROT_READ | PROT_WRITE, 
               MAP_ANON | MAP_PRIVATE, -1, 0);
#endif

    if (ret == (void *)-1) {
        if (errno == ENOMEM || 
            (errno == EINVAL && sizeof(void*)==4 && size >= 0xc0000000)) {
            // If we request more than 3Gig, then we get EINVAL
            // instead of ENOMEM (at least on Linux).
            errorBelch("out of memory (requested %" FMT_Word " bytes)", size);
            stg_exit(EXIT_FAILURE);
        } else {
            barf("getMBlock: mmap: %s", strerror(errno));
        }
    }

    return ret;
}
Example #20
0
int main(int argc, char *argv[]) {
	unsigned long long num_nodes, ram_size;
	unsigned long num_forks = 1;
	struct sysinfo info;
	void *shm;
	int *cond;
	struct sigaction zig;
	int c, add_wait = -1, is_parent = 1;
#ifdef __cpu_set_t_defined
	int affinity = 0;
	cpu_set_t my_cpu_mask;
#endif

	/* By default we'll use 1/16th of total RAM, rounded
	 * down to the nearest page. */
	if (sysinfo(&info) != 0) {
		perror("sysinfo");
		return 1;
	}

	ram_size = info.totalram / 16;
	ram_size = ram_size & ~(getpagesize() - 1);
	num_nodes = ram_size / sizeof(void *);

	/* Parse command line args */
	while ( (c = getopt(argc, argv, "a:p:n:d:s:t")) != -1) {
		switch (c) {
			case 'p':
				num_forks = atoi(optarg);
				break;
			case 'd':
				ram_size = info.totalram / atoi(optarg);
				ram_size = ram_size & ~(getpagesize() - 1);
				num_nodes = ram_size / sizeof(void *);
				break;
			case 'n':
				num_nodes = atoi(optarg);
				ram_size = num_nodes * sizeof(void *);
				break;
			case 's':
				report_interval = atoi(optarg);
				break;
			case 'a':
				add_wait = atoi(optarg);
				break;
#ifdef __cpu_set_t_defined
			case 't':
				affinity = 1;
				break;
#endif
			default:
				print_help(argv[0]);
				return 0;
		}
	}

	/* Will we exceed half the address space size?  Use 1/4 of it at most.  */
	if (ram_size > ((unsigned long long)1 << ((sizeof(void *) * 8) - 1))) {
		printf("Was going to use %lluKB (%llu nodes) but that's too big.\n",
			ram_size / 1024, num_nodes);
		ram_size = ((unsigned long long)1 << (sizeof(void *) * 8));
		ram_size /= 4;
		num_nodes = ram_size / sizeof(void *);
		printf("Clamping to %lluKB (%llu nodes) instead.\n",
			ram_size / 1024, num_nodes);
	}

	/* Talk about what we're going to do. */
	printf("Going to use %lluKB (%llu nodes).\n", ram_size / 1024,
		num_nodes);
	
	/* Make a shared anonymous map of the RAM */
	shm = mmap(NULL, ram_size, PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	if (shm == MAP_FAILED) {
		perror("mmap");
		return 2;
	}
	printf("mmap region: %p (%llu nodes)\n", shm, num_nodes);

	/* Create an SHM condition variable.  Bogus, I know... */
	cond = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE,
		MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	if (cond == MAP_FAILED) {
		perror("mmap");
		return 4;
	}
	*cond = 1;

	/* Create a "graph" by populating it with random pointers. */
	printf("Populating nodes...");
	fflush(stdout);
	populate_graph(shm, num_nodes);
	printf("done.\n");

	printf("Creating %lu processes with reports every %lu seconds \
and %d seconds between adding children.\n",
		num_forks, report_interval, add_wait);

	/* Fork off separate processes.  The shared region is shared
	 * across all children.  If we only wanted one thread, we shouldn't
	 * fork anything.  Note that the "cond" mmap is a really crappy
	 * condition variable kludge that works well enough for HERE ONLY. */
	for (c = (add_wait >= 0 ? 0 : 1); c < num_forks; c++) {
		/* Child should wait for the condition and then break. */
		if (!fork()) {
#ifdef __cpu_set_t_defined
			if (affinity) {
				CPU_ZERO(&my_cpu_mask);
				CPU_SET(c, &my_cpu_mask);
				if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) {
					perror("sched_setaffinity");
				}
			}
#endif

			is_parent = 0;
			while (*cond) {
				usleep(10000);
			}
			break;
		}
	}
	if (is_parent) {
#ifdef __cpu_set_t_defined
		if (affinity) {
			CPU_ZERO(&my_cpu_mask);
			CPU_SET(0, &my_cpu_mask);
			if (0 != sched_setaffinity(0,sizeof(cpu_set_t), &my_cpu_mask)) {
				perror("sched_setaffinity");
			}
		}
#endif
		printf("All threads created.  Launching!\n");
		*cond = 0;
	}

	/* now start the work */
	if (!is_parent) {
start_thread:
		/* Set up the alarm handler to print speed info. */
		memset(&zig, 0x00, sizeof(zig));
		zig.sa_handler = alarm_func;
		sigaction(SIGALRM, &zig, NULL);
		gettimeofday(&last, NULL);
		alarm(report_interval);

		/* Walk the graph. */
		walk_graph(shm);

		/* This function never returns */
	} else {
		/* Start the ramp-up.  The children will never die,
		 * so we don't need to wait() for 'em.
		 */
		while (add_wait != -1) {
			sleep(add_wait);
			if (fork() == 0) {
				/* goto is cheesy, but works. */
				goto start_thread;
			} else {
				printf("Added thread.\n");
			}
		}
		goto start_thread;
	}
	
	return 0;
}
Example #21
0
int
main(int argc, char *argv[])
{
	struct stat sb;
	int ch, fd, match;
	wchar_t termchar;
	unsigned char *back, *front;
	unsigned const char *file;
	wchar_t *key;

	(void) setlocale(LC_CTYPE, "");

	file = _path_words;
	termchar = L'\0';
	while ((ch = getopt(argc, argv, "dft:")) != -1)
		switch(ch) {
		case 'd':
			dflag = 1;
			break;
		case 'f':
			fflag = 1;
			break;
		case 't':
			if (mbrtowc(&termchar, optarg, MB_LEN_MAX, NULL) !=
			    strlen(optarg))
				errx(2, "invalid termination character");
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc == 0)
		usage();
	if (argc == 1) 			/* But set -df by default. */
		dflag = fflag = 1;
	key = prepkey(*argv++, termchar);
	if (argc >= 2)
		file = *argv++;

	match = 1;

	do {
		if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
			err(2, "%s", file);
		if ((uintmax_t)sb.st_size > (uintmax_t)SIZE_T_MAX)
			errx(2, "%s: %s", file, strerror(EFBIG));
		if (sb.st_size == 0) {
			close(fd);
			continue;
		}
		if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
			err(2, "%s", file);
		back = front + sb.st_size;
		match *= (look(key, front, back));
		close(fd);
	} while (argc-- > 2 && (file = *argv++));

	exit(match);
}
int imc_shm_mmap(size_t   region_size,
                 int      prot,
                 int      flags,
                 int      off,
                 int      expect_creation_failure,
                 int      map_view)
{
  int   d;
  void  *addr;
  char  *mem;
  int   i;
  int   diff_count;

  if (verbosity > 0) {
    printf("imc_shm_mmap(0x%x, 0x%x, 0x%x, 0x%x, %d, %d)\n",
           region_size, prot, flags, off,
           expect_creation_failure, map_view);
  }
  if (verbosity > 1) {
    printf("basic imc mem obj creation\n");
  }
  d = imc_mem_obj_create(region_size);
  if (expect_creation_failure) {
    if (-1 != d) {
      fprintf(stderr,
              ("imc_shm_mmap: expected failure to create"
               " IMC shm object, but got %d\n"),
              d);
      (void) close(d);
      return 1;
    }
    return 0;
  }
  if (-1 == d) {
    fprintf(stderr,
            ("imc_shm_mmap: could not create an IMC shm object"
             " of size %d (0x%x)\n"),
            region_size, region_size);
    return 1;
  }
  if (verbosity > 1) {
    printf("basic mmap functionality\n");
  }
  addr = mmap((void *) 0, region_size, prot, flags, d, off);
  if (MAP_FAILED == addr) {
    fprintf(stderr, "imc_shm_mmap: mmap failed, errno %d\n", errno);
    return 1;
  }

  /* Check that the region is zero-initialised. */
  mem = (char *) addr;
  diff_count = 0;
  if (verbosity > 1) {
    printf("initial zero content check\n");
  }
  for (i = 0; i < region_size; ++i) {
    if (0 != mem[i]) {
      if (i >= verbosity) {
        printf("imc_shm_mmap: check_contents, byte %d not zero\n", i);
      }
      ++diff_count;
    }
  }
  if (0 != diff_count) {
    munmap(addr, region_size);
    (void) close(d);
    return diff_count;
  }

  if (map_view && 0 != (prot & PROT_WRITE)) {
    void  *addr2;
    int   i;
    int   diff_count;
    char  *mem1;
    char  *mem2;

    if (verbosity > 1) {
      printf("coherent mapping test\n");
    }

    addr2 = mmap((void *) 0, region_size, prot, flags, d, off);
    if (MAP_FAILED == addr2) {
      fprintf(stderr,
              "imc_shm_mmap: 2nd map view mapping failed, errno %d\n", errno);
      return 1;
    }
    for (diff_count = 0, mem1 = (char *) addr, mem2 = (char *) addr2, i = 0;
         i < region_size; ++i) {
      mem1[i] = i;
      if ((0xff & i) != (0xff & mem2[i])) {
        if (i >= verbosity) {
          printf(("imc_shm_mmap: map_view: write to byte %d not coherent"
                  " wrote 0x%02x, got 0x%02x\n"), i, i, mem2[i]);
        }
        ++diff_count;
      }
    }
    if (0 != diff_count) {
      fprintf(stderr, "imc_shm_mmap: map_view: incoherent mapping!\n");
      return diff_count;
    }
  }

  if (0 != close(d)) {
    fprintf(stderr, "imc_shm_mmap: close on IMC shm desc failed\n");
    return 1;
  }
  return 0;
}
Example #23
0
int main(int argc, char *argv[])
{
    int i;
    int fd;
    int result;
    int *map;  /* mmapped array of int's */

    /* Open a file for writing.
     *  - Creating the file if it doesn't exist.
     *  - Truncating it to 0 size if it already exists. (not really needed)
     *
     * Note: "O_WRONLY" mode is not sufficient when mmaping.
     */
    fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
    if (fd == -1) {
	perror("Error opening file for writing");
	exit(EXIT_FAILURE);
    }

    /* Stretch the file size to the size of the (mmapped) array of ints
     */
    result = lseek(fd, FILESIZE-1, SEEK_SET);
    if (result == -1) {
	close(fd);
	perror("Error calling lseek() to 'stretch' the file");
	exit(EXIT_FAILURE);
    }
    
    /* Something needs to be written at the end of the file to
     * have the file actually have the new size.
     * Just writing an empty string at the current file position will do.
     *
     * Note:
     *  - The current position in the file is at the end of the stretched 
     *    file due to the call to lseek().
     *  - An empty string is actually a single '\0' character, so a zero-byte
     *    will be written at the last byte of the file.
     */
    result = write(fd, "", 1);
    if (result != 1) {
	close(fd);
	perror("Error writing last byte of the file");
	exit(EXIT_FAILURE);
    }

    /* Now the file is ready to be mmapped.
     */
    map = mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (map == MAP_FAILED) {
	close(fd);
	perror("Error mmapping the file");
	exit(EXIT_FAILURE);
    }
    
    /* Now write int's to the file as if it were memory (an array of ints).
     */
    for (i = 1; i <=NUMINTS; ++i) {
	map[i] = 2 * i; 
    }

    /* Don't forget to free the mmapped memory
     */
    if (munmap(map, FILESIZE) == -1) {
	perror("Error un-mmapping the file");
	/* Decide here whether to close(fd) and exit() or not. Depends... */
    }

    /* Un-mmaping doesn't close the file, so we still need to do that.
     */
    close(fd);
    return 0;
}
int main(void){
	
	int 		i, psb_check, dip_check, counter,Data;
	int 		buttons_value = 0;
	int 		switch_value = 0;
	int 		fd;
	void 		*ptr_buttons,*ptr_switch,*ptr_gray,*ptr_led;
	unsigned 	page_addr_buttons,page_addr_switch,page_addr_gray,page_addr_led;
	unsigned	page_offset_buttons,page_offset_switch,page_offset_gray,page_offset_led;
	unsigned 	page_size = sysconf(_SC_PAGESIZE);
	
	fd = open("/dev/mem",O_RDWR);

	page_addr_buttons	= (BUTTONS_BASE_ADDR & ~(page_size-1));
	page_offset_buttons	= BUTTONS_BASE_ADDR - page_addr_buttons;

	page_addr_switch	= (SWITCH_BASE_ADDR & ~(page_size-1));
	page_offset_switch	= SWITCH_BASE_ADDR - page_addr_switch;

	page_addr_gray		= (GRAY_BASE_ADDR & ~(page_size-1));
	page_offset_gray	= GRAY_BASE_ADDR - page_addr_gray;

	page_addr_led		= (LEDS_BASE_ADDR & ~(page_size-1));
	page_offset_led		= LEDS_BASE_ADDR - page_addr_led;

	
	ptr_buttons = mmap(NULL,page_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(BUTTONS_BASE_ADDR & ~(page_size-1)));
	ptr_switch 	= mmap(NULL,page_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(SWITCH_BASE_ADDR & ~(page_size-1)));
	ptr_gray 	= mmap(NULL,page_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(GRAY_BASE_ADDR & ~(page_size-1)));
	ptr_led 	= mmap(NULL,page_size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(LEDS_BASE_ADDR & ~(page_size-1)));
	
	
	while (1)
   	{ 
		buttons_value = *((unsigned *)(ptr_buttons+page_offset_buttons));		
		fprintf(stdout,"Buttons Value %d\n", buttons_value);

		if(buttons_value == 0)
			  	Data = 0;
		else if(buttons_value == 2)
		  	  	Data = 1;
		else if(buttons_value == 16)
		  	 	Data = 2;
		else	Data = 3;
		

		fprintf(stdout,"Data: %d\n", Data);

		//GRAY_COUNTER_mWriteReg(XPAR_GRAY_COUNTER_S_AXI_BASEADDR, 0, Data);
		*((unsigned *)(ptr_gray+page_offset_gray))= Data;
		
		counter = *((unsigned *)(ptr_gray+page_offset_gray+4));

		fprintf(stdout,"Counter Status %d\n", counter);
		// output dip switches value on LED_ip device
		//LED_IP_mWriteReg(XPAR_LED_IP_S_AXI_BASEADDR, 0, counter);
		*((unsigned *)(ptr_led+page_offset_led)) = counter;


		for (i=0; i<9999999; i++);
   }	
	
	return 0;
}
static void test_mmap_wrong_magic_keyset (const char * tmpFile)
{
	// first write a mmap file
	{
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = simpleTestKeySet ();
		succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 1, "kdbSet was not successful");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}

	// now manipulate magic keyset inside the mapped region
	FILE * fp;
	if ((fp = fopen (tmpFile, "r+")) == 0)
	{
		yield_error ("fopen() error");
	}
	struct stat sbuf;
	if (stat (tmpFile, &sbuf) == -1)
	{
		yield_error ("stat() error");
	}

	int fd = fileno (fp);
	char * mappedRegion = mmap (0, sbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (mappedRegion == MAP_FAILED)
	{
		ELEKTRA_LOG_WARNING ("error mapping file %s\nmmapSize: " ELEKTRA_STAT_ST_SIZE_F, tmpFile, sbuf.st_size);
		yield_error ("mmap() error");
		return;
	}
	if (fp)
	{
		fclose (fp);
	}

	KeySet * magicKs = (KeySet *) (mappedRegion + sizeof (MmapHeader));
	magicKs->size = 1234; // magic keyset contains SIZE_MAX here

	if (msync ((void *) mappedRegion, sbuf.st_size, MS_SYNC) != 0)
	{
		yield_error ("msync() error");
		return;
	}

	if (munmap (mappedRegion, sbuf.st_size) != 0)
	{
		yield_error ("munmap() error");
		return;
	}

	// manipulated magic keyset should be detected now
	{
		// we expect an error here
		Key * parentKey = keyNew (TEST_ROOT_KEY, KEY_VALUE, tmpFile, KEY_END);
		KeySet * conf = ksNew (0, KS_END);
		PLUGIN_OPEN ("mmapstorage");

		KeySet * ks = ksNew (0, KS_END);
		succeed_if (plugin->kdbGet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
			    "kdbGet did not detect wrong magic keyset");

		keyDel (parentKey);
		ksDel (ks);
		PLUGIN_CLOSE ();
	}
}
Example #26
0
static int config(uint32_t width, uint32_t height, uint32_t d_width,
                  uint32_t d_height, uint32_t flags, char *title,
                  uint32_t format)
{
  struct fb_fix_screeninfo fb_finfo;
  uint32_t black = 0x00800080;
  long temp;
  int vt_fd;

  fs = flags & VOFLAG_FULLSCREEN;

  if (pre_init_err == -2) {
    mp_msg(MSGT_VO, MSGL_ERR, "Internal fatal error: config() was called before preinit()\n");
    return -1;
  }

  if (pre_init_err)
    return 1;

  in_width  = width;
  in_height = height;

  out_width  = (d_width && fs) ? d_width  : width;
  out_height = (d_width && fs) ? d_height : height;

  fb_vinfo.xres_virtual = fb_vinfo.xres;
  fb_vinfo.yres_virtual = fb_vinfo.yres;

  if (fb_tty_fd >= 0 && ioctl(fb_tty_fd, KDSETMODE, KD_GRAPHICS) < 0) {
    mp_msg(MSGT_VO, MSGL_V, "Can't set graphics mode: %s\n", strerror(errno));
    close(fb_tty_fd);
    fb_tty_fd = -1;
  }

  if (ioctl(fb_dev_fd, FBIOPUT_VSCREENINFO, &fb_vinfo)) {
    mp_msg(MSGT_VO, MSGL_ERR, "Can't put VSCREENINFO: %s\n", strerror(errno));
    if (fb_tty_fd >= 0 && ioctl(fb_tty_fd, KDSETMODE, KD_TEXT) < 0) {
      mp_msg(MSGT_VO, MSGL_ERR, "Can't restore text mode: %s\n", strerror(errno));
    }
    return 1;
  }

  fb_pixel_size = 2;

  if (fs) {
    out_width  = fb_vinfo.xres;
    out_height = fb_vinfo.yres;
  }
  if (out_width < in_width || out_height < in_height) {
    mp_msg(MSGT_VO, MSGL_ERR, "screensize is smaller than video size\n");
    return 1;
  }

  if (ioctl(fb_dev_fd, FBIOGET_FSCREENINFO, &fb_finfo)) {
    mp_msg(MSGT_VO, MSGL_ERR, "Can't get FSCREENINFO: %s\n", strerror(errno));
    return 1;
  }

  if (fb_finfo.type != FB_TYPE_PACKED_PIXELS) {
    mp_msg(MSGT_VO, MSGL_ERR, "type %d not supported\n", fb_finfo.type);
    return 1;
  }

  fb_line_len = fb_finfo.line_length;
  fb_size     = fb_finfo.smem_len;

  frame_buffer = (uint8_t *) mmap(0, fb_size, PROT_READ | PROT_WRITE,
                                  MAP_SHARED, fb_dev_fd, 0);
  if (frame_buffer == (uint8_t *) -1) {
    mp_msg(MSGT_VO, MSGL_ERR, "Can't mmap %s: %s\n", fb_dev_name, strerror(errno));
    return 1;
  }

  center = frame_buffer +
    ((out_width - in_width) / 2) * fb_pixel_size +
    ((out_height - in_height) / 2) * fb_line_len;

  mp_msg(MSGT_VO, MSGL_DBG2, "frame_buffer @ %p\n", frame_buffer);
  mp_msg(MSGT_VO, MSGL_DBG2, "center @ %p\n", center);
  mp_msg(MSGT_VO, MSGL_V, "pixel per line: %d\n", fb_line_len / fb_pixel_size);

  /* blanking screen */
  for (temp = 0; temp < fb_size; temp += 4)
    memcpy(frame_buffer + temp, (void *) &black, 4);

  if (vt_doit && (vt_fd = open("/dev/tty", O_WRONLY)) == -1) {
    mp_msg(MSGT_VO, MSGL_ERR, "can't open /dev/tty: %s\n", strerror(errno));
    vt_doit = 0;
  }
  if (vt_doit && !(vt_fp = fdopen(vt_fd, "w"))) {
    mp_msg(MSGT_VO, MSGL_ERR, "can't fdopen /dev/tty: %s\n", strerror(errno));
    vt_doit = 0;
  }

  if (vt_doit)
    vt_set_textarea((out_height + in_height) / 2, fb_vinfo.yres);

  return 0;
}
Example #27
0
int main(int argc, char *argv[])
{
    if(argc==1) usage(argv[0]);

    LibRaw RawProcessor;
    int i,arg,c,ret;
    char opm,opt,*cp,*sp;
    int use_bigfile=0, use_timing=0,use_mem=0;
#ifndef WIN32
    int msize = 0,use_mmap=0;
    
#endif
	void *iobuffer=0;
#ifdef OUT
#undef OUT
#endif

#define OUT RawProcessor.imgdata.params
    
        argv[argc] = (char*)"";
        for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) 
          {
            char *optstr = argv[arg];
            opt = argv[arg++][1];
            if ((cp = strchr (sp=(char*)"cnbrkStqmHABCgU", opt))!=0)
              for (i=0; i < "111411111144221"[cp-sp]-'0'; i++)
                if (!isdigit(argv[arg+i][0]) && !optstr[2]) 
                  {
                    fprintf (stderr,"Non-numeric argument to \"-%c\"\n", opt);
                    return 1;
                  }
            if(!strchr("ftdeam",opt) && argv[arg-1][2])
              fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
            switch (opt) 
              {
              case 'v':  verbosity++;  break;
              case 'G':  OUT.green_matching = 1; break;
              case 'c':  OUT.adjust_maximum_thr   = (float)atof(argv[arg++]);  break;
              case 'U':  OUT.auto_bright_thr   = (float)atof(argv[arg++]);  break;
              case 'n':  OUT.threshold   = (float)atof(argv[arg++]);  break;
              case 'b':  OUT.bright      = (float)atof(argv[arg++]);  break;
              case 'P':  OUT.bad_pixels  = argv[arg++];        break;
              case 'K':  OUT.dark_frame  = argv[arg++];        break;
              case 'r':
                for(c=0;c<4;c++) 
                  OUT.user_mul[c] = (float)atof(argv[arg++]);  
                break;
              case 'C':  
                OUT.aber[0] = 1 / atof(argv[arg++]);
                OUT.aber[2] = 1 / atof(argv[arg++]);  
                break;
              case 'g':  
                OUT.gamm[0] = 1 / atof(argv[arg++]);
                OUT.gamm[1] =     atof(argv[arg++]);  
                break;
              case 'k':  OUT.user_black  = atoi(argv[arg++]);  break;
              case 'S':  OUT.user_sat    = atoi(argv[arg++]);  break;
              case 'R':  OUT.raw_processing_options = atoi(argv[arg++]);  break;
              case 't':  
                if(!strcmp(optstr,"-timing"))
                  use_timing=1;
                else if(!argv[arg-1][2])
                  OUT.user_flip   = atoi(argv[arg++]);  
                else
                  fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                break;
              case 'q':  OUT.user_qual   = atoi(argv[arg++]);  break;
              case 'm':
#ifndef WIN32
                if(!strcmp(optstr,"-mmap"))
                  use_mmap              = 1;
                else
#endif
                  if(!strcmp(optstr,"-mem"))
                    use_mem              = 1;
                  else
                    {
                      if(!argv[arg-1][2])
                        OUT.med_passes  = atoi(argv[arg++]);  
                      else
                        fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                    }
                break;
              case 'H':  OUT.highlight   = atoi(argv[arg++]);  break;
              case 's':  OUT.shot_select = abs(atoi(argv[arg++])); break;
              case 'o':  
                if(isdigit(argv[arg][0]) && !isdigit(argv[arg][1]))
                  OUT.output_color = atoi(argv[arg++]);
#ifndef NO_LCMS
                else
                  OUT.output_profile = argv[arg++];
                break;
              case 'p':  OUT.camera_profile = argv[arg++];
#endif
                break;
              case 'h':  
                OUT.half_size         = 1;		
                break;
              case 'f':  
                if(!strcmp(optstr,"-fbdd"))
                  OUT.fbdd_noiserd = atoi(argv[arg++]);
                else
                  {
                    if(!argv[arg-1][2])    
                      OUT.four_color_rgb    = 1;  
                    else
                      fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                  }
                break;
              case 'A':  for(c=0; c<4;c++) OUT.greybox[c]  = atoi(argv[arg++]); break;
              case 'B':  for(c=0; c<4;c++) OUT.cropbox[c]  = atoi(argv[arg++]); break;
              case 'a':
                if(!strcmp(optstr,"-aexpo"))			  
                  {
                    OUT.exp_correc = 1;
                    OUT.exp_shift = (float)atof(argv[arg++]);
                    OUT.exp_preser = (float)atof(argv[arg++]);
                  }	
                else
#ifdef LIBRAW_DEMOSAIC_PACK_GPL3
                  if(!strcmp(optstr,"-acae")) 
                    {
                      OUT.ca_correc = 1;
                      OUT.cared       = (float)atof(argv[arg++]);
                      OUT.cablue      = (float)atof(argv[arg++]);
                    }
                  else if(!strcmp(optstr,"-aline"))			  
                    {
                      OUT.cfaline = 1;
                      OUT.linenoise = (float)atof(argv[arg++]);
                    }	
                  else if(!strcmp(optstr,"-aclean"))			  
                    {
                      OUT.cfa_clean = 1;
                      OUT.lclean = (float)atof(argv[arg++]);
                      OUT.cclean = (float)atof(argv[arg++]);
                    }								  
                  else if(!strcmp(optstr,"-agreen"))			  
                    {
                      OUT.cfa_green = 1;
                      OUT.green_thresh =(float)atof(argv[arg++]);
                    }								  
                  else
#endif
                    if(!argv[arg-1][2])    
                      OUT.use_auto_wb       = 1;  
                    else
                      fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                break;
              case 'w':  OUT.use_camera_wb     = 1;  break;
              case 'M':  OUT.use_camera_matrix = (opm == '+'); break;
              case 'j':  OUT.use_fuji_rotate   = 0;  break;
              case 'W':  OUT.no_auto_bright    = 1;  break;
              case 'T':  OUT.output_tiff       = 1;  break;
              case '4':  OUT.gamm[0] = OUT.gamm[1] =  OUT.no_auto_bright    = 1; /* no break here! */
              case '6':  OUT.output_bps = 16;  break;
              case 'F':  use_bigfile=1; break;
              case 'd':
                if(!strcmp(optstr,"-dcbi"))
                  OUT.dcb_iterations = atoi(argv[arg++]);
                else if(!strcmp(optstr,"-disars"))
                  OUT.use_rawspeed=0;
                else if(!strcmp(optstr,"-disadcf"))
                  OUT.force_foveon_x3f=1;
                else if(!strcmp(optstr,"-disinterp"))
                  OUT.no_interpolation=1;
                else if(!strcmp(optstr,"-dcbe"))
                  OUT.dcb_enhance_fl = 1;
                else if(!strcmp(optstr,"-dsrawrgb1"))
                  OUT.sraw_ycc = 1;
                else if(!strcmp(optstr,"-dsrawrgb2"))
                  OUT.sraw_ycc = 2;
                else if(!strcmp(optstr,"-dbnd"))
                  {
                    for(c=0; c<4; c++)
                      OUT.wf_deband_treshold[c] = (float)atof(argv[arg++]);
                    OUT.wf_debanding = 1;
                  }
                else
                  fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                break;
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
              case 'e':
                if(!strcmp(optstr,"-eeci"))
                  OUT.eeci_refine = 1;
                else if(!strcmp(optstr,"-esmed"))
                  OUT.es_med_passes = atoi(argv[arg++]);
                else
                  fprintf (stderr,"Unknown option \"%s\".\n",argv[arg-1]);
                break;
#endif
              default:
                fprintf (stderr,"Unknown option \"-%c\".\n", opt);
                return 1;
              }
          }
#ifndef WIN32
  putenv ((char*)"TZ=UTC"); // dcraw compatibility, affects TIFF datestamp field
#else
  _putenv ((char*)"TZ=UTC"); // dcraw compatibility, affects TIFF datestamp field
#endif
#define P1 RawProcessor.imgdata.idata
#define S RawProcessor.imgdata.sizes
#define C RawProcessor.imgdata.color
#define T RawProcessor.imgdata.thumbnail
#define P2 RawProcessor.imgdata.other

  if(verbosity>1)
    RawProcessor.set_progress_handler(my_progress_callback,(void*)"Sample data passed");
#ifdef LIBRAW_USE_OPENMP
  if(verbosity)
    printf ("Using %d threads\n", omp_get_max_threads());
#endif
  
  for ( ; arg < argc; arg++)
    {
      char outfn[1024];

      if(verbosity) printf("Processing file %s\n",argv[arg]);
            
      timerstart();
            
#ifndef WIN32
      if(use_mmap)
        {
          int file = open(argv[arg],O_RDONLY);
          struct stat st;
          if(file<0)
            {
              fprintf(stderr,"Cannot open %s: %s\n",argv[arg],strerror(errno));
              continue;
            }
          if(fstat(file,&st))
            {
              fprintf(stderr,"Cannot stat %s: %s\n",argv[arg],strerror(errno));
              close(file);
              continue;
            }
          int pgsz = getpagesize();
          msize = ((st.st_size+pgsz-1)/pgsz)*pgsz;
          iobuffer = mmap(NULL,msize,PROT_READ,MAP_PRIVATE,file,0);
          if(!iobuffer)
            {
              fprintf(stderr,"Cannot mmap %s: %s\n",argv[arg],strerror(errno));
              close(file);
              continue;
            }
          close(file);
          if( (ret = RawProcessor.open_buffer(iobuffer,st.st_size) != LIBRAW_SUCCESS))
            {
              fprintf(stderr,"Cannot open_buffer %s: %s\n",argv[arg],libraw_strerror(ret));
              continue; // no recycle b/c open file will recycle itself
            }

        }
      else
#endif
        if (use_mem)
          {
            int file = open(argv[arg],O_RDONLY|O_BINARY);
            struct stat st;
            if(file<0)
              {
                fprintf(stderr,"Cannot open %s: %s\n",argv[arg],strerror(errno));
                continue;
              }
            if(fstat(file,&st))
              {
                fprintf(stderr,"Cannot stat %s: %s\n",argv[arg],strerror(errno));
                close(file);
                continue;
              }
            if(!(iobuffer = malloc(st.st_size)))
              {
                fprintf(stderr,"Cannot allocate %d kbytes for memory buffer\n",(int)(st.st_size/1024));
                close(file);
                continue;
              }
            int rd;
            if(st.st_size!=(rd=read(file,iobuffer,st.st_size)))
              {
                fprintf(stderr,"Cannot read %d bytes instead of  %d to memory buffer\n",(int)rd,(int)st.st_size);
                close(file);
                free(iobuffer);
                continue;
              }
            close(file);
            if( (ret = RawProcessor.open_buffer(iobuffer,st.st_size)) != LIBRAW_SUCCESS)
              {
                fprintf(stderr,"Cannot open_buffer %s: %s\n",argv[arg],libraw_strerror(ret));
                free(iobuffer);
                continue; // no recycle b/c open file will recycle itself
              }
          }
        else
          {
            if(use_bigfile)
              // force open_file switch to bigfile processing
              ret = RawProcessor.open_file(argv[arg],1);
            else
              ret = RawProcessor.open_file(argv[arg]);
                        
            if( ret  != LIBRAW_SUCCESS)
              {
                fprintf(stderr,"Cannot open %s: %s\n",argv[arg],libraw_strerror(ret));
                continue; // no recycle b/c open_file will recycle itself
              }
          }

      if(use_timing)
        timerprint("LibRaw::open_file()",argv[arg]);


      timerstart();
      if( (ret = RawProcessor.unpack() ) != LIBRAW_SUCCESS)
        {
          fprintf(stderr,"Cannot unpack %s: %s\n",argv[arg],libraw_strerror(ret));
          continue;
        }

      if(use_timing)
        timerprint("LibRaw::unpack()",argv[arg]);

      timerstart();
      if (LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_process()))
        {
          fprintf(stderr,"Cannot do postpocessing on %s: %s\n",argv[arg],libraw_strerror(ret));
          if(LIBRAW_FATAL_ERROR(ret))
            continue; 
        }
      if(use_timing)
        timerprint("LibRaw::dcraw_process()",argv[arg]);

      snprintf(outfn,sizeof(outfn),
               "%s.%s",
               argv[arg], OUT.output_tiff ? "tiff" : (P1.colors>1?"ppm":"pgm"));

      if(verbosity)
        {
          printf("Writing file %s\n",outfn);
        }

      if( LIBRAW_SUCCESS != (ret = RawProcessor.dcraw_ppm_tiff_writer(outfn)))
        fprintf(stderr,"Cannot write %s: %s\n",outfn,libraw_strerror(ret));

#ifndef WIN32
      if(use_mmap && iobuffer)
        {
          munmap(iobuffer,msize);
          iobuffer=0;
        }
#endif
      else if(use_mem && iobuffer)
        {
          free(iobuffer);
          iobuffer = 0;
        }
            
      RawProcessor.recycle(); // just for show this call
    }
  return 0;
}
Example #28
0
// application entry point
int main(int argc, char* argv[])
{
    int fbfd = 0; // framebuffer filedescriptor
    struct fb_var_screeninfo orig_var_info;
    struct fb_var_screeninfo var_info;
    struct fb_fix_screeninfo fix_info;
    char *fbp = 0; // framebuffer memory pointer

    // Open the framebuffer device file for reading and writing
    fbfd = open("/dev/fb0", O_RDWR);
    if (!fbfd) {
        printf("Error: cannot open framebuffer device.\n");
        return(1);
    }
    //printf("The framebuffer device opened.\n");

    // hide cursor
    char *kbfds = "/dev/tty";
    int kbfd = open(kbfds, O_WRONLY);
    if (kbfd >= 0) {
        ioctl(kbfd, KDSETMODE, KD_GRAPHICS);
    }
    else {
        printf("Could not open %s.\n", kbfds);
    }

    // Get original variable screen information
    if (ioctl(fbfd, FBIOGET_VSCREENINFO, &var_info)) {
        printf("Error reading variable screen info.\n");
    }
    //printf("Original info %dx%d, %dbpp\n", var_info.xres, var_info.yres, var_info.bits_per_pixel );

    // Store for resetting before exit
    memcpy(&orig_var_info, &var_info, sizeof(struct fb_var_screeninfo));

    // Set variable info
    var_info.xres = 320; //480; //320;
    var_info.yres = 240; //280; //240;
    var_info.xres_virtual = var_info.xres;
    var_info.yres_virtual = var_info.yres;
    var_info.bits_per_pixel = 8;
    var_info.xoffset = 0;
    var_info.yoffset = 0;
    if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &var_info)) {
        printf("Error setting variable screen info.\n");
    }

    // Get fixed screen information
    if (ioctl(fbfd, FBIOGET_FSCREENINFO, &fix_info)) {
        printf("Error reading fixed screen info.\n");
    }

    // Create palette
    unsigned short r[256]; // red
    unsigned short g[256]; // green
    unsigned short b[256]; // blue
    int i;
    for (i = 0; i < 256; i++) {
        if (i < 32) {
            r[i] = i * 7 << 8;
            g[i] = b[i] = 0;
        }
        else if (i < 64) {
            r[i] = 224 << 8;
            g[i] = (i - 32) * 4 << 8;
            b[i] = 0;
        }
        else if (i < 96) {
            r[i] = 224 + (i - 64) << 8;
            g[i] = 128 + (i - 64) * 3 << 8;
            b[i] = 0;
        }
        else {
            r[i] = g[i] = 255 << 8;
            b[i] = 128 << 8;
        }
    }
    struct fb_cmap palette;
    palette.start = 0;
    palette.len = 256;
    palette.red = r;
    palette.green = g;
    palette.blue = b;
    palette.transp = 0; // null == no transparency settings
    // Set palette
    if (ioctl(fbfd, FBIOPUTCMAP, &palette)) {
        printf("Error setting palette.\n");
    }

    // map fb to user mem 
    long int screensize = fix_info.smem_len;
    fbp = (char*)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0);
    if ((int)fbp == -1) {
        printf("Failed to mmap.\n");
    }
  
    if ((int)fbp != -1) {
        // Draw
        int maxx = var_info.xres - 1;
        int maxy = var_info.yres - 1;
        int n = 0, r, c, x, y;
        int c0, c1, c2;
        while (n++ < 200) {

            // seed
            for (x = 1; x < maxx; x++) {

                r = rand();
                c = (r % 4 == 0) ? 192 : 32;
                put_pixel(x, maxy, fbp, &var_info, c);
                if ((r % 4 == 0)) { // && (r % 3 == 0)) {
                    c = 2 * c / 3;
                    put_pixel(x - 1, maxy, fbp, &var_info, c);
                    put_pixel(x + 1, maxy, fbp, &var_info, c);
                }
            }

            // smooth
            for (y = 1; y < maxy - 1; y++) {
                for (x = 1; x < maxx; x++) {
                    c0 = get_pixel(x - 1, y, fbp, &var_info);
                    c1 = get_pixel(x, y + 1, fbp, &var_info);
                    c2 = get_pixel(x + 1, y, fbp, &var_info);
                    c = (c0 + c1 + c1 + c2) / 4;
                    put_pixel(x, y - 1, fbp, &var_info, c);
                }
            }

            // convect
            for (y = 0; y < maxy; y++) {
                for (x = 1; x < maxx; x++) {
                    c = get_pixel(x, y + 1, fbp, &var_info);
                    if (c > 0) c--;
                    put_pixel(x, y, fbp, &var_info, c);
                }
            }

            //usleep(100);
        }
    }

    // Cleanup
    // unmap the file from memory
    munmap(fbp, screensize);
    // reset palette
    palette.start = 0;
    palette.len = 16;
    palette.red = def_red;
    palette.green = def_green;
    palette.blue = def_blue;
    palette.transp = 0; // null == no transparency settings
    if (ioctl(fbfd, FBIOPUTCMAP, &palette)) {
        printf("Error setting palette.\n");
    }
    // reset the display mode
    if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &orig_var_info)) {
        printf("Error re-setting variable screen info.\n");
    }
    // close file  
    close(fbfd);
    // reset cursor
    if (kbfd >= 0) {
        ioctl(kbfd, KDSETMODE, KD_TEXT);
    }

    return 0;
}
Example #29
0
static int pdp_1394L_open(t_pdp_1394L *x, t_symbol *name)
{
  x->x_devicename = name->s_name;

  if(x->x_haveVideo){
    verbose(1, "Stream already going on. Doing some clean-up...");
    stopTransfer(x);
  }

  /*
  All of the errors in this method return -1 anyhow, so fd should be 0 to allow
  successful open if everything goes ok.

  Ico Bukvic [email protected] 2-18-07
  */
  int fd = 0; 
  struct dv1394_init init = {
    DV1394_API_VERSION, // api version 
    0x63,              // isochronous transmission channel
    N_BUF,             // number of frames in ringbuffer
    (x->x_norm==NTSC)?DV1394_NTSC:DV1394_PAL,         // PAL or NTSC
    //DV1394_PAL,         // PAL or NTSC
    0, 0 , 0                // default packet rate
  };

  x->x_framesize=(x->x_norm==NTSC)?DV1394_NTSC_FRAME_SIZE:DV1394_PAL_FRAME_SIZE;
  //x->x_framesize=DV1394_PAL_FRAME_SIZE;

  if(x->x_devicename){
    if ((fd = open(x->x_devicename, O_RDWR)) < 0) {
        perror(x->x_devicename);
        return -1;
    }
  } else {
    signed char devnum=(x->x_devicenum<0)?0:(signed char)x->x_devicenum;
    char buf[256];
    buf[255]=0;buf[32]=0;buf[33]=0;
    if (devnum<0)devnum=0;
    snprintf(buf, 32, "/dev/ieee1394/dv/host%d/%s/in", devnum, (x->x_norm==NTSC)?"NTSC":"PAL");
    //snprintf(buf, 32, "/dev/ieee1394/dv/host%d/%s/in", devnum, "PAL");
    if ((fd = open(buf, O_RDWR)) < 0)    {
      snprintf(buf, 32, "/dev/dv1394/%d", devnum);
      if ((fd = open(buf, O_RDWR)) < 0) {
	if ((fd=open("/dev/dv1394", O_RDWR)) < 0)    {
	  perror(buf);
	  return -1;
	}
      }
    }
  }
  if (ioctl(fd, DV1394_INIT, &init) < 0)    {
    perror("initializing");
    close(fd);
    return -1;
  }
  
  x->x_mmapbuf = (unsigned char *) mmap( NULL, N_BUF*x->x_framesize,
				       PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  if(x->x_mmapbuf == MAP_FAILED) {
    perror("mmap frame buffers");
    close(fd);
    return -1;
  }
  
  if(ioctl(fd, DV1394_START_RECEIVE, NULL)) {
    perror("dv1394 START_RECEIVE ioctl");
    close(fd);
    return -1;
  }
  /*Extra verbosity never hurt anyone...

  Ico Bukvic [email protected] 2-18-07
  */
  post("DV4L: Successfully opened...");
  startTransfer(x);
  x->dvfd=fd;

  return 1;
	
}
Example #30
0
int
elfts_compare_files(const char *rfn, const char *fn)
{
	int fd, result, rfd;
	struct stat sb, rsb;
	char *m, *rm;
	size_t c, nc;

	fd = rfd = -1;
	m = rm = NULL;
	result = TET_UNRESOLVED;

	if ((fd = open(fn, O_RDONLY, 0)) < 0) {
		tet_printf("U: open \"%s\" failed: %s.", fn,
		    strerror(errno));
		goto done;
	}

	if ((rfd = open(rfn, O_RDONLY, 0)) < 0) {
		tet_printf("U: open \"%s\" failed: %s.", rfn,
		    strerror(errno));
		goto done;
	}

	if (fstat(fd, &sb) < 0) {
		tet_printf("U: fstat \"%s\" failed: %s.", fn,
		    strerror(errno));
		goto done;
	}

	if (fstat(rfd, &rsb) < 0) {
		tet_printf("U: fstat \"%s\" failed: %s.", rfn,
		    strerror(errno));
		goto done;
	}

	if (sb.st_size != rsb.st_size) {
		tet_printf("F: refsz(%d) != target(%d).", rsb.st_size, sb.st_size);
		result = TET_FAIL;
		goto done;
	}

	if ((m = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, fd,
		 (off_t) 0)) == MAP_FAILED) {
		tet_printf("U: mmap \"%s\" failed: %s.", fn,
		    strerror(errno));
		goto done;
	}

	if ((rm = mmap(NULL, rsb.st_size, PROT_READ, MAP_SHARED, rfd,
		 (off_t) 0)) == MAP_FAILED) {
		tet_printf("U: mmap \"%s\" failed: %s.", rfn,
		    strerror(errno));
		goto done;
	}

	result = TET_PASS;
	nc = sb.st_size;

	/* Compare bytes. */
	for (c = 0; c < nc && *m == *rm; c++, m++, rm++)
		;
	if (c != nc) {
		tet_printf("F: @ offset 0x%x ref[%d] != actual[%d].", c,
		     *rm, *m);
		result = TET_FAIL;
	}

 done:
	if (m)
		(void) munmap(m, sb.st_size);
	if (rm)
		(void) munmap(rm, rsb.st_size);
	if (fd != -1)
		(void) close(fd);
	if (rfd != -1)
		(void) close(rfd);
	return (result);

}