コード例 #1
0
ファイル: kalloc.c プロジェクト: Aegisub/fftw3
void *X(kernel_malloc)(size_t n)
{
     void *p;

#if defined(MIN_ALIGNMENT)

#  if defined(WITH_OUR_MALLOC)
     p = our_malloc(n);
#    undef real_free
#    define real_free our_free

#  elif defined(__FreeBSD__) && (MIN_ALIGNMENT <= 16)
     /* FreeBSD does not have memalign, but its malloc is 16-byte aligned. */
     p = malloc(n);

#  elif (defined(__MACOSX__) || defined(__APPLE__)) && (MIN_ALIGNMENT <= 16)
     /* MacOS X malloc is already 16-byte aligned */
     p = malloc(n);

#  elif defined(HAVE_MEMALIGN)
     p = memalign(MIN_ALIGNMENT, n);

#  elif defined(HAVE_POSIX_MEMALIGN)
     /* note: posix_memalign is broken in glibc 2.2.5: it constrains
	the size, not the alignment, to be (power of two) * sizeof(void*).
        The bug seems to have been fixed as of glibc 2.3.1. */
     if (posix_memalign(&p, MIN_ALIGNMENT, n))
	  p = (void*) 0;

#  elif defined(__ICC) || defined(__INTEL_COMPILER) || defined(HAVE__MM_MALLOC)
     /* Intel's C compiler defines _mm_malloc and _mm_free intrinsics */
     p = (void *) _mm_malloc(n, MIN_ALIGNMENT);
#    undef real_free
#    define real_free _mm_free

#  elif defined(_MSC_VER)
     /* MS Visual C++ 6.0 with a "Processor Pack" supports SIMD
	and _aligned_malloc/free (uses malloc.h) */
     p = (void *) _aligned_malloc(n, MIN_ALIGNMENT);
#    undef real_free
#    define real_free _aligned_free

#  elif defined(macintosh) /* MacOS 9 */
     p = (void *) MPAllocateAligned(n,
#    if MIN_ALIGNMENT == 8
				    kMPAllocate8ByteAligned,
#    elif MIN_ALIGNMENT == 16
				    kMPAllocate16ByteAligned,
#    elif MIN_ALIGNMENT == 32
				    kMPAllocate32ByteAligned,
#    else
#      error "Unknown alignment for MPAllocateAligned"
#    endif
				    0);
#    undef real_free
#    define real_free MPFree

#  else
     /* Add your machine here and send a patch to [email protected] 
        or (e.g. for Windows) configure --with-our-malloc */
#    error "Don't know how to malloc() aligned memory ... try configuring --with-our-malloc"
#  endif

#else /* !defined(MIN_ALIGNMENT) */
     p = malloc(n);
#endif

     return p;
}
コード例 #2
0
ファイル: test_brw.c プロジェクト: michaeljclark/userblk
int main(int argc, char **argv)
{
  int ub_fd, bi_fd, ret;
  char *wrbuf, *rdbuf;

  parse_cmdline(argc, argv);

  /* open the ubb device */
  if((ub_fd = open64(opt_ubb_device, O_RDWR | O_CREAT | O_LARGEFILE | O_DIRECT,
                     0644)) < 0) {
    perror("test_brw: opening ubb");
    exit(1);
  }

  /* open the disk image */
  if((bi_fd = open64(opt_image, O_RDWR | O_CREAT | O_LARGEFILE | O_DIRECT,
                     0644)) < 0) {
    perror("test_brw: opening image");
    exit(1);
  }

  /* allocate buffers */
  wrbuf = memalign(opt_bufalign, opt_bufsize);
  rdbuf = memalign(opt_bufalign, opt_bufsize);
  if(!wrbuf || !rdbuf) {
    perror("test_brw: error allocating buffers");
    exit(1);
  }

  /* fill test buffer */
  memset(wrbuf, opt_testchar, opt_bufsize);

  /* write to block image */
  if((ret = pwrite64(ub_fd, wrbuf, opt_bufsize, opt_testoffset)) < 0) {
    perror("test_brw: error writing to ubb");
    exit(1);
  }
  if(ret != opt_bufsize) {
    fprintf(stderr, "test_brw: short write: ret=%d", ret);
    exit(1);
  }

  /* read back from device */
  if((ret = pread64(bi_fd, rdbuf, opt_bufsize, opt_testoffset)) < 0) {
    perror("test_brw: error reading from image");
    exit(1);
  }
  if(ret != opt_bufsize) {
    fprintf(stderr, "test_brw: short read: ret=%d", ret);
    exit(1);
  }

  /* compare read and write buffers */
  if(memcmp(wrbuf, rdbuf, opt_bufsize) != 0) {
    fprintf(stderr, "test_brw: read and write buffers differ\n");    
  } else {
    printf("SUCCESS\n");
  }

  /* clean up */
  close(bi_fd);
  close(ub_fd);
  free(wrbuf);
  free(rdbuf);

  exit(0);
}
コード例 #3
0
ファイル: DirectPut.c プロジェクト: jvolmer/tmLQCD
int msg_InjFifoInit ( msg_InjFifoHandle_t *injFifoHandlePtr,
                      uint32_t             startingSubgroupId,
                      uint32_t             startingFifoId,
                      uint32_t             numFifos,
                      size_t               fifoSize,
                      Kernel_InjFifoAttributes_t  *injFifoAttrs ) {

    void                *buffer = NULL;
    uint32_t endingFifoId; // Relative to a subgroup
    uint32_t numFifosInSubgroup;
    int rc;
    uint32_t subgroupId = startingSubgroupId;
    uint32_t fifoIds[BGQ_MU_NUM_INJ_FIFOS_PER_SUBGROUP];
    Kernel_InjFifoAttributes_t attrs[BGQ_MU_NUM_INJ_FIFOS_PER_SUBGROUP];
    Kernel_InjFifoAttributes_t defaultAttrs;
    uint64_t lock_cache;

    memset ( &defaultAttrs, 0x00, sizeof(defaultAttrs) );
    if(injFifoAttrs == NULL) {
        injFifoAttrs = &defaultAttrs;
    }

    // Malloc space for the info structure
    msg_InjFifoInfo_t *info;
    info = (msg_InjFifoInfo_t *) memalign(32, sizeof(msg_InjFifoInfo_t));
    if( !info ) return -1;

    // Initialize the info structure
    info->startingSubgroupId = startingSubgroupId;
    info->startingFifoId     = startingFifoId;
    info->numFifos           = numFifos;
    info->numSubgroups       = 0;

    // Malloc space for the injection fifos.  They are 64-byte aligned.
    for (unsigned int i = 0; i < numFifos; i++) {
        info->fifoPtr[i] = (uint64_t*)memalign(64, fifoSize);
        if ( !info->fifoPtr[i] ) return -1;
    }

    // Process one subgroup at a time.
    // - Allocate the fifos.
    // - Init the MU MMIO for the fifos.
    // - Activate the fifos.
    while ( numFifos > 0 ) {
        info->numSubgroups++;

        // startingFifoId is the starting fifo number relative to the
        // subgroup we are working on.
        // Determine endingFifoId, the ending fifo number relative to
        // the subgroup we are working on.
        endingFifoId = startingFifoId + numFifos-1;
        if ( endingFifoId > (BGQ_MU_NUM_INJ_FIFOS_PER_SUBGROUP-1) ) {
            endingFifoId = BGQ_MU_NUM_INJ_FIFOS_PER_SUBGROUP-1;
        }
        numFifosInSubgroup = endingFifoId - startingFifoId + 1;
        info->numFifosInSubgroup[subgroupId] = numFifosInSubgroup;

        // Init structures for allocating the fifos...
        // - fifo Ids
        // - attributes
        for (unsigned int i = 0; i < numFifosInSubgroup; i++) {
            fifoIds[i] = startingFifoId + i;
            memcpy(&attrs[i], injFifoAttrs, sizeof(attrs[i]));
        }

        // Allocate the fifos
        rc = Kernel_AllocateInjFifos (subgroupId,
                                      &info->subgroup[subgroupId],
                                      numFifosInSubgroup,
                                      fifoIds,
                                      attrs);
        if ( rc ) {
            printf("msg_InjFifoInit: Kernel_AllocateInjFifos failed with rc=%d\n",rc);
            return rc;
        }

        // Init the MU MMIO for the fifos.
        for (unsigned int i = 0; i < numFifosInSubgroup; i++) {
            Kernel_MemoryRegion_t memRegion;
            rc = Kernel_CreateMemoryRegion ( &memRegion,
                                             info->fifoPtr[numFifos-i-1],
                                             fifoSize );
            if ( rc ) {
                printf("msg_InjFifoInit: Kernel_CreateMemoryRegion failed with rc=%d\n",rc);
                return rc;
            }

            // initialise the Fifos
            rc = Kernel_InjFifoInit (&info->subgroup[subgroupId],
                                     fifoIds[i],
                                     &memRegion,
                                     (uint64_t)info->fifoPtr[numFifos-i-1] -
                                     (uint64_t)memRegion.BaseVa,
                                     fifoSize-1);
            if ( rc ) {
                printf("msg_InjFifoInit: Kernel_InjFifoInit failed with rc=%d\n",rc);
                return rc;
            }
        }

        // Activate the fifos.
        rc = Kernel_InjFifoActivate (&info->subgroup[subgroupId],
                                     numFifosInSubgroup,
                                     fifoIds,
                                     KERNEL_INJ_FIFO_ACTIVATE);
        if ( rc ) {
            printf("msg_InjFifoInit: Kernel_InjFifoActivate failed with rc=%d\n",rc);
            return rc;
        }

        startingFifoId = 0; // Next subgroup will start at fifo 0.

        subgroupId++;       // Next subgroup.
        numFifos -= numFifosInSubgroup;
    }

    injFifoHandlePtr->pOpaqueObject = (void *)info;
    return 0;
}
コード例 #4
0
ファイル: dt_mem.c プロジェクト: peterfuture/dtplayer_c
void *dt_malloc(size_t size)
{
    void *ptr = NULL;
#if CONFIG_MEMALIGN_HACK
    long diff;
#endif

    /* let's disallow possibly ambiguous cases */
    if (size > (max_alloc_size - 32)) {
        return NULL;
    }

#if CONFIG_MEMALIGN_HACK
    ptr = malloc(size + ALIGN);
    if (!ptr) {
        return ptr;
    }
    diff              = ((~(long)ptr) & (ALIGN - 1)) + 1;
    ptr               = (char *)ptr + diff;
    ((char *)ptr)[-1] = diff;
#elif HAVE_POSIX_MEMALIGN
    if (size) //OS X on SDK 10.6 has a broken posix_memalign implementation
        if (posix_memalign(&ptr, ALIGN, size)) {
            ptr = NULL;
        }
#elif HAVE_ALIGNED_MALLOC
    ptr = _aligned_malloc(size, ALIGN);
#elif HAVE_MEMALIGN
#ifndef __DJGPP__
    ptr = memalign(ALIGN, size);
#else
    ptr = memalign(size, ALIGN);
#endif
    /* Why 64?
     * Indeed, we should align it:
     *   on  4 for 386
     *   on 16 for 486
     *   on 32 for 586, PPro - K6-III
     *   on 64 for K7 (maybe for P3 too).
     * Because L1 and L2 caches are aligned on those values.
     * But I don't want to code such logic here!
     */
    /* Why 32?
     * For AVX ASM. SSE / NEON needs only 16.
     * Why not larger? Because I did not see a difference in benchmarks ...
     */
    /* benchmarks with P3
     * memalign(64) + 1          3071, 3051, 3032
     * memalign(64) + 2          3051, 3032, 3041
     * memalign(64) + 4          2911, 2896, 2915
     * memalign(64) + 8          2545, 2554, 2550
     * memalign(64) + 16         2543, 2572, 2563
     * memalign(64) + 32         2546, 2545, 2571
     * memalign(64) + 64         2570, 2533, 2558
     *
     * BTW, malloc seems to do 8-byte alignment by default here.
     */
#else
    ptr = malloc(size);
#endif
    if (!ptr && !size) {
        size = 1;
        ptr = dt_malloc(1);
    }
#if CONFIG_MEMORY_POISONING
    if (ptr) {
        memset(ptr, FF_MEMORY_POISON, size);
    }
#endif
    return ptr;
}
コード例 #5
0
ファイル: glw_ps3.c プロジェクト: hjmb/showtime
static void
init_screen(glw_ps3_t *gp)
{

  // Allocate a 1Mb buffer, alligned to a 1Mb boundary to be our shared IO memory with the RSX.
  void *host_addr = memalign(1024*1024, 1024*1024);
  assert(host_addr != NULL);

  // Initilise Reality, which sets up the command buffer and shared IO memory
  gp->gr.gr_be.be_ctx = realityInit(0x10000, 1024*1024, host_addr); 
  assert(gp->gr.gr_be.be_ctx != NULL);
  
  gcmConfiguration config;
  gcmGetConfiguration(&config);

  TRACE(TRACE_INFO, "RSX", "memory @ 0x%x size = %d\n",
	config.localAddress, config.localSize);

  hts_mutex_init(&gp->gr.gr_be.be_mempool_lock);
  gp->gr.gr_be.be_mempool = extent_create(0, config.localSize >> 4);
  gp->gr.gr_be.be_rsx_address = (void *)(uint64_t)config.localAddress;


  VideoState state;
  assert(videoGetState(0, 0, &state) == 0); // Get the state of the display
  assert(state.state == 0); // Make sure display is enabled
  
  // Get the current resolution
  assert(videoGetResolution(state.displayMode.resolution, &gp->res) == 0);
  
  TRACE(TRACE_INFO, "RSX", "Video resolution %d x %d",
	gp->res.width, gp->res.height);

  gp->framebuffer_pitch = 4 * gp->res.width; // each pixel is 4 bytes
  gp->depthbuffer_pitch = 4 * gp->res.width; // And each value in the depth buffer is a 16 bit float
  
  // Configure the buffer format to xRGB
  VideoConfiguration vconfig;
  memset(&vconfig, 0, sizeof(VideoConfiguration));
  vconfig.resolution = state.displayMode.resolution;
  vconfig.format = VIDEO_BUFFER_FORMAT_XRGB;
  vconfig.pitch = gp->framebuffer_pitch;

  assert(videoConfigure(0, &vconfig, NULL, 0) == 0);
  assert(videoGetState(0, 0, &state) == 0); 
  
  const s32 buffer_size = gp->framebuffer_pitch * gp->res.height; 
  const s32 depth_buffer_size = gp->depthbuffer_pitch * gp->res.height;
  TRACE(TRACE_INFO, "RSX", "Buffer will be %d bytes", buffer_size);
  
  gcmSetFlipMode(GCM_FLIP_VSYNC); // Wait for VSYNC to flip
  
  // Allocate two buffers for the RSX to draw to the screen (double buffering)
  gp->framebuffer[0] = rsx_alloc(&gp->gr, buffer_size, 16);
  gp->framebuffer[1] = rsx_alloc(&gp->gr, buffer_size, 16);

  TRACE(TRACE_INFO, "RSX", "Buffers at 0x%x 0x%x\n",
	gp->framebuffer[0], gp->framebuffer[1]);

  gp->depthbuffer = rsx_alloc(&gp->gr, depth_buffer_size * 4, 16);
  
  // Setup the display buffers
  gcmSetDisplayBuffer(0, gp->framebuffer[0],
		      gp->framebuffer_pitch, gp->res.width, gp->res.height);
  gcmSetDisplayBuffer(1, gp->framebuffer[1],
		      gp->framebuffer_pitch, gp->res.width, gp->res.height);

  gcmResetFlipStatus();
  flip(gp, 1);
}
コード例 #6
0
ファイル: osystem_gfx.cpp プロジェクト: AdamRi/scummvm-pink
void OSystem_Wii::initSize(uint width, uint height,
							const Graphics::PixelFormat *format) {
	bool update = false;
	gfx_tex_format_t tex_format;

#ifdef USE_RGB_COLOR
	Graphics::PixelFormat newFormat;

	if (format)
		newFormat = *format;
	else
		newFormat = Graphics::PixelFormat::createFormatCLUT8();

	if (newFormat.bytesPerPixel > 2)
		newFormat = Graphics::PixelFormat::createFormatCLUT8();

	if (_pfGame != newFormat) {
		_pfGame = newFormat;
		update = true;
	}
#endif

	uint newWidth, newHeight;
	if (_pfGame.bytesPerPixel > 1) {
		newWidth = ROUNDUP(width, 4);
		newHeight = ROUNDUP(height, 4);
	} else {
		newWidth = ROUNDUP(width, 8);
		newHeight = ROUNDUP(height, 4);
	}

	if (_gameWidth != newWidth || _gameHeight != newHeight) {
		assert((newWidth <= 640) && (newHeight <= 480));

		if (width != newWidth || height != newHeight)
			printf("extending texture for compability: %ux%u -> %ux%u\n",
					width, height, newWidth, newHeight);

		_gameWidth = newWidth;
		_gameHeight = newHeight;
		update = true;
	}

	if (_gameRunning) {
		switchVideoMode(_configGraphicsMode);

		if (_arCorrection && (_gameWidth == 320) && (_gameHeight == 200))
			gfx_set_ar(320.0 / 240.0);
		else
			gfx_set_ar(f32(_gameWidth) / f32(_gameHeight));
	}

	if (update) {
		free(_gamePixels);

		tex_format = GFX_TF_PALETTE_RGB565;

#ifdef USE_RGB_COLOR
		if (_pfGame.bytesPerPixel > 1) {
			tex_format = GFX_TF_RGB565;
			_pfGameTexture = _pfRGB565;
		}

		printf("initSize %u*%u*%u (%u%u%u -> %u%u%u match: %d)\n",
				_gameWidth, _gameHeight, _pfGame.bytesPerPixel * 8,
				8 - _pfGame.rLoss, 8 - _pfGame.gLoss, 8 - _pfGame.bLoss,
				8 - _pfGameTexture.rLoss, 8 - _pfGameTexture.gLoss,
				8 - _pfGameTexture.bLoss, _pfGame == _pfGameTexture);

		_gamePixels = (u8 *) memalign(32, _gameWidth * _gameHeight *
										_pfGame.bytesPerPixel);
		memset(_gamePixels, 0, _gameWidth * _gameHeight *
				_pfGame.bytesPerPixel);
#else
		printf("initSize %u*%u\n", _gameWidth, _gameHeight);

		_gamePixels = (u8 *) memalign(32, _gameWidth * _gameHeight);
		memset(_gamePixels, 0, _gameWidth * _gameHeight);
#endif

		if (!gfx_tex_init(&_texGame, tex_format, TLUT_GAME,
					_gameWidth, _gameHeight)) {
			printf("could not init the game texture\n");
			::abort();
		}

		gfx_tex_set_bilinear_filter(&_texGame, _bilinearFilter);
		gfx_coords(&_coordsGame, &_texGame, GFX_COORD_FULLSCREEN);

		updateScreenResolution();
	}
}
コード例 #7
0
ファイル: binaryIO.c プロジェクト: cran/dbarts
int misc_bio_initialize(misc_binaryIO* bio, const char* fileName, int openFlag, int permissionsFlag)
{
  if (bio == NULL) return EFAULT;
  
  bio->buffer = NULL;
  bio->bufferLength = 0;
  
  bio->fileDescriptor = open(fileName, openFlag, permissionsFlag);
  if (bio->fileDescriptor == -1) return errno;
  
  errno = 0;
#ifdef _WIN32
  SYSTEM_INFO si;
  GetSystemInfo(&si);

  long pageSize = si.dwPageSize;
#elif defined(_SC_PAGE_SIZE)
  long pageSize = sysconf(_SC_PAGE_SIZE);
#elif defined(_SC_PAGESIZE)
  long pageSize = sysconf(_SC_PAGESIZE)
#else
  long pageSize = 4096;
#endif

  if (pageSize <= 0 || errno != 0) pageSize = 4096; // sure, why not?
  bio->bufferLength = (size_t) pageSize;
  
  // practically needs to hold at least one 64 bit int
  while (bio->bufferLength < sizeof(uint64_t)) bio->bufferLength <<= 1;
  
  size_t alignment = sizeof(uint64_t);
  if (alignment % sizeof(void*) != 0) alignment *= sizeof(void*);
  
#ifdef HAVE_POSIX_MEMALIGN
  int errorCode = posix_memalign(&bio->buffer, alignment, bio->bufferLength);
  if (errorCode != 0) {
    if (bio->buffer != NULL) free(bio->buffer);
#elif defined(__MINGW32__)
  bio->buffer = __mingw_aligned_malloc(bio->bufferLength, alignment);
  if (bio->buffer == NULL) {
    int errorCode = ENOMEM;
#else
  bio->buffer = memalign(alignment, bio->bufferLength);
  if (bio->buffer == NULL) {
    int errorCode = ENOMEM;
#endif
    close(bio->fileDescriptor);
    bio->fileDescriptor = -1;
    bio->bufferLength = 0;
    return errorCode;
  }
  
  return 0;
}

void misc_bio_invalidate(misc_binaryIO* bio)
{
  if (bio == NULL) return;
  
  if (bio->fileDescriptor != -1) {
    close(bio->fileDescriptor);
    bio->fileDescriptor = -1;
  }
  
  if (bio->buffer != NULL) {
#if defined(HAVE_POSIX_MEMALIGN) || !defined(__MINGW32__)
    free(bio->buffer);
#else
    __mingw_aligned_free(bio->buffer);
#endif
    bio->buffer = NULL;
  }
  
  bio->bufferLength = 0;
}

int misc_bio_writeChar(misc_binaryIO* bio, char c)
{
  if (bio == NULL) return EFAULT;
  
  ssize_t bytesWritten = write(bio->fileDescriptor, &c, sizeof(char));
  
  if (bytesWritten == 0) return EIO;
  if (bytesWritten < 0) return errno;
  
  return 0;
}

int misc_bio_writeChars(misc_binaryIO* bio, const char* c, size_t length)
{
  if (bio == NULL) return EFAULT;
  
  int errorCode = misc_bio_writeSizeType(bio, length);
  if (errorCode != 0) return errorCode;
  
  return misc_bio_writeNChars(bio, c, length);
}

int misc_bio_writeNChars(misc_binaryIO* bio, const char* c, size_t length)
{
  if (bio == NULL) return EFAULT;
  
  size_t totalBytesWritten = 0;
  while (totalBytesWritten < length) {
    ssize_t bytesWritten = write(bio->fileDescriptor, c + totalBytesWritten, length - totalBytesWritten);
    if (bytesWritten == 0) return EIO;
    if (bytesWritten < 0) return errno;
    totalBytesWritten += (size_t) bytesWritten;
  }
  
  return 0;
}

int misc_bio_writeSizeType(misc_binaryIO* bio, size_t s)
{
  uint64_t u = (uint64_t) s;
#ifndef WORDS_BIGENDIAN
  swapEndiannessFor8ByteWord((char*) &u);
#endif
  
  ssize_t bytesWritten = write(bio->fileDescriptor, &u, sizeof(uint64_t));
  if (bytesWritten == 0) return EIO;
  if (bytesWritten < 0) return errno;
  
  return 0;
}

int misc_bio_writeSizeTypes(misc_binaryIO* bio, const size_t* v, size_t length)
{
  if (bio == NULL) return EFAULT;
  
  int errorCode = misc_bio_writeSizeType(bio, length);
  if (errorCode != 0) return errorCode;
  
  return misc_bio_writeNSizeTypes(bio, v, length);
}

int misc_bio_writeNSizeTypes(misc_binaryIO* bio, const size_t* v, size_t length)
{
  if (bio == NULL) return EFAULT;
  
  size_t totalItemsWritten = 0;
  while (totalItemsWritten < length) {
    size_t itemsWritten = fillBufferFromSizeTypes(bio, v + totalItemsWritten, length - totalItemsWritten);
    
    size_t totalBytesWritten = 0;
    size_t bytesToWrite = itemsWritten * sizeof(uint64_t);
    
    while (totalBytesWritten < bytesToWrite) {
      ssize_t bytesWritten = write(bio->fileDescriptor, (char*) bio->buffer, bytesToWrite - totalBytesWritten);
      if (bytesWritten == 0) return EIO;
      if (bytesWritten < 0) return errno;
      totalBytesWritten += (size_t) bytesWritten;
    }
    
    totalItemsWritten += itemsWritten;
  }
  
  return 0;
}

int misc_bio_writeUnsigned32BitInteger(misc_binaryIO* bio, uint32_t u)
{
#ifndef WORDS_BIGENDIAN
  swapEndiannessFor4ByteWord((char*) &u);
#endif
  
  ssize_t bytesWritten = write(bio->fileDescriptor, &u, sizeof(uint32_t));
  if (bytesWritten == 0) return EIO;
  if (bytesWritten < 0) return errno;
  
  return 0;
}
コード例 #8
0
ファイル: wdbEndPktDrv.c プロジェクト: andy345/vxworks5
STATUS wdbEndPktDevInit
    (
    WDB_END_PKT_DEV *	pPktDev,	/* device structure to init */
    void		(*stackRcv) (),	/* receive packet callback (udpRcv) */
    char *		pDevice,	/* Device (ln, ie, etc.) that we */
    					/* wish to bind to. */
    int         	unit            /* unit number (0, 1, etc.) */
    )
    {
    END_OBJ *	pEnd;
    char	ifname [20];
    char	inetAdrs [24];

    /* initialize the wdbDrvIf field with driver info */

    pPktDev->wdbDrvIf.mode	= WDB_COMM_MODE_POLL| WDB_COMM_MODE_INT;
    pPktDev->wdbDrvIf.mtu	= WDB_END_PKT_MTU;
    pPktDev->wdbDrvIf.stackRcv	= stackRcv;		/* udpRcv */
    pPktDev->wdbDrvIf.devId	= (WDB_END_PKT_DEV *)pPktDev;
    pPktDev->wdbDrvIf.pollRtn	= wdbEndPoll;
    pPktDev->wdbDrvIf.pktTxRtn	= wdbEndTx;
    pPktDev->wdbDrvIf.modeSetRtn = wdbEndModeSet;

    /* initialize the device specific fields in the driver structure */

    pPktDev->inputBusy		= FALSE;
    pPktDev->outputBusy		= FALSE;

#ifndef	STANDALONE_AGENT
    /*
     * Here is where we bind to the lower layer.
     * We do not, as yet, provide for a shutdown routine, but perhaps
     * later.
     * We are a promiscous protocol.
     * The Int routine a fakeout.  Interrupts are handled by the lower
     * layer but we use a similar mechanism to check packets for 
     * the proper type and hand them off to the WDB agent from
     * the "interrupt" routine if it's appropriate to do so.
     */

#ifdef WDB_NPT_CAPABLE
    if (muxTkDrvCheck (pDevice) == TRUE)
	{
	if ((pPktDev->pCookie = muxTkBind (pDevice, unit, wdbNptInt,
					   (FUNCPTR)wdbNptShutdown,
                                           NULL, NULL, MUX_PROTO_SNARF,
					   "Wind Debug Agent",
					   NULL, NULL, NULL)) == NULL)
	    {
	    if (wdbEndDebug)
		logMsg ("Could not bind to NPT Device %s, loading...\n",
			(int)pDevice, 2, 3, 4, 5, 6);
	    return (ERROR);
	    }
	}
    else  /* END */
	{
	if (wdbEndDebug)
	    logMsg ("Not a NPT device! %s\n", (int)pDevice,2,3,4,5,6);
#endif /* WDB_NPT_CAPABLE */
	if ((pPktDev->pCookie = muxBind (pDevice, unit, wdbEndInt, NULL,
					 NULL, NULL, MUX_PROTO_SNARF,
			 		 "Wind Debug Agent", NULL)) == NULL)
	    {
	    if (wdbEndDebug)
		logMsg ("Could not bind to %s, loading...\n",
			(int)pDevice, 2, 3, 4, 5, 6);
	    return (ERROR);
	    }
#ifdef WDB_NPT_CAPABLE
	}
#endif /* WDB_NPT_CAPABLE */

    pEnd = PCOOKIE_TO_ENDOBJ(pPktDev->pCookie);


#else	/* STANDALONE_AGENT */
    /*
     * for standalone agent, we simply need to get the address of the 
     * of the device.
     */

     if ((pPktDev->pCookie = endFindByName (pDevice, unit)) == NULL)
	return (ERROR); 
#endif	/* STANDALONE_AGENT */

    /* build interface name */

    sprintf (ifname, "%s%d", pDevice, unit);

    /* get interface inet address */

    if (ifAddrGet (ifname, inetAdrs) != OK)
    	{
	if (wdbEndDebug)
	    logMsg ("Could not get inet address of %s interface...\n",
	    	(int) ifname, 2, 3, 4, 5, 6);
	return (ERROR);
	}

    pPktDev->ipAddr.s_addr = inet_addr (inetAdrs);

    pEnd = PCOOKIE_TO_ENDOBJ(pPktDev->pCookie);

    if ((pInPkt = memalign (4,pEnd->mib2Tbl.ifMtu)) == NULL)
        return (ERROR);
   
    if ((pPktDev->pInBlk = wdbEndMblkClGet (pEnd, pEnd->mib2Tbl.ifMtu))
        == NULL)
	return (ERROR);
    pPktDev->pInBlk->mBlkHdr.mFlags |= M_PKTHDR;

    if ((pPktDev->pOutBlk = wdbEndMblkClGet (pEnd, pEnd->mib2Tbl.ifMtu))
        == NULL)
	return (ERROR);
    pPktDev->pOutBlk->mBlkHdr.mFlags |= M_PKTHDR;

    if ((pPktDev->lastHAddr = wdbEndMblkClGet (pEnd, pEnd->mib2Tbl.ifMtu))
        == NULL)
	return (ERROR);

    if ((pPktDev->srcAddr = wdbEndMblkClGet (pEnd, pEnd->mib2Tbl.ifMtu))
        == NULL)
	return (ERROR);

    /* Set the length to the size of the buffer just allocated. */
    pPktDev->pInBlk->mBlkHdr.mLen = pPktDev->pInBlk->pClBlk->clSize;

    pPktDev->lastHAddr->mBlkHdr.mLen = pEnd->mib2Tbl.ifPhysAddress.addrLength;

    memset (pPktDev->lastHAddr->mBlkHdr.mData, 0xff,
            pPktDev->lastHAddr->mBlkHdr.mLen);

    /*
     * Create a source address structure so we can send fully
     * qualified packets.
     */
     
    muxIoctl (pPktDev->pCookie, EIOCGADDR, pPktDev->srcAddr->mBlkHdr.mData);

    
    pEndPktDev = pPktDev;

    return (OK);
    }
コード例 #9
0
ファイル: virtio-block.c プロジェクト: nvll/lk
status_t virtio_block_init(struct virtio_device *dev, uint32_t host_features)
{
    LTRACEF("dev %p, host_features 0x%x\n", dev, host_features);

    /* allocate a new block device */
    struct virtio_block_dev *bdev = malloc(sizeof(struct virtio_block_dev));
    if (!bdev)
        return ERR_NO_MEMORY;

    mutex_init(&bdev->lock);
    event_init(&bdev->io_event, false, EVENT_FLAG_AUTOUNSIGNAL);

    bdev->dev = dev;
    dev->priv = bdev;

    bdev->blk_req = memalign(sizeof(struct virtio_blk_req), sizeof(struct virtio_blk_req));
#if WITH_KERNEL_VM
    arch_mmu_query((vaddr_t)bdev->blk_req, &bdev->blk_req_phys, NULL);
#else
    bdev->blk_freq_phys = (uint64_t)(uintptr_t)bdev->blk_req;
#endif
    LTRACEF("blk_req structure at %p (0x%lx phys)\n", bdev->blk_req, bdev->blk_req_phys);

#if WITH_KERNEL_VM
    arch_mmu_query((vaddr_t)&bdev->blk_response, &bdev->blk_response_phys, NULL);
#else
    bdev->blk_response_phys = (uint64_t)(uintptr_t)&bdev->blk_response;
#endif

    /* make sure the device is reset */
    virtio_reset_device(dev);

    volatile struct virtio_blk_config *config = (struct virtio_blk_config *)dev->config_ptr;

    LTRACEF("capacity 0x%llx\n", config->capacity);
    LTRACEF("size_max 0x%x\n", config->size_max);
    LTRACEF("seg_max  0x%x\n", config->seg_max);
    LTRACEF("blk_size 0x%x\n", config->blk_size);

    /* ack and set the driver status bit */
    virtio_status_acknowledge_driver(dev);

    // XXX check features bits and ack/nak them

    /* allocate a virtio ring */
    virtio_alloc_ring(dev, 0, 16);

    /* set our irq handler */
    dev->irq_driver_callback = &virtio_block_irq_driver_callback;

    /* set DRIVER_OK */
    virtio_status_driver_ok(dev);

    /* construct the block device */
    static uint8_t found_index = 0;
    char buf[16];
    snprintf(buf, sizeof(buf), "virtio%u", found_index++);
    bio_initialize_bdev(&bdev->bdev, buf,
                        config->blk_size, config->capacity,
                        0, NULL);

    /* override our block device hooks */
    bdev->bdev.read_block = &virtio_bdev_read_block;
    bdev->bdev.write_block = &virtio_bdev_write_block;

    bio_register_device(&bdev->bdev);

    printf("found virtio block device of size %lld\n", config->capacity * config->blk_size);

    return NO_ERROR;
}
コード例 #10
0
ファイル: dec_audio.c プロジェクト: batman52/dingux-code
int init_audio_codec(sh_audio_t *sh_audio)
{
  if ((af_cfg.force & AF_INIT_FORMAT_MASK) == AF_INIT_FLOAT) {
      int fmt = AF_FORMAT_FLOAT_NE;
      if (sh_audio->ad_driver->control(sh_audio, ADCTRL_QUERY_FORMAT,
				       &fmt) == CONTROL_TRUE) {
	  sh_audio->sample_format = fmt;
	  sh_audio->samplesize = 4;
      }
  }
  if(!sh_audio->ad_driver->preinit(sh_audio))
  {
      mp_msg(MSGT_DECAUDIO,MSGL_ERR,MSGTR_ADecoderPreinitFailed);
      return 0;
  }

/* allocate audio in buffer: */
  if(sh_audio->audio_in_minsize>0){
      sh_audio->a_in_buffer_size=sh_audio->audio_in_minsize;
      mp_msg(MSGT_DECAUDIO,MSGL_V,MSGTR_AllocatingBytesForInputBuffer,
          sh_audio->a_in_buffer_size);
      sh_audio->a_in_buffer=memalign(16,sh_audio->a_in_buffer_size);
      memset(sh_audio->a_in_buffer,0,sh_audio->a_in_buffer_size);
      sh_audio->a_in_buffer_len=0;
  }

/* allocate audio out buffer: */
  sh_audio->a_buffer_size=sh_audio->audio_out_minsize+MAX_OUTBURST; /* worst case calc.*/

  mp_msg(MSGT_DECAUDIO,MSGL_V,MSGTR_AllocatingBytesForOutputBuffer,
      sh_audio->audio_out_minsize,MAX_OUTBURST,sh_audio->a_buffer_size);

  sh_audio->a_buffer=memalign(16,sh_audio->a_buffer_size);
  if(!sh_audio->a_buffer){
      mp_msg(MSGT_DECAUDIO,MSGL_ERR,MSGTR_CantAllocAudioBuf);
      return 0;
  }
  memset(sh_audio->a_buffer,0,sh_audio->a_buffer_size);
  sh_audio->a_buffer_len=0;

  if(!sh_audio->ad_driver->init(sh_audio)){
      mp_msg(MSGT_DECAUDIO,MSGL_WARN,MSGTR_ADecoderInitFailed);
      uninit_audio(sh_audio); // free buffers
      return 0;
  }

  sh_audio->inited=1;
  
  if(!sh_audio->channels || !sh_audio->samplerate){
    mp_msg(MSGT_DECAUDIO,MSGL_WARN,MSGTR_UnknownAudio);
    uninit_audio(sh_audio); // free buffers
    return 0;
  }

  if(!sh_audio->o_bps)
  sh_audio->o_bps=sh_audio->channels*sh_audio->samplerate*sh_audio->samplesize;

  mp_msg(MSGT_DECAUDIO,MSGL_INFO,"AUDIO: %d Hz, %d ch, %s, %3.1f kbit/%3.2f%% (ratio: %d->%d)\n",
	sh_audio->samplerate,sh_audio->channels,
	af_fmt2str_short(sh_audio->sample_format),
	sh_audio->i_bps*8*0.001,((float)sh_audio->i_bps/sh_audio->o_bps)*100.0,
        sh_audio->i_bps,sh_audio->o_bps);
  mp_msg(MSGT_IDENTIFY,MSGL_INFO,"ID_AUDIO_BITRATE=%d\nID_AUDIO_RATE=%d\n"
    "ID_AUDIO_NCH=%d\n", sh_audio->i_bps*8, sh_audio->samplerate,
    sh_audio->channels );

  sh_audio->a_out_buffer_size=sh_audio->a_buffer_size;
  sh_audio->a_out_buffer=sh_audio->a_buffer;
  sh_audio->a_out_buffer_len=sh_audio->a_buffer_len;
  
  return 1;
}
コード例 #11
0
ファイル: slabs_buffer.c プロジェクト: disprosium8/xfer_test
psdSLAB *psd_slabs_buf_create(size_t size, int partitions) {
	psdSLAB *buf;
	int page_size;
	int i;

	page_size = sysconf(_SC_PAGESIZE);

	if (partitions <= 0)
		partitions = 1;

	buf = malloc(sizeof(psdSLAB));
	if (!buf)
		goto error_exit;

	memset(buf, 0, sizeof(psdSLAB));

	buf->p_size = floor(size / partitions);
	buf->size = buf->p_size * partitions;
	buf->p_count = partitions - 1;
	buf->total_count_bytes = 0;
	buf->r_index = buf->p_count;
	buf->s_index = 0;
	buf->w_index = 0;

	if (buf->p_size < page_size) {
		goto buf_exit;
	}

	buf->entries = (bufEntry**)malloc(partitions * sizeof(bufEntry*));
	if (!buf->entries)
		goto buf_exit;

	for (i=0; i <= buf->p_count; i++) {
		bufEntry *entry = malloc(sizeof(bufEntry));
		entry->base = NULL;
		
		//entry->base = malloc(buf->p_size * sizeof(char));
		entry->base = memalign(page_size, buf->p_size * sizeof(char));
		if (!entry->base) {
			printf("could not allocate aligned memory\n");
			goto entry_exit;
		}
		
		entry->size = buf->p_size;
		entry->ptr = entry->base;
		entry->empty = TRUE;
		entry->priv = NULL;
		entry->write_amount = 0;
		entry->read_amount = 0;
		entry->status = PSB_NO_ERR;
		
		buf->entries[i] = entry;
	}

	if (pthread_mutex_init(&(buf->buf_lock), NULL) < 0)
		goto entry_exit;
	
	if (pthread_cond_init(&(buf->read_cond), NULL) < 0)
		goto entry_exit;
	
	if (pthread_cond_init(&(buf->write_cond), NULL) < 0)
		goto entry_exit;
	

	return buf;

 entry_exit:
	for (i=0; i<= buf->p_count; i++) {
		if (buf->entries[i]) {
			free(buf->entries[i]->base);
			free(buf->entries[i]);
		}
		else
			break;
	}

 buf_exit:
	free(buf);
 error_exit:
	return NULL;
}
コード例 #12
0
static void atmel_hlcdc_init(struct udevice *dev)
{
	struct video_uc_platdata *uc_plat = dev_get_uclass_platdata(dev);
	struct atmel_hlcdc_priv *priv = dev_get_priv(dev);
	struct atmel_hlcd_regs *regs = priv->regs;
	struct display_timing *timing = &priv->timing;
	struct lcd_dma_desc *desc;
	unsigned long value, vl_clk_pol;
	int ret;

	/* Disable DISP signal */
	writel(LCDC_LCDDIS_DISPDIS, &regs->lcdc_lcddis);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_DISPSTS,
			   false, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	/* Disable synchronization */
	writel(LCDC_LCDDIS_SYNCDIS, &regs->lcdc_lcddis);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_LCDSTS,
			   false, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	/* Disable pixel clock */
	writel(LCDC_LCDDIS_CLKDIS, &regs->lcdc_lcddis);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_CLKSTS,
			   false, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	/* Disable PWM */
	writel(LCDC_LCDDIS_PWMDIS, &regs->lcdc_lcddis);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_PWMSTS,
			   false, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);

	/* Set pixel clock */
	value = priv->clk_rate / timing->pixelclock.typ;
	if (priv->clk_rate % timing->pixelclock.typ)
		value++;

	vl_clk_pol = 0;
	if (timing->flags & DISPLAY_FLAGS_PIXDATA_NEGEDGE)
		vl_clk_pol = LCDC_LCDCFG0_CLKPOL;

	if (value < 1) {
		/* Using system clock as pixel clock */
		writel(LCDC_LCDCFG0_CLKDIV(0)
			| LCDC_LCDCFG0_CGDISHCR
			| LCDC_LCDCFG0_CGDISHEO
			| LCDC_LCDCFG0_CGDISOVR1
			| LCDC_LCDCFG0_CGDISBASE
			| vl_clk_pol
			| LCDC_LCDCFG0_CLKSEL,
			&regs->lcdc_lcdcfg0);

	} else {
		writel(LCDC_LCDCFG0_CLKDIV(value - 2)
			| LCDC_LCDCFG0_CGDISHCR
			| LCDC_LCDCFG0_CGDISHEO
			| LCDC_LCDCFG0_CGDISOVR1
			| LCDC_LCDCFG0_CGDISBASE
			| vl_clk_pol,
			&regs->lcdc_lcdcfg0);
	}

	/* Initialize control register 5 */
	value = 0;

	if (!(timing->flags & DISPLAY_FLAGS_HSYNC_HIGH))
		value |= LCDC_LCDCFG5_HSPOL;
	if (!(timing->flags & DISPLAY_FLAGS_VSYNC_HIGH))
		value |= LCDC_LCDCFG5_VSPOL;

	switch (priv->output_mode) {
	case 12:
		value |= LCDC_LCDCFG5_MODE_OUTPUT_12BPP;
		break;
	case 16:
		value |= LCDC_LCDCFG5_MODE_OUTPUT_16BPP;
		break;
	case 18:
		value |= LCDC_LCDCFG5_MODE_OUTPUT_18BPP;
		break;
	case 24:
		value |= LCDC_LCDCFG5_MODE_OUTPUT_24BPP;
		break;
	default:
		BUG();
		break;
	}

	value |= LCDC_LCDCFG5_GUARDTIME(priv->guard_time);
	value |= (LCDC_LCDCFG5_DISPDLY | LCDC_LCDCFG5_VSPDLYS);
	writel(value, &regs->lcdc_lcdcfg5);

	/* Vertical & Horizontal Timing */
	value = LCDC_LCDCFG1_VSPW(timing->vsync_len.typ - 1);
	value |= LCDC_LCDCFG1_HSPW(timing->hsync_len.typ - 1);
	writel(value, &regs->lcdc_lcdcfg1);

	value = LCDC_LCDCFG2_VBPW(timing->vback_porch.typ);
	value |= LCDC_LCDCFG2_VFPW(timing->vfront_porch.typ - 1);
	writel(value, &regs->lcdc_lcdcfg2);

	value = LCDC_LCDCFG3_HBPW(timing->hback_porch.typ - 1);
	value |= LCDC_LCDCFG3_HFPW(timing->hfront_porch.typ - 1);
	writel(value, &regs->lcdc_lcdcfg3);

	/* Display size */
	value = LCDC_LCDCFG4_RPF(timing->vactive.typ - 1);
	value |= LCDC_LCDCFG4_PPL(timing->hactive.typ - 1);
	writel(value, &regs->lcdc_lcdcfg4);

	writel(LCDC_BASECFG0_BLEN_AHB_INCR4 | LCDC_BASECFG0_DLBO,
	       &regs->lcdc_basecfg0);

	switch (VNBITS(priv->vl_bpix)) {
	case 16:
		writel(LCDC_BASECFG1_RGBMODE_16BPP_RGB_565,
		       &regs->lcdc_basecfg1);
		break;
	case 32:
		writel(LCDC_BASECFG1_RGBMODE_24BPP_RGB_888,
		       &regs->lcdc_basecfg1);
		break;
	default:
		BUG();
		break;
	}

	writel(LCDC_BASECFG2_XSTRIDE(0), &regs->lcdc_basecfg2);
	writel(0, &regs->lcdc_basecfg3);
	writel(LCDC_BASECFG4_DMA, &regs->lcdc_basecfg4);

	/* Disable all interrupts */
	writel(~0UL, &regs->lcdc_lcdidr);
	writel(~0UL, &regs->lcdc_baseidr);

	/* Setup the DMA descriptor, this descriptor will loop to itself */
	desc = memalign(CONFIG_SYS_CACHELINE_SIZE, sizeof(*desc));
	if (!desc)
		return;

	desc->address = (u32)uc_plat->base;

	/* Disable DMA transfer interrupt & descriptor loaded interrupt. */
	desc->control = LCDC_BASECTRL_ADDIEN | LCDC_BASECTRL_DSCRIEN
			| LCDC_BASECTRL_DMAIEN | LCDC_BASECTRL_DFETCH;
	desc->next = (u32)desc;

	/* Flush the DMA descriptor if we enabled dcache */
	flush_dcache_range((u32)desc,
			   ALIGN(((u32)desc + sizeof(*desc)),
			   CONFIG_SYS_CACHELINE_SIZE));

	writel(desc->address, &regs->lcdc_baseaddr);
	writel(desc->control, &regs->lcdc_basectrl);
	writel(desc->next, &regs->lcdc_basenext);
	writel(LCDC_BASECHER_CHEN | LCDC_BASECHER_UPDATEEN,
	       &regs->lcdc_basecher);

	/* Enable LCD */
	value = readl(&regs->lcdc_lcden);
	writel(value | LCDC_LCDEN_CLKEN, &regs->lcdc_lcden);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_CLKSTS,
			   true, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	value = readl(&regs->lcdc_lcden);
	writel(value | LCDC_LCDEN_SYNCEN, &regs->lcdc_lcden);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_LCDSTS,
			   true, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	value = readl(&regs->lcdc_lcden);
	writel(value | LCDC_LCDEN_DISPEN, &regs->lcdc_lcden);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_DISPSTS,
			   true, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
	value = readl(&regs->lcdc_lcden);
	writel(value | LCDC_LCDEN_PWMEN, &regs->lcdc_lcden);
	ret = wait_for_bit(__func__, &regs->lcdc_lcdsr, LCDC_LCDSR_PWMSTS,
			   true, 1000, false);
	if (ret)
		printf("%s: %d: Timeout!\n", __func__, __LINE__);
}
コード例 #13
0
u8*	DecompressAsh( const u8 *stuff, u32 &len )
{
	if( !IsAshCompressed( stuff, len ) )
	{
		return NULL;
	}

	u32 r[32];
	u32 t;

	r[4] = (u32)stuff;      //in


	r[5] = *(u32*)( r[4] + 4 );
	r[5] = r[5] & 0x00FFFFFF;

	u32 size = r[5];

	//gprintf("Decompressed size: %d\n", size);
	u8* buf1 = (u8*)memalign( 32, size );
	if( !buf1 )
	{
		gprintf( "ASH: no memory\n" );
		return NULL;
	}
	r[3] = (u32)buf1;   //out
	//memset( (void*)buf1, 0, size );
	//printf("r[3] :%08X\n", r[3]);

	//printf("\n\n");

	r[24] = 0x10;
	r[28] = *(u32 *)(r[4]+8);
	r[25] = 0;
	r[29] = 0;
	r[26] = *(u32 *)(r[4]+0xC);
	r[30] = *(u32 *)(r[4]+r[28]);
	r[28] = r[28] + 4;
	//r[8]  = 0x8108<<16;
	//HACK, pointer to RAM
	u8* workingBuffer = (u8*)memalign( 32, MAX( 0x100000, size ) );
	if( !workingBuffer )
	{
		gprintf( "ASH: no memory 2\n" );
		free( buf1 );
		return NULL;
	}
	r[8]  = (u32)workingBuffer;
	//memset( (void*)workingBuffer, 0, 0x100000 );

	r[9]  = r[8]  + 0x07FE;
	r[10] = r[9]  + 0x07FE;
	r[11] = r[10] + 0x1FFE;
	r[31] = r[11] + 0x1FFE;
	r[23] = 0x200;
	r[22] = 0x200;
	r[27] = 0;

	while( 1 )
	{
		// loc_81332124:
		r[0] = r[26] >> 31;
		if( r[25] != 0x1F )
		{
			// loc_81332140:
			r[25]++;
			r[26] <<= 1;
		}
		else
		{
			// 8133212C
			r[26]= *(u32 *)( r[4] + r[24] );
			r[25]= 0;
			r[24] += 4;
		}

		// loc_8133214C:
		if( r[0] )
		{
			// 81332150
			*(u16*)( r[31] )	 = r[23] | 0x8000;
			*(u16*)( r[31] + 2 ) = r[23] | 0x4000;

			r[31] += 4;
			r[27] += 2;
			r[23]++;
			r[22]++;
			continue;
		}

		// loc_81332174:
		r[21] = r[25] + 9;
		t = r[21];
		if( r[21] > 0x20 )
		{
			// loc_813321AC:
			r[0] = 0x17;
			r[6] = r[26] >> r[0];
			r[26]= *(u32*)( r[4] + r[24 ]);
			r[0] = (~(r[21] - 0x40))+1;
			r[24] += 4;
			r[0] = r[26] >> r[0];
			r[6] |= r[0];
			r[25] = r[21] - 0x20;
			r[26] = r[26] << r[25];
		}
		else
		{
コード例 #14
0
ファイル: main.c プロジェクト: Jamis14/Nintendont
int main(int argc, char **argv)
{
	// Exit after 10 seconds if there is an error
	__exception_setreload(10);
//	u64 timeout = 0;
	CheckForGecko();
	DCInvalidateRange(loader_stub, 0x1800);
	memcpy(loader_stub, (void*)0x80001800, 0x1800);

	RAMInit();

	//Meh, doesnt do anything anymore anyways
	//STM_RegisterEventHandler(HandleSTMEvent);

	Initialise();

	u32 u;
	//Disables MEMPROT for patches
	write16(MEM_PROT, 0);
	//Patches FS access
	for( u = 0x93A00000; u < 0x94000000; u+=2 )
	{
		if( memcmp( (void*)(u), FSAccessPattern, sizeof(FSAccessPattern) ) == 0 )
		{
		//	gprintf("FSAccessPatch:%08X\r\n", u );
			memcpy( (void*)u, FSAccessPatch, sizeof(FSAccessPatch) );
			DCFlushRange((void*)u, sizeof(FSAccessPatch));
			break;
		}
	}

	//for BT.c
	CONF_GetPadDevices((conf_pads*)0x932C0000);
	DCFlushRange((void*)0x932C0000, sizeof(conf_pads));
	*(vu32*)0x932C0490 = CONF_GetIRSensitivity();
	*(vu32*)0x932C0494 = CONF_GetSensorBarPosition();
	DCFlushRange((void*)0x932C0490, 8);

	if(LoadKernel() < 0)
	{
		ClearScreen();
		gprintf("Failed to load kernel from NAND!\r\n");
		PrintFormat(DEFAULT_SIZE, MAROON, MENU_POS_X, 232, "Failed to load kernel from NAND!" );
		ExitToLoader(1);
	}
	InsertModule((char*)kernel_bin, kernel_bin_size);

	memset( (void*)0x92f00000, 0, 0x100000 );
	DCFlushRange( (void*)0x92f00000, 0x100000 );

	DCInvalidateRange( (void*)0x939F02F0, 0x20 );

	memcpy( (void*)0x939F02F0, Boot2Patch, sizeof(Boot2Patch) );

	DCFlushRange( (void*)0x939F02F0, 0x20 );

	//libogc still has that, lets close it
	__ES_Close();
	s32 fd = IOS_Open( "/dev/es", 0 );

	memset( STATUS, 0xFFFFFFFF, 0x20  );
	DCFlushRange( STATUS, 0x20 );

	memset( (void*)0x91000000, 0xFFFFFFFF, 0x20  );
	DCFlushRange( (void*)0x91000000, 0x20 );

	*(vu32*)0xD3003420 = 0; //make sure kernel doesnt reload

	raw_irq_handler_t irq_handler = BeforeIOSReload();
	IOS_IoctlvAsync( fd, 0x1F, 0, 0, &IOCTL_Buf, NULL, NULL );
	AfterIOSReload( irq_handler, FoundVersion );

	while(1)
	{
		DCInvalidateRange( STATUS, 0x20 );
		if((STATUS_LOADING > 0 || abs(STATUS_LOADING) > 1) && STATUS_LOADING < 20)
		{
			gprintf("Kernel sent signal\n");
			break;
		}
	}

	/* For slow USB HDDs */
	time_t timeout = time(NULL);
	while(time(NULL) - timeout < 10)
	{
		if(__io_custom_usbstorage.startup() && __io_custom_usbstorage.isInserted())
			break;
		usleep(50000);
	}
	fatInitDefault();

	gprintf("Nintendont at your service!\r\n%s\r\n", NIN_BUILD_STRING);
	KernelLoaded = 1;

	char* first_slash = strrchr(argv[0], '/');
	if (first_slash != NULL) strncpy(launch_dir, argv[0], first_slash-argv[0]+1);
	gprintf("launch_dir = %s\r\n", launch_dir);

	FPAD_Init();
	FPAD_Update();

	PrintInfo();
	PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + + 430, MENU_POS_Y + 20*0, "Home: Exit");
	PrintFormat(DEFAULT_SIZE, BLACK, MENU_POS_X + + 430, MENU_POS_Y + 20*1, "A   : Select");
	GRRLIB_Render();
	ClearScreen();

	/* Read IPL Font before doing any patches */
	void *fontbuffer = memalign(32, 0x50000);
	__SYS_ReadROM((void*)fontbuffer,0x50000,0x1AFF00);
	memcpy((void*)0xD3100000, fontbuffer, 0x50000);
	DCInvalidateRange( (void*)0x93100000, 0x50000 );
	free(fontbuffer);
	//gprintf("Font: 0x1AFF00 starts with %.4s, 0x1FCF00 with %.4s\n", (char*)0x93100000, (char*)0x93100000 + 0x4D000);

	// Simple code to autoupdate the meta.xml in Nintendont's folder
	FILE *meta = fopen("meta.xml", "w");
	if(meta != NULL)
	{
		fprintf(meta, "%s\r\n<app version=\"1\">\r\n\t<name>%s</name>\r\n", META_XML, META_NAME);
		fprintf(meta, "\t<coder>%s</coder>\r\n\t<version>%d.%d</version>\r\n", META_AUTHOR, NIN_VERSION>>16, NIN_VERSION&0xFFFF);
		fprintf(meta, "\t<release_date>20150531000000</release_date>\r\n");
		fprintf(meta, "\t<short_description>%s</short_description>\r\n", META_SHORT);
		fprintf(meta, "\t<long_description>%s\r\n\r\n%s</long_description>\r\n", META_LONG1, META_LONG2);
		fprintf(meta, "\t<ahb_access/>\r\n</app>");
		fclose(meta);
	}
コード例 #15
0
static ssize_t
fi_ibv_rdm_process_connect_request(struct rdma_cm_event *event,
				   struct fi_ibv_rdm_ep *ep)
{
	struct ibv_qp_init_attr qp_attr;
	struct rdma_conn_param cm_params;
	struct fi_ibv_rdm_conn *conn = NULL;
	struct rdma_cm_id *id = event->id;
	ssize_t ret = FI_SUCCESS;

	char *p = (char *) event->param.conn.private_data;

	if (ep->is_closing) {
		int rej_message = 0xdeadbeef;
		if (rdma_reject(id, &rej_message, sizeof(rej_message))) {
			VERBS_INFO_ERRNO(FI_LOG_AV, "rdma_reject\n", errno);
			ret = -errno;
			if (rdma_destroy_id(id)) {
				VERBS_INFO_ERRNO(FI_LOG_AV, "rdma_destroy_id\n",
						 errno);
				ret = (ret == FI_SUCCESS) ? -errno : ret;
			}
		}
		assert(ret == FI_SUCCESS);
		return ret;
	}

	HASH_FIND(hh, ep->domain->rdm_cm->conn_hash, p, FI_IBV_RDM_DFLT_ADDRLEN,
		  conn);

	if (!conn) {
		conn = memalign(FI_IBV_RDM_MEM_ALIGNMENT, sizeof(*conn));
		if (!conn)
			return -FI_ENOMEM;

		memset(conn, 0, sizeof(*conn));

		conn->state = FI_VERBS_CONN_ALLOCATED;
		dlist_init(&conn->postponed_requests_head);
		fi_ibv_rdm_unpack_cm_params(&event->param.conn, conn, ep);
		fi_ibv_rdm_conn_init_cm_role(conn, ep);

		FI_INFO(&fi_ibv_prov, FI_LOG_AV,
			"CONN REQUEST, NOT found in hash, new conn %p %d, addr %s:%u, HASH ADD\n",
			conn, conn->cm_role, inet_ntoa(conn->addr.sin_addr),
			ntohs(conn->addr.sin_port));

		HASH_ADD(hh, ep->domain->rdm_cm->conn_hash, addr,
			 FI_IBV_RDM_DFLT_ADDRLEN, conn);
	} else {
		if (conn->cm_role != FI_VERBS_CM_ACTIVE) {
			/*
			 * Do it before rdma_create_qp since that call would
			 * modify event->param.conn.private_data buffer
			 */
			fi_ibv_rdm_unpack_cm_params(&event->param.conn, conn,
						    ep);
		}

		FI_INFO(&fi_ibv_prov, FI_LOG_AV,
			"CONN REQUEST,  FOUND in hash, conn %p %d, addr %s:%u\n",
			conn, conn->cm_role, inet_ntoa(conn->addr.sin_addr),
			ntohs(conn->addr.sin_port));
	}

	if (conn->cm_role == FI_VERBS_CM_ACTIVE) {
		int rej_message = 0xdeadbeef;
		if (rdma_reject(id, &rej_message, sizeof(rej_message))) {
			VERBS_INFO_ERRNO(FI_LOG_AV, "rdma_reject\n", errno);
			ret = -errno;
			if (rdma_destroy_id(id)) {
				VERBS_INFO_ERRNO(FI_LOG_AV, "rdma_destroy_id\n",
						 errno);
				ret = (ret == FI_SUCCESS) ? -errno : ret;
			}
		}
		if (conn->state == FI_VERBS_CONN_ALLOCATED) {
			ret = fi_ibv_rdm_start_connection(ep, conn);
			if (ret != FI_SUCCESS)
				goto err;
		}
	} else {
		assert(conn->state == FI_VERBS_CONN_ALLOCATED ||
		       conn->state == FI_VERBS_CONN_STARTED);

		const size_t idx = 
			(conn->cm_role == FI_VERBS_CM_PASSIVE) ? 0 : 1;

		conn->state = FI_VERBS_CONN_STARTED;

		assert (conn->id[idx] == NULL);
		conn->id[idx] = id;

		ret = fi_ibv_rdm_prepare_conn_memory(ep, conn);
		if (ret != FI_SUCCESS)
			goto err;

		fi_ibv_rdm_tagged_init_qp_attributes(&qp_attr, ep);
		if (rdma_create_qp(id, ep->domain->pd, &qp_attr)) {
			ret = -errno;
			goto err;
		}
		conn->qp[idx] = id->qp;

		ret = fi_ibv_rdm_repost_receives(conn, ep, ep->rq_wr_depth);
		if (ret < 0) {
			VERBS_INFO(FI_LOG_AV, "repost receives failed\n");
			goto err;
		} else {
			ret = FI_SUCCESS;
		}

		id->context = conn;

		fi_ibv_rdm_pack_cm_params(&cm_params, conn, ep);

		if (rdma_accept(id, &cm_params)) {
			VERBS_INFO_ERRNO(FI_LOG_AV, "rdma_accept\n", errno);
			ret = -errno;
			goto err;
		}
		if (cm_params.private_data) {
			free((void *) cm_params.private_data);
		}
	}

	return ret;
err:
	/* ret err code is already set here, just cleanup resources */
	fi_ibv_rdm_conn_cleanup(conn);
	return ret;
}
コード例 #16
0
ファイル: tst-cmp.c プロジェクト: bminor/glibc
int
do_test (void)
{
  enum {
    max_align = 64,
    max_string_length = 33
  };
  size_t blob_size = max_align + max_string_length + 1;
  char *left = memalign (max_align, blob_size);
  char *right = memalign (max_align, blob_size);
  if (left == NULL || right == NULL)
    {
      printf ("error: out of memory\n");
      return 1;
    }

  const struct
  {
    const char *name;
    int (*implementation) (const char *, const char *);
  } functions[] =
      {
        { "strcmp", strcmp },
        { "strcasecmp", strcasecmp },
        { "strncmp (without NUL)", strncmp_no_terminator},
        { "strncasecmp (without NUL)", strncasecmp_no_terminator},
        { "strncmp (with NUL)", strncmp_terminator},
        { "strncasecmp (with NUL)", strncasecmp_terminator},
        { "strncmp (length 64)", strncmp_64},
        { "strncasecmp (length 64)", strncasecmp_64},
        { "strncmp (length SIZE_MAX)", strncmp_max},
        { "strncasecmp (length SIZE_MAX)", strncasecmp_max},
        { NULL, NULL }
      };
  const char *const strings[] =
    {
      "",
      "0",
      "01",
      "01234567",
      "0123456789abcde",
      "0123456789abcdef",
      "0123456789abcdefg",
      "1",
      "10",
      "123456789abcdef",
      "123456789abcdefg",
      "23456789abcdef",
      "23456789abcdefg",
      "abcdefghijklmnopqrstuvwxyzABCDEF",
      NULL
    };
  const unsigned char pads[] =
    { 0, 1, 32, 64, 128, '0', '1', 'e', 'f', 'g', 127, 192, 255 };

  bool errors = false;
  for (int left_idx = 0; strings[left_idx] != NULL; ++left_idx)
    for (int left_align = 0; left_align < max_align; ++left_align)
      for (unsigned pad_left = 0; pad_left < sizeof (pads); ++pad_left)
        {
          memset (left, pads[pad_left], blob_size);
          strcpy (left + left_align, strings[left_idx]);

          for (int right_idx = 0; strings[right_idx] != NULL; ++right_idx)
            for (unsigned pad_right = 0; pad_right < sizeof (pads);
                 ++pad_right)
              for (int right_align = 0; right_align < max_align;
                   ++right_align)
                {
                  memset (right, pads[pad_right], blob_size);
                  strcpy (right + right_align, strings[right_idx]);

                  for (int func = 0; functions[func].name != NULL; ++func)
                    {
                      int expected = left_idx - right_idx;
                      int actual = functions[func].implementation
                        (left + left_align, right + right_align);
                      if (signum (actual) != signum (expected))
                        {
                          printf ("error: mismatch for %s: %d\n"
                                  "  left:  \"%s\"\n"
                                  "  right: \"%s\"\n"
                                  "  pad_left = %u, pad_right = %u,\n"
                                  "  left_align = %d, right_align = %d\n",
                                  functions[func].name, actual,
                                  strings[left_idx], strings[right_idx],
                                  pad_left, pad_right,
                                  left_align, right_align);
                          errors = true;
                        }
                    }
                }
        }
  free (right);
  free (left);
  return errors;
}
コード例 #17
0
ファイル: exemple.c プロジェクト: xerpi/PS2InfoGB_rev6c_dsmod
int load_rom(char *filename)
{
    
     unsigned long file_length;
      int fd,fd_size;  
      int n;	
      int ret = 0;
      int ok=0;
      char tmpnom[0x100];    
  
 if(check_zip(filename))
    { 
        unzFile fd2=unzOpen(filename);        
         
        if(fd2==NULL)return (1);
                
        // Go to first file in archive 
        ret = unzGoToFirstFile(fd2);
        if(ret != UNZ_OK) {
            unzClose(fd2);
            return (1);
        }
        // Get information on the file 
        ret = unzGetCurrentFileInfo(fd2, &info, tmpnom, 0x100, NULL, 0, NULL, 0);
        if(ret != UNZ_OK) {
            unzClose(fd2);
            return (1);
        }
      
        //Open the file for reading 
        ret = unzOpenCurrentFile(fd2);
        if(ret != UNZ_OK) {
            unzClose(fd2);
            return (1);
        }       
        // Allocate file data buffer 
        fd_size = info.uncompressed_size;
       
        // Read (decompress) the file 
       // cartridge_rom = (unsigned char *)malloc(fd_size);
        cartridge_rom = (u8 *)memalign(64, fd_size);
        ret = unzReadCurrentFile(fd2,/*(char *)*/cartridge_rom, info.uncompressed_size);
        if(ret != info.uncompressed_size)
        {
            //free(buf2);
            unzCloseCurrentFile(fd2);
            unzClose(fd2);
            return (1);
        }
        //printf("zip decomp %d \n",(int)info.uncompressed_size);

        // Close the current file 
        ret = unzCloseCurrentFile(fd2);
        if(ret != UNZ_OK) {           
            unzClose(fd2);
            return (1);
        }
        // printf("zip close file\n");

        // Close the archive 
        ret = unzClose(fd2);
        if(ret != UNZ_OK) {            
            return (1);
        }
        // printf("zip close archive\n");

    // Check for 512-byte header    
   // ok=0;
   // cartridge_rom = (unsigned char *)malloc(fd_size);
   // for(n = 0; n <fd_size;n++)cartridge_rom[n]=buf[n+ok];  
    printf("zip header / rom copy %d %d %s \n",fd_size,ok,tmpnom);
    
 } 
 else{
  
   fd = fioOpen(filename, O_RDONLY);
   if(fd <= 0) {
	//	display_error("Error opening file.",0);
      printf("%s not found.\n",filename);
		return 0;
	}
 
	file_length = fioLseek(fd,0,SEEK_END);
	fioLseek(fd,0,SEEK_SET);

    cartridge_rom = (unsigned char *)malloc(file_length);
	fioRead(fd, (char *)cartridge_rom, file_length);

    fioClose(fd);
    
 }
 
 // traitement du fich rom ....
 
 return 0; 
 
 }
コード例 #18
0
ファイル: recovery.c プロジェクト: sndnvaps/lk-1
int _emmc_recovery_init(void)
{
	int update_status = 0;
	struct recovery_message *msg;
	uint32_t block_size = 0;

	block_size = mmc_get_device_blocksize();

	// get recovery message
	msg = (struct recovery_message *)memalign(CACHE_LINE, block_size);
	ASSERT(msg);

	if(emmc_get_recovery_msg(msg))
	{
		if(msg)
			free(msg);
		return -1;
	}

	msg->command[sizeof(msg->command)-1] = '\0'; //Ensure termination
	if (msg->command[0] != 0 && msg->command[0] != 255) {
		dprintf(INFO,"Recovery command: %d %s\n",
			sizeof(msg->command), msg->command);
	}

	if (!strcmp(msg->command, "boot-recovery")) {
		boot_into_recovery = 1;
	}

	if (!strcmp("update-radio",msg->command))
	{
		/* We're now here due to radio update, so check for update status */
		int ret = get_boot_info_apps(UPDATE_STATUS, (unsigned int *) &update_status);

		if(!ret && (update_status & 0x01))
		{
			dprintf(INFO,"radio update success\n");
			strlcpy(msg->status, "OKAY", sizeof(msg->status));
		}
		else
		{
			dprintf(INFO,"radio update failed\n");
			strlcpy(msg->status, "failed-update", sizeof(msg->status));
		}
		boot_into_recovery = 1;		// Boot in recovery mode
	}
	if (!strcmp("reset-device-info",msg->command))
	{
		reset_device_info();
	}
	if (!strcmp("root-detect",msg->command))
	{
		set_device_root();
	}
	else
		goto out;// do nothing

	strlcpy(msg->command, "", sizeof(msg->command));	// clearing recovery command
	emmc_set_recovery_msg(msg);	// send recovery message

out:
	if(msg)
		free(msg);
	return 0;
}
コード例 #19
0
static inline void *btAlignedAllocDefault(size_t size, int alignment)
{
	return memalign(alignment, size);
}
コード例 #20
0
ファイル: drvSIS3820.cpp プロジェクト: keenanlang/mca
/*Constructor */
drvSIS3820::drvSIS3820(const char *portName, int baseAddress, int interruptVector, int interruptLevel, 
                       int maxChans, int maxSignals, bool useDma, int fifoBufferWords)
  :  drvSIS38XX(portName, maxChans, maxSignals),
     useDma_(useDma)
{
  int status;
  epicsUInt32 controlStatusReg;
  epicsUInt32 moduleID;
  static const char* functionName="SIS3820";
  
  setIntegerParam(SIS38XXModel_, MODEL_SIS3820);
  
  /* Call devLib to get the system address that corresponds to the VME
   * base address of the board.
   */
  status = devRegisterAddress("drvSIS3820",
                               SIS3820_ADDRESS_TYPE,
                               (size_t)baseAddress,
                               SIS3820_BOARD_SIZE,
                               (volatile void **)&registers_);

  if (status) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: %s, Can't register VME address 0x%x\n", 
              driverName, functionName, portName, baseAddress);
    return;
  }
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: Registered VME address: 0x%x to local address: %p size: 0x%X\n", 
            driverName, functionName, baseAddress, registers_, SIS3820_BOARD_SIZE);

  /* Call devLib to get the system address that corresponds to the VME
   * FIFO address of the board.
   */
  fifoBaseVME_ = (epicsUInt32 *)(baseAddress + SIS3820_FIFO_BASE);
  status = devRegisterAddress("drvSIS3820",
                              SIS3820_ADDRESS_TYPE,
                              (size_t)fifoBaseVME_,
                              SIS3820_FIFO_BYTE_SIZE,
                              (volatile void **)&fifoBaseCPU_);

  if (status) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: %s, Can't register FIFO address 0x%x\n", 
              driverName, functionName, portName, baseAddress + SIS3820_FIFO_BASE);
    return;
  }

  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: Registered VME FIFO address: %p to local address: %p size: 0x%X\n", 
            driverName, functionName, fifoBaseVME_, 
            fifoBaseCPU_, SIS3820_FIFO_BYTE_SIZE);

  /* Probe VME bus to see if card is there */
  status = devReadProbe(4, (char *) &(registers_->control_status_reg),
                       (char *) &controlStatusReg);
  if (status) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: devReadProbe failure for address %p = %d\n", 
              driverName, functionName, &registers_->control_status_reg, status);
    return;
  }

  /* Get the module info from the card */
  moduleID = (registers_->moduleID_reg & 0xFFFF0000) >> 16;
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: module ID=%x\n", 
            driverName, functionName, moduleID);
  firmwareVersion_ = registers_->moduleID_reg & 0x0000FFFF;
  setIntegerParam(SIS38XXFirmware_, firmwareVersion_);
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: firmware=%d\n",
            driverName, functionName, firmwareVersion_);

  // Allocate FIFO readout buffer
  // fifoBufferWords input argument is in words, must be less than SIS3820_FIFO_WORD_SIZE
  if (fifoBufferWords == 0) fifoBufferWords = SIS3820_FIFO_WORD_SIZE;
  if (fifoBufferWords > SIS3820_FIFO_WORD_SIZE) fifoBufferWords = SIS3820_FIFO_WORD_SIZE;
  fifoBufferWords_ = fifoBufferWords;
#ifdef vxWorks
  fifoBuffer_ = (epicsUInt32*) memalign(8, fifoBufferWords_*sizeof(epicsUInt32));
#else
  void *ptr;
  status = posix_memalign(&ptr, 8, fifoBufferWords_*sizeof(epicsUInt32));
  if(status != 0) {
    printf("Error: posix_memalign status = %d\n", status);
  }
  fifoBuffer_ = (epicsUInt32*)ptr;
#endif
  if (fifoBuffer_ == NULL) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: posix_memalign failure for fifoBuffer_ = %d\n", 
              driverName, functionName, status);
    return;
  }
  
  dmaDoneEventId_ = epicsEventCreate(epicsEventEmpty);
  // Create the DMA ID
  if (useDma_) {
    dmaId_ = sysDmaCreate(dmaCallbackC, (void*)this);
    if (dmaId_ == 0 || (int)dmaId_ == -1) {
      asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
                "%s:%s: sysDmaCreate failed, errno=%d. Disabling use of DMA.\n",
                driverName, functionName, errno);
      useDma_ = false;
    }
  }
 
  /* Reset card */
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: resetting port %s\n", 
            driverName, functionName, portName);
  registers_->key_reset_reg = 1;

  /* Clear FIFO */
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
           "%s:%s: clearing FIFO\n",
           driverName, functionName);
  resetFIFO();
  
  // Disable 25MHz test pulses and test mode
  registers_->control_status_reg = CTRL_COUNTER_TEST_25MHZ_DISABLE;
  registers_->control_status_reg = CTRL_COUNTER_TEST_MODE_DISABLE;

  /* Set up the interrupt service routine */
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: interruptServiceRoutine pointer %p\n",
            driverName, functionName, intFuncC);

  status = devConnectInterruptVME(interruptVector, intFuncC, this);
  if (status) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: Can't connect to vector % d\n", 
              driverName, functionName, interruptVector);
    return;
  }
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: Connected interrupt vector: %d\n\n",
            driverName, functionName, interruptVector);
  
  /* Write interrupt level to hardware */
  registers_->irq_config_reg &= ~SIS3820_IRQ_LEVEL_MASK;
  registers_->irq_config_reg |= (interruptLevel << 8);
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: irq after setting IntLevel= 0x%x\n", 
             driverName, functionName, registers_->irq_config_reg);

  /* Write interrupt vector to hardware */
  registers_->irq_config_reg &= ~SIS3820_IRQ_VECTOR_MASK;
  registers_->irq_config_reg |= interruptVector;
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: irq = 0x%08x\n", 
            driverName, functionName, registers_->irq_config_reg);
            
  /* Initialize board in MCS mode. This will also set the initial value of the operation mode register. */
  setAcquireMode(ACQUIRE_MODE_MCS);

  /* Create the thread that reads the FIFO */
  if (epicsThreadCreate("SIS3820FIFOThread",
                         epicsThreadPriorityLow,
                         epicsThreadGetStackSize(epicsThreadStackMedium),
                         (EPICSTHREADFUNC)readFIFOThreadC,
                         this) == NULL) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: epicsThreadCreate failure\n", 
              driverName, functionName);
    return;
  }
  else
    asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: epicsThreadCreate success\n", 
            driverName, functionName);

  erase();

  /* Enable interrupts in hardware */  
  asynPrint(pasynUserSelf, ASYN_TRACE_FLOW, 
            "%s:%s: irq before enabling interrupts= 0x%08x\n", 
            driverName, functionName, registers_->irq_config_reg);

  registers_->irq_config_reg |= SIS3820_IRQ_ENABLE;

  /* Enable interrupt level in EPICS */
  status = devEnableInterruptLevel(intVME, interruptLevel);
  if (status) {
    asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
              "%s:%s: Can't enable enterrupt level %d\n", 
              driverName, functionName, interruptLevel);
    return;
  }
  
  exists_ = true;
  return;
}
コード例 #21
0
ファイル: pscom_psm.c プロジェクト: JonBau/pscom
static
pspsm_con_info_t *pspsm_con_create(void)
{
	pspsm_con_info_t *con_info = memalign(8, sizeof(*con_info));
	return con_info;
}
コード例 #22
0
/* Send an unsolicited advertisement packet
 * Please refer to rfc4861 / rfc3542
 */
int
send_ua(struct in6_addr* src_ip, char* if_name)
{
	int status = -1;
	int fd;

	int ifindex;
	int hop;
	struct ifreq ifr;
	u_int8_t *payload = NULL;
	int    payload_size;
	struct nd_neighbor_advert *na;
	struct nd_opt_hdr *opt;
	struct sockaddr_in6 src_sin6;
	struct sockaddr_in6 dst_sin6;

	if ((fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) == 0) {
		cl_log(LOG_ERR, "socket(IPPROTO_ICMPV6) failed: %s",
		       strerror(errno));
		goto err;
	}
	/* set the outgoing interface */
	ifindex = if_nametoindex(if_name);
	if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF,
		       &ifindex, sizeof(ifindex)) < 0) {
		cl_log(LOG_ERR, "setsockopt(IPV6_MULTICAST_IF) failed: %s",
		       strerror(errno));
		goto err;
	}
	/* set the hop limit */
	hop = 255; /* 255 is required. see rfc4861 7.1.2 */
	if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
		       &hop, sizeof(hop)) < 0) {
		cl_log(LOG_ERR, "setsockopt(IPV6_MULTICAST_HOPS) failed: %s",
		       strerror(errno));
		goto err;
	}
	
	/* set the source address */
	memset(&src_sin6, 0, sizeof(src_sin6));
	src_sin6.sin6_family = AF_INET6;
	src_sin6.sin6_addr = *src_ip;
	src_sin6.sin6_port = 0;
	if (bind(fd, (struct sockaddr *)&src_sin6, sizeof(src_sin6)) < 0) {
		cl_log(LOG_ERR, "bind() failed: %s", strerror(errno));
		goto err;
	}


	/* get the hardware address */
	memset(&ifr, 0, sizeof(ifr));
	strncpy(ifr.ifr_name, if_name, sizeof(ifr.ifr_name) - 1);
	if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
		cl_log(LOG_ERR, "ioctl(SIOCGIFHWADDR) failed: %s", strerror(errno));
		goto err;
	}

	/* build a neighbor advertisement message */
	payload_size = sizeof(struct nd_neighbor_advert)
			 + sizeof(struct nd_opt_hdr) + HWADDR_LEN;
	payload = memalign(sysconf(_SC_PAGESIZE), payload_size);
	if (!payload) {
		cl_log(LOG_ERR, "malloc for payload failed");
		goto err;
	}
	memset(payload, 0, payload_size);

	/* Ugly typecast from ia64 hell! */
	na = (struct nd_neighbor_advert *)((void *)payload);
	na->nd_na_type = ND_NEIGHBOR_ADVERT;
	na->nd_na_code = 0;
	na->nd_na_cksum = 0; /* calculated by kernel */
	na->nd_na_flags_reserved = ND_NA_FLAG_OVERRIDE;
	na->nd_na_target = *src_ip;

	/* options field; set the target link-layer address */
	opt = (struct nd_opt_hdr *)(payload + sizeof(struct nd_neighbor_advert));
	opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
	opt->nd_opt_len = 1; /* The length of the option in units of 8 octets */
	memcpy(payload + sizeof(struct nd_neighbor_advert)
			+ sizeof(struct nd_opt_hdr),
	       &ifr.ifr_hwaddr.sa_data, HWADDR_LEN);

	/* sending an unsolicited neighbor advertisement to all */
	memset(&dst_sin6, 0, sizeof(dst_sin6));
	dst_sin6.sin6_family = AF_INET6;
	inet_pton(AF_INET6, BCAST_ADDR, &dst_sin6.sin6_addr); /* should not fail */

	if (sendto(fd, payload, payload_size, 0,
		   (struct sockaddr *)&dst_sin6, sizeof(dst_sin6))
	    != payload_size) {
		cl_log(LOG_ERR, "sendto(%s) failed: %s",
		       if_name, strerror(errno));
		goto err;
	}

	status = 0;

err:
	close(fd);
	free(payload);
	return status;
}
コード例 #23
0
ファイル: wiiusb_hid.c プロジェクト: 6lackmag3/RetroArch
static int add_adapter(void *data, usb_device_entry *dev)
{
   int rc;
   usb_devdesc desc;
   const char *device_name = NULL;
   struct wiiusb_adapter *old_head = NULL;
   struct wiiusb_hid *hid = (struct wiiusb_hid*)data;
   struct wiiusb_adapter *adapter  = (struct wiiusb_adapter*)
      calloc(1, sizeof(struct wiiusb_adapter));

   (void)rc;

   if (!adapter)
      return -1;

   if (!hid)
   {
      free(adapter);
      RARCH_ERR("Allocation of adapter failed.\n");
      return -1;
   }

   if (USB_OpenDevice(dev->device_id, dev->vid, dev->pid, &adapter->handle) < 0)
   {
      RARCH_ERR("Error opening device 0x%p (VID/PID: %04x:%04x).\n",
            (void*)&adapter->device, dev->vid, dev->pid);
      free(adapter);
      return -1;
   }

   adapter->device = *dev;

   USB_GetDescriptors(adapter->handle, &desc);

   wiiusb_get_description(&adapter->device, adapter, &desc);

   if (adapter->endpoint_in == 0)
   {
      RARCH_ERR("Could not find HID config for device.\n");
      goto error;
   }

   if (desc.iManufacturer)
   {
      USB_GetAsciiString(adapter->handle, desc.iManufacturer, 0,
            sizeof(adapter->manufacturer_name), adapter->manufacturer_name);
#if 0
      RARCH_ERR(" Adapter Manufacturer name: %s\n", adapter->manufacturer_name);
#endif
   }

   if (desc.iProduct)
   {
      USB_GetAsciiString(adapter->handle, desc.iProduct, 0,
            sizeof(adapter->name), adapter->name);
#if 0
      RARCH_ERR(" Adapter name: %s\n", adapter->name);
#endif
   }

   device_name = (const char *)adapter->name;

   adapter->send_control_lock = slock_new();
   adapter->send_control_buffer = fifo_new(4096);

   if (!adapter->send_control_lock || !adapter->send_control_buffer)
   {
      RARCH_ERR("Error creating send control buffer.\n");
      goto error;
   }

   adapter->slot = pad_connection_pad_init(hid->slots,
         device_name, desc.idVendor, desc.idProduct,
         adapter, &wiiusb_hid_device_send_control);

   if (adapter->slot == -1)
      goto error;

   if (!pad_connection_has_interface(hid->slots, adapter->slot))
   {
      RARCH_ERR(" Interface not found (%s).\n", adapter->name);
      goto error;
   }

   RARCH_LOG("Interface found: [%s].\n", adapter->name);

   RARCH_LOG("Device 0x%p attached (VID/PID: %04x:%04x).\n",
         adapter->device, desc.idVendor, desc.idProduct);

   wiiusb_hid_device_add_autodetect(adapter->slot,
         device_name, wiiusb_hid.ident, desc.idVendor, desc.idProduct);

   adapter->hid = hid;
   adapter->thread = sthread_create(adapter_thread, adapter);

   if (!adapter->thread)
   {
      RARCH_ERR("Error initializing adapter thread.\n");
      goto error;
   }

   adapter->data = memalign(32, 2048);

   old_head = adapters.next;
   adapters.next = adapter;
   adapter->next = old_head;

   USB_FreeDescriptors(&desc);

   USB_DeviceRemovalNotifyAsync(adapter->handle, wiiusb_hid_removalnotify_cb, (void *)hid);

   return 0;

error:
   if (adapter->thread)
      sthread_join(adapter->thread);
   if (adapter->send_control_lock)
      slock_free(adapter->send_control_lock);
   if (adapter->send_control_buffer)
      fifo_free(adapter->send_control_buffer);
   if (adapter)
      free(adapter);
   USB_FreeDescriptors(&desc);
   USB_CloseDevice(&adapter->handle);
   return -1;
}
コード例 #24
0
ファイル: event.c プロジェクト: andyvand/cygpcpfans
static int
event_create(event_logfile_t *logfile)
{
    int j;
    char *s, *p;
    size_t offset;
    ssize_t bytes;
    struct timeval timestamp;

    static char *buffer;
    static int bufsize;

    /*
     * Using a static (global) event buffer to hold initial read.
     * The aim is to reduce memory allocation until we know we'll
     * need to keep something.
     */
    if (!buffer) {
	int	sts = 0;
	bufsize = 16 * getpagesize();
#ifdef HAVE_POSIX_MEMALIGN
	sts = posix_memalign((void **)&buffer, getpagesize(), bufsize);
#else
#ifdef HAVE_MEMALIGN
	buffer = (char *)memalign(getpagesize(), bufsize);
	if (buffer == NULL) sts = -1;
#else
	buffer = (char *)malloc(bufsize);
	if (buffer == NULL) sts = -1;
#endif
#endif
	if (sts != 0) {
	    __pmNotifyErr(LOG_ERR, "event buffer allocation failure");
	    return -1;
	}
    }

    offset = 0;
multiread:
    if (logfile->fd < 0)
    	return 0;
    bytes = read(logfile->fd, buffer + offset, bufsize - 1 - offset);
    /*
     * Ignore the error if:
     * - we've got EOF (0 bytes read)
     * - EBADF (fd isn't valid - most likely a closed pipe)
     * - EAGAIN/EWOULDBLOCK (fd is marked nonblocking and read would block)
     * - EINVAL/EISDIR (fd is a directory - config file botch)
     */
    if (bytes == 0)
	return 0;
    if (bytes < 0 && (errno == EBADF || errno == EISDIR || errno == EINVAL))
	return 0;
    if (bytes < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
	return 0;
    if (bytes > maxmem)
	return 0;
    if (bytes < 0) {
	__pmNotifyErr(LOG_ERR, "read failure on %s: %s",
		      logfile->pathname, strerror(errno));
	return -1;
    }

    gettimeofday(&timestamp, NULL);
    buffer[bufsize-1] = '\0';
    for (s = p = buffer, j = 0; *s != '\0' && j < bufsize-1; s++, j++) {
	if (*s != '\n')
	    continue;
	*s = '\0';
	bytes = (s+1) - p;
	pmdaEventQueueAppend(logfile->queueid, p, bytes, &timestamp);
	p = s + 1;
    }
    /* did we just do a full buffer read? */
    if (p == buffer) {
	char msg[64];
	__pmNotifyErr(LOG_ERR, "Ignoring long (%d bytes) line: \"%s\"", (int)
			bytes, __pmdaEventPrint(p, bytes, msg, sizeof(msg)));
    } else if (j == bufsize - 1) {
	offset = bufsize-1 - (p - buffer);
	memmove(buffer, p, offset);
	goto multiread;	/* read rest of line */
    }
    return 1;
}
コード例 #25
0
ファイル: mergernode.c プロジェクト: rikhul/Cell-Merge-Sort
void setup_spu(unsigned int spu_ctrlblock_addr){
  ctrl_dma_tag = mfc_tag_reserve();

  // Get SPU control block
  mfc_get(&spu_ctrlblock,
	  spu_ctrlblock_addr,
	  sizeof(spu_ctrlblock),
	  ctrl_dma_tag,
	  0,0);

  mfc_write_tag_mask(1<<ctrl_dma_tag);
  mfc_read_tag_status_all();

  mcb = (merger_ctrlblock_t*)memalign(128,spu_ctrlblock.num_mergers * sizeof(merger_ctrlblock_t) );
  md = (merger_data_t*)malloc(spu_ctrlblock.num_mergers * sizeof(merger_data_t));

  // Set addresses
  int i;
  for(i = 0; i < spu_ctrlblock.num_mergers; i++){
    // Set head/tail vector addresses
    mcb[i].idx_addr[LEFT] = (unsigned int) &md[i].idx[LEFT][HEAD];
    mcb[i].idx_addr[RIGHT] = (unsigned int) &md[i].idx[RIGHT][HEAD];
    mcb[i].idx_addr[OUT] = (unsigned int) &md[i].idx[PARENT][TAIL];
  }

  // Send merger control blocks
  mfc_put(mcb,
	  spu_ctrlblock.ctrlblocks_addr,
	  spu_ctrlblock.num_mergers * sizeof(merger_ctrlblock_t),
	  ctrl_dma_tag,
	  0,0);

  mfc_read_tag_status_all();

  // Mail PPU telling it we've set the addresses
  spu_write_out_mbox(1);

  // Wait for go-ahead mail
  spu_read_in_mbox();

  // Get merger blocks
  mfc_get(mcb,
	  spu_ctrlblock.ctrlblocks_addr,
	  spu_ctrlblock.num_mergers * sizeof(merger_ctrlblock_t),
	  ctrl_dma_tag,
	  0,0);

  mfc_read_tag_status_all();

  int buffer_idx = 0;
  for(i = 0; i < spu_ctrlblock.num_mergers; i++){
    // Add start address of buffer array to all block addresses
    if(mcb[i].id != 0)
      mcb[i].block_addr[OUT] += (unsigned int) &buffer[0];

    if(!mcb[i].leaf_node){
      mcb[i].block_addr[LEFT] += (unsigned int) &buffer[0];
      mcb[i].block_addr[RIGHT] += (unsigned int) &buffer[0];
    }

    // Setup merger data
    md[i].held_tag[LEFT] = 32;
    md[i].held_tag[RIGHT] = 32;
    md[i].held_tag[OUT] = 32;
    md[i].num_pulled[LEFT] = 0;
    md[i].num_pulled[RIGHT] = 0;
    md[i].mm_depleted[LEFT] = 0;
    md[i].mm_depleted[RIGHT] = 0;
    md[i].depleted[LEFT] = 0;
    md[i].depleted[RIGHT] = 0;
    md[i].done = 0;
    md[i].consumed[LEFT] = 0;
    md[i].consumed[RIGHT] = 0;

    md[i].idx[LEFT][HEAD] = spu_splats(0);
    md[i].idx[LEFT][TAIL] = spu_splats(0);
    md[i].idx[RIGHT][HEAD] = spu_splats(0);
    md[i].idx[RIGHT][TAIL] = spu_splats(0);
    md[i].idx[OUT][HEAD] = spu_splats(0);
    md[i].idx[OUT][TAIL] = spu_splats(0);
    md[i].idx[PARENT][HEAD] = spu_splats(0);
    md[i].idx[PARENT][TAIL] = spu_splats(0);

    md[i].buffer[LEFT] = &buffer[buffer_idx];
    buffer_idx += mcb[i].buffer_size[LEFT];
    md[i].buffer[RIGHT] = &buffer[buffer_idx];
    buffer_idx += mcb[i].buffer_size[RIGHT];
    md[i].buffer[OUT] = &buffer[buffer_idx];
    buffer_idx += mcb[i].buffer_size[OUT];
  }

  // Setup internal nodes
  for(i = 0; i < spu_ctrlblock.num_mergers; i++){
    if(mcb[i].local[OUT] < 255){
      int parent_idx = mcb[i].local[OUT];
      int side = (mcb[i].id+1)&1;
      md[i].buffer[OUT] = md[parent_idx].buffer[side];
      mcb[i].buffer_size[OUT] = mcb[parent_idx].buffer_size[side];
    }
  }
}
コード例 #26
0
ファイル: lesson6.c プロジェクト: Veryyes/Wii-Patrol
int main(int argc,char **argv)
{
	f32 yscale;
	u32 xfbHeight;
	u32 fb = 0;
	f32 rquad = 0.0f;
	u32 first_frame = 1;
	GXTexObj texture;
	Mtx view; // view and perspective matrices
	Mtx model, modelview;
	Mtx44 perspective;
	void *gpfifo = NULL;
	GXColor background = {0, 0, 0, 0xff};
	guVector cam = {0.0F, 0.0F, 0.0F},
			up = {0.0F, 1.0F, 0.0F},
		  look = {0.0F, 0.0F, -1.0F};

	TPLFile neheTPL;

	VIDEO_Init();
	WPAD_Init();

	rmode = VIDEO_GetPreferredMode(NULL);

	// allocate the fifo buffer
	gpfifo = memalign(32,DEFAULT_FIFO_SIZE);
	memset(gpfifo,0,DEFAULT_FIFO_SIZE);

	// allocate 2 framebuffers for double buffering
	frameBuffer[0] = SYS_AllocateFramebuffer(rmode);
	frameBuffer[1] = SYS_AllocateFramebuffer(rmode);

	// configure video
	VIDEO_Configure(rmode);
	VIDEO_SetNextFramebuffer(frameBuffer[fb]);
	VIDEO_Flush();
	VIDEO_WaitVSync();
	if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();

	fb ^= 1;

	// init the flipper
	GX_Init(gpfifo,DEFAULT_FIFO_SIZE);
 
	// clears the bg to color and clears the z buffer
	GX_SetCopyClear(background, 0x00ffffff);
 
	// other gx setup
	GX_SetViewport(0,0,rmode->fbWidth,rmode->efbHeight,0,1);
	yscale = GX_GetYScaleFactor(rmode->efbHeight,rmode->xfbHeight);
	xfbHeight = GX_SetDispCopyYScale(yscale);
	GX_SetScissor(0,0,rmode->fbWidth,rmode->efbHeight);
	GX_SetDispCopySrc(0,0,rmode->fbWidth,rmode->efbHeight);
	GX_SetDispCopyDst(rmode->fbWidth,xfbHeight);
	GX_SetCopyFilter(rmode->aa,rmode->sample_pattern,GX_TRUE,rmode->vfilter);
	GX_SetFieldMode(rmode->field_rendering,((rmode->viHeight==2*rmode->xfbHeight)?GX_ENABLE:GX_DISABLE));
 
	if (rmode->aa)
        GX_SetPixelFmt(GX_PF_RGB565_Z16, GX_ZC_LINEAR);
    else
        GX_SetPixelFmt(GX_PF_RGB8_Z24, GX_ZC_LINEAR);

	GX_SetCullMode(GX_CULL_NONE);
	GX_CopyDisp(frameBuffer[fb],GX_TRUE);
	GX_SetDispCopyGamma(GX_GM_1_0);

	// setup the vertex attribute table
	// describes the data
	// args: vat location 0-7, type of data, data format, size, scale
	// so for ex. in the first call we are sending position data with
	// 3 values X,Y,Z of size F32. scale sets the number of fractional
	// bits for non float data.
	GX_ClearVtxDesc();
	GX_SetVtxDesc(GX_VA_POS, GX_DIRECT);
	GX_SetVtxDesc(GX_VA_CLR0, GX_DIRECT);
	GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT);

	GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XYZ, GX_F32, 0);
	GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
	GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_CLR0, GX_CLR_RGBA, GX_RGB8, 0);

	// set number of rasterized color channels
	GX_SetNumChans(1);

	//set number of textures to generate
	GX_SetNumTexGens(1);

	// setup texture coordinate generation
	// args: texcoord slot 0-7, matrix type, source to generate texture coordinates from, matrix to use
	GX_SetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY);

    GX_InvVtxCache();
	GX_InvalidateTexAll();

	TPL_OpenTPLFromMemory(&neheTPL, (void *)NeHe_tpl,NeHe_tpl_size);
	TPL_GetTexture(&neheTPL,nehe,&texture);
	// setup our camera at the origin
	// looking down the -z axis with y up
	guLookAt(view, &cam, &up, &look);
 
	// setup our projection matrix
	// this creates a perspective matrix with a view angle of 90,
	// and aspect ratio based on the display resolution
    f32 w = rmode->viWidth;
    f32 h = rmode->viHeight;
	guPerspective(perspective, 45, (f32)w/h, 0.1F, 300.0F);
	GX_LoadProjectionMtx(perspective, GX_PERSPECTIVE);

	guVector cubeAxis = {1,1,1};

	while(1) {

		WPAD_ScanPads();
		if ( WPAD_ButtonsDown(0) & WPAD_BUTTON_HOME) exit(0);

		GX_SetTevOp(GX_TEVSTAGE0,GX_REPLACE);
		GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0);

		GX_LoadTexObj(&texture, GX_TEXMAP0);

		guMtxIdentity(model);
		guMtxRotAxisDeg(model, &cubeAxis, rquad);
		guMtxTransApply(model, model, 1.5f,0.0f,-7.0f);
		guMtxConcat(view,model,modelview);
		// load the modelview matrix into matrix memory
		GX_LoadPosMtxImm(modelview, GX_PNMTX0);
		
		GX_Begin(GX_QUADS, GX_VTXFMT0, 24);			// Draw a Cube

			GX_Position3f32(-1.0f, 1.0f, -1.0f);	// Top Left of the quad (top)
			GX_Color3f32(0.0f,1.0f,0.0f);			// Set The Color To Green
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32(-1.0f, 1.0f, 1.0f);	// Top Right of the quad (top)
			GX_Color3f32(0.0f,1.0f,0.0f);			// Set The Color To Green
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32(-1.0f, -1.0f, 1.0f);	// Bottom Right of the quad (top)
			GX_Color3f32(0.0f,1.0f,0.0f);			// Set The Color To Green
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32(- 1.0f, -1.0f, -1.0f);		// Bottom Left of the quad (top)
			GX_Color3f32(0.0f,1.0f,0.0f);			// Set The Color To Green
			GX_TexCoord2f32(0.0f,1.0f);

			GX_Position3f32( 1.0f,1.0f, -1.0f);	// Top Left of the quad (bottom)
			GX_Color3f32(1.0f,0.5f,0.0f);			// Set The Color To Orange
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32(1.0f,-1.0f, -1.0f);	// Top Right of the quad (bottom)
			GX_Color3f32(1.0f,0.5f,0.0f);			// Set The Color To Orange
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32(1.0f,-1.0f,1.0f);	// Bottom Right of the quad (bottom)
			GX_Color3f32(1.0f,0.5f,0.0f);			// Set The Color To Orange
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32( 1.0f,1.0f,1.0f);	// Bottom Left of the quad (bottom)
			GX_Color3f32(1.0f,0.5f,0.0f);			// Set The Color To Orange
			GX_TexCoord2f32(0.0f,1.0f);

			GX_Position3f32( -1.0f, -1.0f, 1.0f);		// Top Right Of The Quad (Front)
			GX_Color3f32(1.0f,0.0f,0.0f);			// Set The Color To Red
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32(1.0f, -1.0f, 1.0f);	// Top Left Of The Quad (Front)
			GX_Color3f32(1.0f,0.0f,0.0f);			// Set The Color To Red
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32(1.0f,-1.0f, -1.0f);	// Bottom Left Of The Quad (Front)
			GX_Color3f32(1.0f,0.0f,0.0f);			// Set The Color To Red
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32( -1.0f,-1.0f, -1.0f);	// Bottom Right Of The Quad (Front)
			GX_Color3f32(1.0f,0.0f,0.0f);			// Set The Color To Red
			GX_TexCoord2f32(0.0f,1.0f);

			GX_Position3f32( -1.0f,1.0f,1.0f);	// Bottom Left Of The Quad (Back)
			GX_Color3f32(1.0f,1.0f,0.0f);			// Set The Color To Yellow
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32(-1.0f,1.0f,-1.0f);	// Bottom Right Of The Quad (Back)
			GX_Color3f32(1.0f,1.0f,0.0f);			// Set The Color To Yellow
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32(1.0f, 1.0f,-1.0f);	// Top Right Of The Quad (Back)
			GX_Color3f32(1.0f,1.0f,0.0f);			// Set The Color To Yellow
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32( 1.0f, 1.0f,1.0f);	// Top Left Of The Quad (Back)
			GX_Color3f32(1.0f,1.0f,0.0f);			// Set The Color To Yellow
			GX_TexCoord2f32(0.0f,1.0f);

			GX_Position3f32(1.0f, -1.0f, -1.0f);	// Top Right Of The Quad (Left)
			GX_Color3f32(0.0f,0.0f,1.0f);			// Set The Color To Blue
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32(1.0f, 1.0f,-1.0f);	// Top Left Of The Quad (Left)
			GX_Color3f32(0.0f,0.0f,1.0f);			// Set The Color To Blue
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32(-1.0f,1.0f,-1.0f);	// Bottom Left Of The Quad (Left)
			GX_Color3f32(0.0f,0.0f,1.0f);			// Set The Color To Blue
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32(-1.0f,-1.0f, -1.0f);	// Bottom Right Of The Quad (Left)
			GX_Color3f32(0.0f,0.0f,1.0f);			// Set The Color To Blue
			GX_TexCoord2f32(0.0f,1.0f);

			GX_Position3f32( 1.0f, -1.0f,1.0f);	// Top Right Of The Quad (Right)
			GX_Color3f32(1.0f,0.0f,1.0f);			// Set The Color To Violet
			GX_TexCoord2f32(0.0f,0.0f);
			GX_Position3f32( -1.0f, -1.0f, 1.0f);		// Top Left Of The Quad (Right)
			GX_Color3f32(1.0f,0.0f,1.0f);			// Set The Color To Violet
			GX_TexCoord2f32(1.0f,0.0f);
			GX_Position3f32( -1.0f,1.0f, 1.0f);	// Bottom Left Of The Quad (Right)
			GX_Color3f32(1.0f,0.0f,1.0f);			// Set The Color To Violet
			GX_TexCoord2f32(1.0f,1.0f);
			GX_Position3f32( 1.0f,1.0f,1.0f);	// Bottom Right Of The Quad (Right)		
			GX_Color3f32(1.0f,0.0f,1.0f);			// Set The Color To Violet
			GX_TexCoord2f32(0.0f,1.0f);

		GX_End();									// Done Drawing The Quad 

		GX_SetZMode(GX_TRUE, GX_LEQUAL, GX_TRUE);
		GX_SetColorUpdate(GX_TRUE);
		GX_CopyDisp(frameBuffer[fb],GX_TRUE);

		GX_DrawDone();

		VIDEO_SetNextFramebuffer(frameBuffer[fb]);
		if(first_frame) {
			first_frame = 0;
			VIDEO_SetBlack(FALSE);
		}
		VIDEO_Flush();
 		VIDEO_WaitVSync();
		fb ^= 1;

		rquad -= 0.15f;				// Decrease The Rotation Variable For The Quad     ( NEW )
	}
}
コード例 #27
0
ファイル: glass.c プロジェクト: crtc-demos/the-scary-demo
static void
ghost_init_effect (void *params, backbuffer_info *bbuf)
{
  glass_data *gdata = (glass_data *) params;

  guPerspective (perspmat, 60, 1.33f, 10.0f, 500.0f);
  scene_update_camera (&scene);
  
  object_loc_initialise (&gdata->obj_loc, GX_PNMTX0);
  object_set_tex_norm_matrix (&gdata->obj_loc, GX_TEXMTX0);

  TPL_OpenTPLFromMemory (&mighty_zebuTPL, (void *) mighty_zebu_tpl,
			 mighty_zebu_tpl_size);
  
  /*TPL_OpenTPLFromMemory (&spiderwebTPL, (void *) spiderweb_tpl,
			 spiderweb_tpl_size);*/
  
  gdata->grabbed_texture = memalign (32, GX_GetTexBufferSize (RTT_WIDTH,
				     RTT_HEIGHT, USEFMT, GX_FALSE, 0));
  
  /* Set up refraction shader.  */
  gdata->refraction_shader = create_shader (&refraction_setup, NULL);
  shader_append_texmap (gdata->refraction_shader,
			get_utility_texture (UTIL_TEX_REFRACT),
			GX_TEXMAP2);
  shader_append_texcoordgen (gdata->refraction_shader, GX_TEXCOORD0,
			     GX_TG_MTX2x4, GX_TG_NRM, GX_TEXMTX0);

  /* Set up refraction post-pass shader.  */
  TPL_GetTexture (&mighty_zebuTPL, mighty_zebu, &gdata->mighty_zebu_tex_obj);

  GX_InitTexObjWrapMode (&gdata->mighty_zebu_tex_obj, GX_CLAMP, GX_CLAMP);
  GX_InitTexObjFilterMode (&gdata->mighty_zebu_tex_obj, GX_LINEAR, GX_LINEAR);
  
  gdata->plain_texture_shader = create_shader (&plain_texture_setup, NULL);
  shader_append_texmap (gdata->plain_texture_shader,
			&gdata->mighty_zebu_tex_obj, GX_TEXMAP0);
  shader_append_texcoordgen (gdata->plain_texture_shader,
			     GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0,
			     GX_IDENTITY);

  GX_InitTexObj (&gdata->grabbed_tex_obj, gdata->grabbed_texture, RTT_WIDTH,
		 RTT_HEIGHT, USEFMT, GX_CLAMP, GX_CLAMP, GX_FALSE);
  gdata->refraction_postpass_shader = create_shader (&refraction_postpass_setup,
						     NULL);
  shader_append_texmap (gdata->refraction_postpass_shader,
			&gdata->grabbed_tex_obj, GX_TEXMAP0);
  shader_append_texmap (gdata->refraction_postpass_shader,
			&gdata->mighty_zebu_tex_obj, GX_TEXMAP1);
  shader_append_texcoordgen (gdata->refraction_postpass_shader,
			     GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0,
			     GX_IDENTITY);
  shader_append_texcoordgen (gdata->refraction_postpass_shader,
			     GX_TEXCOORD1, GX_TG_MTX2x4, GX_TG_TEX1,
			     GX_IDENTITY);

  /* Set up glass post-pass shader.  */
  gdata->glass_postpass_shader = create_shader (&glass_postpass, NULL);
  shader_append_texmap (gdata->glass_postpass_shader,
			get_utility_texture (UTIL_TEX_DARKENING), GX_TEXMAP3);
  shader_append_texcoordgen (gdata->glass_postpass_shader, GX_TEXCOORD0,
			     GX_TG_MTX2x4, GX_TG_NRM, GX_TEXMTX0);
}
コード例 #28
0
ファイル: main.c プロジェクト: ChillyWillyGuru/PSL1GHT
int
main (s32 argc, const char* argv[])
{
  gcmContextData *context;
  void *host_addr = NULL;
  rsxBuffer buffers[MAX_BUFFERS];
  int currentBuffer = 0;
  padInfo padinfo;
  padData paddata;
  u16 width;
  u16 height;
  int frame = 0;
  int i;

  /* Allocate a 1Mb buffer, alligned to a 1Mb boundary
   * to be our shared IO memory with the RSX. */
  host_addr = memalign (1024*1024, HOST_SIZE);
  context = initScreen (host_addr, HOST_SIZE);
  ioPadInit (7);

  getResolution(&width, &height);
  for (i = 0; i < MAX_BUFFERS; i++)
    makeBuffer (&buffers[i], width, height, i);

  flip(context, MAX_BUFFERS - 1);

  DEBUG ("Starting Cairo test\n");

  while (1) {
    ioPadGetInfo (&padinfo);
    for(i = 0; i < MAX_PADS; i++) {
        if(padinfo.status[i]) {
            ioPadGetData (i, &paddata);
            if(paddata.BTN_START) {
              goto end;
            }
        }
    }

    setRenderTarget(context, &buffers[currentBuffer]);

    DEBUG ("Drawing frame %d\n", frame);
    waitFlip ();
    drawFrame (&buffers[currentBuffer], frame++); /* Draw into the unused buffer */
    flip (context, buffers[currentBuffer].id); /* Flip buffer onto screen */

    currentBuffer++;
    if (currentBuffer >= MAX_BUFFERS)
      currentBuffer = 0;
  }

 end:

  gcmSetWaitFlip(context);
  for (i = 0; i < MAX_BUFFERS; i++)
    rsxFree (buffers[i].ptr);

  rsxFinish (context, 1);
  free (host_addr);
  ioPadEnd();

  return 0;
}
コード例 #29
0
ファイル: kmeans.c プロジェクト: Ethan999/OpenDwarfs
/*---< main() >-------------------------------------------------------------*/
int setup(int argc, char **argv) {
	int		opt;
	extern char   *optarg;
	char   *filename = 0;
	float  *buf;
	char	line[1024];
	int		isBinaryFile = 0;

	float	threshold = 0.001;		/* default value */
	int		max_nclusters=5;		/* default value */
	int		min_nclusters=5;		/* default value */
	int		best_nclusters = 0;
	int		nfeatures = 0;
	int		npoints = 0;
	float	len;

	float **features;
	float **cluster_centres=NULL;
	int		i, j, index;
	int		nloops = 1;				/* default value */

	int		isRMSE = 0;		
	float	rmse;

	int		isOutput = 0;
	//float	cluster_timing, io_timing;		

	//ocd_init(&argc, &argv, NULL);
	//ocd_options opts = ocd_get_options();
	//platform_id = opts.platform_id;
	//device_id = opts.device_id;

	/* obtain command line arguments and change appropriate options */
	while ( (opt=getopt(argc,argv,"i:t:m:n:l:bro"))!= EOF) {
		switch (opt) {
			case 'i': filename=optarg;
				  break;
			case 'b': isBinaryFile = 1;
				  break;            
			case 't': threshold=atof(optarg);
				  break;
			case 'm': max_nclusters = atoi(optarg);
				  break;
			case 'n': min_nclusters = atoi(optarg);
				  break;
			case 'r': isRMSE = 1;
				  break;
			case 'o': isOutput = 1;
				  break;
			case 'l': nloops = atoi(optarg);
				  break;
			case '?': usage(argv[0]);
				  break;
			default: usage(argv[0]);
				 break;
		}
	}

	if (filename == 0) usage(argv[0]);

	/* ============== I/O begin ==============*/
	/* get nfeatures and npoints */
	//io_timing = omp_get_wtime();
	if (isBinaryFile) {		//Binary file input
		int infile;
		if ((infile = open(filename, O_RDONLY, "0600")) == -1) {
			fprintf(stderr, "Error: no such file (%s)\n", filename);
			exit(1);
		}
		read(infile, &npoints,   sizeof(int));
		read(infile, &nfeatures, sizeof(int));        

		/* allocate space for features[][] and read attributes of all objects */
		buf         = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		features    = (float**)memalign(AOCL_ALIGNMENT,npoints*          sizeof(float*));
		features[0] = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		for (i=1; i<npoints; i++)
			features[i] = features[i-1] + nfeatures;

		read(infile, buf, npoints*nfeatures*sizeof(float));

		close(infile);
	}
	else {
		FILE *infile;
		if ((infile = fopen(filename, "r")) == NULL) {
			fprintf(stderr, "Error: no such file (%s)\n", filename);
			exit(1);
		}		
		while (fgets(line, 1024, infile) != NULL)
			if (strtok(line, " \t\n") != 0)
				npoints++;			
		rewind(infile);
		while (fgets(line, 1024, infile) != NULL) {
			if (strtok(line, " \t\n") != 0) {
				/* ignore the id (first attribute): nfeatures = 1; */
				while (strtok(NULL, " ,\t\n") != NULL) nfeatures++;
				break;
			}
		}        

		/* allocate space for features[] and read attributes of all objects */
		buf         = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		features    = (float**)memalign(AOCL_ALIGNMENT,npoints*          sizeof(float*));
		features[0] = (float*) memalign(AOCL_ALIGNMENT,npoints*nfeatures*sizeof(float));
		for (i=1; i<npoints; i++)
			features[i] = features[i-1] + nfeatures;
		rewind(infile);
		i = 0;
		while (fgets(line, 1024, infile) != NULL) {
			if (strtok(line, " \t\n") == NULL) continue;            
			for (j=0; j<nfeatures; j++) {
				buf[i] = atof(strtok(NULL, " ,\t\n"));             
				i++;
			}            
		}
		fclose(infile);
	}
	//io_timing = omp_get_wtime() - io_timing;

	printf("\nI/O completed\n");
	printf("\nNumber of objects: %d\n", npoints);
	printf("Number of features: %d\n", nfeatures);	
	/* ============== I/O end ==============*/

	// error check for clusters
	if (npoints < min_nclusters)
	{
		printf("Error: min_nclusters(%d) > npoints(%d) -- cannot proceed\n", min_nclusters, npoints);
		exit(0);
	}

	srand(7);												/* seed for future random number generator */	
	memcpy(features[0], buf, npoints*nfeatures*sizeof(float)); /* now features holds 2-dimensional array of features */
	free(buf);

	/* ============ Initialize OpenCL Environment ============ */

	initCL();

	/* ======================= core of the clustering ===================*/

	//cluster_timing = omp_get_wtime();		/* Total clustering time */
	cluster_centres = NULL;
	index = cluster(npoints,				/* number of data points */
			nfeatures,				/* number of features for each point */
			features,				/* array: [npoints][nfeatures] */
			min_nclusters,			/* range of min to max number of clusters */
			max_nclusters,
			threshold,				/* loop termination factor */
			&best_nclusters,			/* return: number between min and max */
			&cluster_centres,		/* return: [best_nclusters][nfeatures] */  
			&rmse,					/* Root Mean Squared Error */
			isRMSE,					/* calculate RMSE */
			nloops);				/* number of iteration for each number of clusters */		

	//cluster_timing = omp_get_wtime() - cluster_timing;
    

	/* =============== Command Line Output =============== */

	/* cluster center coordinates
	   :displayed only for when k=1*/
	if((min_nclusters == max_nclusters) && (isOutput == 1)) {
		printf("\n================= Centroid Coordinates =================\n");
		for(i = 0; i < max_nclusters; i++){
			printf("%d:", i);
			for(j = 0; j < nfeatures; j++){
				printf(" %.2f", cluster_centres[i][j]);
			}
			printf("\n\n");
		}
	}

	len = (float) ((max_nclusters - min_nclusters + 1)*nloops);

    //printf("Number of Iteration: %d\n", nloops);
    //printf("Time for I/O: %.5fsec\n", io_timing);
    //printf("Time for Entire Clustering: %.5fsec\n", cluster_timing);

	if(min_nclusters != max_nclusters){
		if(nloops != 1){									//range of k, multiple iteration
			//printf("Average Clustering Time: %fsec\n",
			//		cluster_timing / len);
			printf("Best number of clusters is %d\n", best_nclusters);				
		}
		else{												//range of k, single iteration
			//printf("Average Clustering Time: %fsec\n",
			//		cluster_timing / len);
			printf("Best number of clusters is %d\n", best_nclusters);				
		}
	}
	else{
		if(nloops != 1){									// single k, multiple iteration
			//printf("Average Clustering Time: %.5fsec\n",
			//		cluster_timing / nloops);
			if(isRMSE)										// if calculated RMSE
				printf("Number of trials to approach the best RMSE of %.3f is %d\n", rmse, index + 1);
		}
		else{												// single k, single iteration				
			if(isRMSE)										// if calculated RMSE
				printf("Root Mean Squared Error: %.3f\n", rmse);
		}
	}


	/* free up memory */
#ifndef __FPGA__
	free(features[0]);
	free(features);    
#endif
	return(0);
}