// Perform all OpenCL setup steps required to have an operational image
// processor
OpenclImageProcessor::OpenclImageProcessor(bool use_gpu) {
  // Determine the NDRange size for each group. This should be made more
  // general in the future, but it works on most hardware for now.
  if (use_gpu)
    workgroup_size_ = 16;
  else
    workgroup_size_ = 1;

  // Initialize OpenCL
  try {
    cl::Platform::get(&platforms_);

    if (use_gpu)
      platforms_[0].getDevices(CL_DEVICE_TYPE_GPU, &devices_);
    else
      platforms_[0].getDevices(CL_DEVICE_TYPE_CPU, &devices_);

    selected_device_ = GetBestDevice();
    context_ = cl::Context(devices_);
    queue_ = cl::CommandQueue(context_, selected_device_);

    // create and load the kernels
    gaussian_ = LoadKernel("gaussian_kernel.cl", "gaussian_kernel", use_gpu);
    sobel_ = LoadKernel("sobel_kernel.cl", "sobel_kernel", use_gpu);
    non_max_suppression_ =
           LoadKernel("non_max_supp_kernel.cl", "non_max_supp_kernel", use_gpu);
    hysteresis_thresholding_ =
           LoadKernel("hyst_kernel.cl", "hyst_kernel", use_gpu);
  } catch (cl::Error e) {
    cerr << endl << "Error: " << e.what() << " : " << e.err() << endl;
  }
}
示例#2
0
sparseStatus_t sparseEngine_d::Multiply(sparseMat_t mat, T alpha, T beta,
	CUdeviceptr xVec, CUdeviceptr yVec) {

	sparseMatrix* m = static_cast<sparseMatrix*>(mat);

	Kernel* k;
	sparseStatus_t status = LoadKernel(m->prec, &k);
	if(SPARSE_STATUS_SUCCESS != status) return status;

	// Push the args and select the xVec as a texture
	CuCallStack callStack;
	callStack.Push(m->outputIndices, m->colIndices, m->sparseValues,
		m->tempOutput, m->numGroups);

	// Get the size of the xVec elements
	PrecTerm precTerms = PrecTerms[m->prec];	
	size_t offset;
	CUresult result = cuTexRefSetAddress(&offset, k->xVec_texture, xVec, 
		m->width * precTerms.vecSize);
	if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR;
	
	// Launch the function
	uint numBlocks = DivUp(m->numGroups, WarpsPerBlock);
	result = k->func[IndexFromVT(m->valuesPerThread)]->Launch(numBlocks, 1, 
		callStack);
	if(CUDA_SUCCESS != result) return SPARSE_STATUS_LAUNCH_ERROR;

	// Finalize the vector
	int numFinalizeBlocks = DivUp(m->numGroups, WarpsPerBlock);
	int useBeta = !IsZero(beta);

	callStack.Reset();
	callStack.Push(m->tempOutput, m->rowIndices, m->height, yVec, alpha, beta,
		useBeta);

	result = k->finalize->Launch(numFinalizeBlocks, 1, callStack);
	if(CUDA_SUCCESS != result) return SPARSE_STATUS_KERNEL_ERROR;

	return SPARSE_STATUS_SUCCESS;
}
示例#3
0
文件: bootstrap.c 项目: michalsc/AROS
/*
 * The entry point in C.
 *
 * The bootstrap routine has to load the kickstart at 0x01000000, with RO sections growing up the memory and 
 * RW sections stored beneath the 0x01000000 address. It is supposed to transfer the GRUB information further 
 * into the 64-bit kickstart.
 *
 * The kickstart is assembled from modules which have been loaded by GRUB. The modules may be loaded separately,
 * or as a collection in PKG file. If some file is specified in both PKG file and list of separate modules, the
 * copy in PKG will be skipped.
*/
static void __bootstrap(unsigned int magic, void *mb)
{
    struct mb_mmap *mmap = NULL;
    unsigned long len = 0;
    unsigned long ro_size = 0;
    unsigned long rw_size = 0;
    unsigned long ksize;
    unsigned long mod_end = 0;
    unsigned long kbase = 0;
    unsigned long kstart = 0;
    void *kend = NULL;
    kernel_entry_fun_t kentry = NULL;
    struct ELF_ModuleInfo *kdebug = NULL;
#ifdef DEBUG_MEM
    struct mb_mmap *mm2;
#endif

    /*
     * This will set fb_Mirror address to start of our working memory.
     * We don't know its size yet, we will allocate it later.
     */
    fb_Mirror = __bs_malloc(0);

#ifdef MULTIBOOT_64BIT
    /*
     * tell the CPU that we will support SSE. We do it here because x86-64 compiler
     * with -m32 switch will use SSE for operations on long longs.
     */                                                                                    
    wrcr(cr4, rdcr(cr4) | (3 << 9));                                                                                               
    /* Clear the EM and MP flags of CR0 */                                                                                         
    wrcr(cr0, rdcr(cr0) & ~6);
#endif

    switch(magic)
    {
    case MB_STARTUP_MAGIC:
	/* Parse multiboot v1 information */
	mod_end = mb1_parse(mb, &mmap, &len);
	break;

    case MB2_STARTUP_MAGIC:
    	/* Parse multiboot v2 information */
    	mod_end = mb2_parse(mb, &mmap, &len);
	break;

    default:
    	/* What to do here? We have no console... Die silently... */
    	return;
    }

#ifdef DEBUG_MEM
    ksize = len;
    mm2   = mmap;

    kprintf("[BOOT] Memory map contents:\n", mmap);
    while (ksize >= sizeof(struct mb_mmap))
    {
#ifdef DEBUG_MEM_TYPE
        if (mm2->type == DEBUG_MEM_TYPE)
#endif
	    kprintf("[BOOT] Type %lu addr %p len %p\n", mm2->type, mm2->addr, mm2->len);

        ksize -= mm2->size+4;
        mm2 = (struct mb_mmap *)(mm2->size + (unsigned long)mm2 + 4);
    }
#endif

    D(kprintf("[BOOT] Modules end at 0x%p\n", mod_end));
    if (!firstMod)
    {
    	panic("No kickstart modules found, nothing to run");
    }

    tag->ti_Tag = KRN_MMAPAddress;
    tag->ti_Data = KERNEL_OFFSET | (unsigned long)mmap;
    tag++;

    tag->ti_Tag = KRN_MMAPLength;
    tag->ti_Data = len;
    tag++;

    /* Setup stage - prepare the environment */
    setup_mmu();

    /* Count kickstart size */
    if (!GetKernelSize(firstMod, &ro_size, &rw_size, NULL))
    {
    	panic("Failed to determine kickstart size");
    }

    D(kprintf("[BOOT] Code %u, data %u\n", ro_size, rw_size));

    /*
     * Total kickstart size + alignment window (page size - 1) + some free space (512KB) for
     * boot-time memory allocator.
     * TODO: This is a temporary thing. Currently our kernel expects that it can use addresses beyond
     * KRN_KernelHighest to store boot-time private data, supervisor stack, segment descriptors, MMU stuff, etc.
     * The area is joined with read-only section because it's accessed only by supervisor-mode code
     * and can safely be marked as read-only for users.
     * Boot-time allocator needs to be smarter.
     */
    ksize = ro_size + rw_size + PAGE_SIZE - 1 + 0x80000;

    /* Now locate the highest appropriate region */
    while (len >= sizeof(struct mb_mmap))
    {
        if (mmap->type == MMAP_TYPE_RAM)
        {
            unsigned long long start = mmap->addr;
            unsigned long long end = mmap->addr + mmap->len;

	    /*
	     * The region must be located in 32-bit memory and must not overlap
	     * our modules.
	     * Here we assume the following:
	     * 1. Multiboot data from GRUB is placed in low memory.
	     * 2. At least one module is placed in upper memory, above ourselves.
	     * 3. There's no usable space below our modules.
	     */
	    if ((start <= 0x100000000ULL - ksize) && (end >= mod_end + ksize))
	    {
		unsigned long size;

	    	if (start < mod_end)
	    	    start = mod_end;

	    	if (end > 0x100000000ULL)
	    	    end = 0x100000000ULL;

		/* Remember the region if it fits in */
		size = end - start;
		if (size >= ksize)
		{
		    /*
		     * We place .data section at the start of the region, followed by .code section
		     * at page-aligned 'kbase' address.
		     * There must be a space beyond kickstart's read-only section, because the kickstart
		     * will extend it in order to store boot-time configuration and own private data.
		     */
		    kstart = start;
		    kbase = start + rw_size;
		    kbase = (kbase + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
	    	}
	    }
	}

        len -= mmap->size+4;
        mmap = (struct mb_mmap *)(mmap->size + (unsigned long)mmap+4);
    }

    if (!kbase)
    {
    	panic("Failed to find %u bytes for the kickstart.\n"
    	      "Your system doesn't have enough memory.");
    }

    kprintf("[BOOT] Loading kickstart, data 0x%p, code 0x%p...\n", kstart, kbase);

    if (!LoadKernel(firstMod, (void *)kbase, (void *)kstart, (char *)__bss_track, DEF_SYSBASE, &kend, &kentry, &kdebug))
    {
        panic("Failed to load the kickstart");
    }

    /* Prepare the rest of boot taglist */
    prepare_message(kstart, kbase, kend, kdebug);

#ifdef DEBUG_TAGLIST
    kprintf("[BOOT] Boot taglist:\n");
    for (tag = km; tag->ti_Tag != TAG_DONE; tag++)
    	kprintf("[BOOT] 0x%llp 0x%llp\n", tag->ti_Tag, tag->ti_Data);
#endif

    /* Jump to the kickstart */
    kick(kentry, km);

    panic("Failed to run the kickstart");
}
/* Main routine */
int main(int argc, char* argv[]) {

  const char* image_name;
  uint64_t key_size;
  uint8_t* key_blob = NULL;
  VbSharedDataHeader* shared;
  GoogleBinaryBlockHeader* gbb;
  VbError_t rv;
  int c, argsleft;
  int errorcnt = 0;
  char *e = 0;

  Memset(&lkp, 0, sizeof(LoadKernelParams));
  lkp.bytes_per_lba = LBA_BYTES;
  lkp.boot_flags = BOOT_FLAG_RECOVERY;
  Memset(&vnc, 0, sizeof(VbNvContext));
  VbNvSetup(&vnc);
  lkp.nv_context = &vnc;
  Memset(&cparams, 0, sizeof(VbCommonParams));

  /* Parse options */
  opterr = 0;
  while ((c=getopt(argc, argv, ":b:")) != -1)
  {
    switch (c)
    {
    case 'b':
      lkp.boot_flags = strtoull(optarg, &e, 0);
      if (!*optarg || (e && *e))
      {
        fprintf(stderr, "Invalid argument to -%c: \"%s\"\n", c, optarg);
        errorcnt++;
      }
      break;
    case '?':
      fprintf(stderr, "Unrecognized switch: -%c\n", optopt);
      errorcnt++;
      break;
    case ':':
      fprintf(stderr, "Missing argument to -%c\n", optopt);
      errorcnt++;
      break;
    default:
      errorcnt++;
      break;
    }
  }

  /* Update argc */
  argsleft = argc - optind;

  if (errorcnt || !argsleft)
  {
    fprintf(stderr, "usage: %s [options] <drive_image> [<sign_key>]\n",
            argv[0]);
    fprintf(stderr, "\noptions:\n");
    /* These cases are because uint64_t isn't necessarily the same as ULL. */
    fprintf(stderr, "  -b NUM     boot flag bits (default %" PRIu64 "):\n",
            (uint64_t)BOOT_FLAG_RECOVERY);
    fprintf(stderr, "               %" PRIu64 " = developer mode on\n",
            (uint64_t)BOOT_FLAG_DEVELOPER);
    fprintf(stderr, "               %" PRIu64 " = recovery mode on\n",
            (uint64_t)BOOT_FLAG_RECOVERY);
    return 1;
  }

  image_name = argv[optind];

  /* Read header signing key blob */
  if (argsleft > 1) {
    key_blob = ReadFile(argv[optind+1], &key_size);
    if (!key_blob) {
      fprintf(stderr, "Unable to read key file %s\n", argv[optind+1]);
      return 1;
    }
    printf("Read %" PRIu64 " bytes of key from %s\n", key_size, argv[optind+1]);
  }

  /* Initialize the GBB */
  lkp.gbb_size = sizeof(GoogleBinaryBlockHeader) + key_size;
  lkp.gbb_data = (void*)malloc(lkp.gbb_size);
  gbb = (GoogleBinaryBlockHeader*)lkp.gbb_data;
  cparams.gbb = gbb;
  Memset(gbb, 0, lkp.gbb_size);
  Memcpy(gbb->signature, GBB_SIGNATURE, GBB_SIGNATURE_SIZE);
  gbb->major_version = GBB_MAJOR_VER;
  gbb->minor_version = GBB_MINOR_VER;
  gbb->header_size = sizeof(GoogleBinaryBlockHeader);
  /* Fill in the given key, if any, for both root and recovery */
  if (key_blob) {
    gbb->rootkey_offset = gbb->header_size;
    gbb->rootkey_size = key_size;
    Memcpy((uint8_t*)gbb + gbb->rootkey_offset, key_blob, key_size);

    gbb->recovery_key_offset = gbb->rootkey_offset;
    gbb->recovery_key_size = key_size;
  }

  /* Initialize the shared data area */
  lkp.shared_data_blob = malloc(VB_SHARED_DATA_REC_SIZE);
  lkp.shared_data_size = VB_SHARED_DATA_REC_SIZE;
  shared = (VbSharedDataHeader*)lkp.shared_data_blob;
  if (0 != VbSharedDataInit(shared, lkp.shared_data_size)) {
    fprintf(stderr, "Unable to init shared data\n");
    return 1;
  }
  /* Copy in the key blob, if any */
  if (key_blob) {
    if (0 != VbSharedDataSetKernelKey(shared, (VbPublicKey*)key_blob)) {
      fprintf(stderr, "Unable to set key in shared data\n");
      return 1;
    }
  }

  /* Free the key blob, now that we're done with it */
  free(key_blob);

  printf("bootflags = %" PRIu64 "\n", lkp.boot_flags);

  /* Get image size */
  printf("Reading from image: %s\n", image_name);
  image_file = fopen(image_name, "rb");
  if (!image_file) {
    fprintf(stderr, "Unable to open image file %s\n", image_name);
    return 1;
  }
  fseek(image_file, 0, SEEK_END);
  lkp.streaming_lba_count = (ftell(image_file) / LBA_BYTES);
  lkp.gpt_lba_count = lkp.streaming_lba_count;
  rewind(image_file);
  printf("Streaming LBA count: %" PRIu64 "\n", lkp.streaming_lba_count);

  /* Allocate a buffer for the kernel */
  lkp.kernel_buffer = malloc(KERNEL_BUFFER_SIZE);
  if(!lkp.kernel_buffer) {
    fprintf(stderr, "Unable to allocate kernel buffer.\n");
    return 1;
  }
  lkp.kernel_buffer_size = KERNEL_BUFFER_SIZE;

  /* Call LoadKernel() */
  rv = LoadKernel(&lkp, &cparams);
  printf("LoadKernel() returned %d\n", rv);

  if (VBERROR_SUCCESS == rv) {
    printf("Partition number:   %" PRIu64 "\n", lkp.partition_number);
    printf("Bootloader address: %" PRIu64 "\n", lkp.bootloader_address);
    printf("Bootloader size:    %" PRIu64 "\n", lkp.bootloader_size);
    printf("Partition guid:     "
           "%02x%02x%02x%02x-%02x%02x-%02x%02x"
           "-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
           lkp.partition_guid[3],
           lkp.partition_guid[2],
           lkp.partition_guid[1],
           lkp.partition_guid[0],
           lkp.partition_guid[5],
           lkp.partition_guid[4],
           lkp.partition_guid[7],
           lkp.partition_guid[6],
           lkp.partition_guid[8],
           lkp.partition_guid[9],
           lkp.partition_guid[10],
           lkp.partition_guid[11],
           lkp.partition_guid[12],
           lkp.partition_guid[13],
           lkp.partition_guid[14],
           lkp.partition_guid[15]);
  }

  fclose(image_file);
  free(lkp.kernel_buffer);
  return rv != VBERROR_SUCCESS;
}
示例#5
0
//------------------------------------------------------------------------------
void  SpiceAttitudeKernelReader::GetCoverageStartAndEnd(StringArray       &kernels,
                                                        Integer           forNaifId,
                                                        Real              &start,
                                                        Real              &end,
                                                        bool              needAngVel)
{
   // first check to see if a kernel specified is not loaded; if not,
   // try to load it
   for (unsigned int ii = 0; ii < kernels.size(); ii++)
      if (!IsLoaded(kernels.at(ii)))   LoadKernel(kernels.at(ii));

   SpiceInt         idSpice     = forNaifId;
   SpiceInt         arclen      = 4;
   SpiceInt         typlen      = 5;
   bool             firstInt    = true;
   bool             idOnKernel  = false;
   char             kStr[5]     = "    ";
   char             aStr[4]     = "   ";
   char             levelStr[8] = "SEGMENT";
   char             timeStr[4]  = "TDB";
   SpiceBoolean     needAv      = needAngVel;
   ConstSpiceChar   *kernelName = NULL;
   ConstSpiceChar   *level      = levelStr;
   ConstSpiceChar   *timeSys    = timeStr;
   SpiceDouble      tol         = 0.0;
   SpiceInt         objId       = 0;
   SpiceInt         numInt      = 0;
   SpiceChar        *kernelType;
   SpiceChar        *arch;
   SpiceDouble      b;
   SpiceDouble      e;
   Real             bA1;
   Real             eA1;
   SPICEINT_CELL(ids, 200);
   SPICEDOUBLE_CELL(cover, 200000);

   // look through each kernel
   for (unsigned int ii = 0; ii < kernels.size(); ii++)
   {
      #ifdef DEBUG_CK_COVERAGE
         MessageInterface::ShowMessage(wxT("Checking coverage for ID %d on kernel %s\n"),
               forNaifId, (kernels.at(ii)).c_str());
      #endif
      kernelName = kernels[ii].char_str();
      // check the type of kernel
      arch        = aStr;
      kernelType  = kStr;
      getfat_c(kernelName, arclen, typlen, arch, kernelType);
      if (failed_c())
      {
         ConstSpiceChar option[] = "LONG";
         SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
         SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
         getmsg_c(option, numChar, err);
         wxString errStr(wxString::FromAscii( err));
         wxString errmsg = wxT("Error determining type of kernel \"");
         errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
         errmsg += errStr + wxT("\n");
         reset_c();
         throw UtilityException(errmsg);
      }
      #ifdef DEBUG_CK_COVERAGE
         MessageInterface::ShowMessage(wxT("Kernel is of type %s\n"),
               kernelType);
      #endif
      // only deal with CK kernels
      if (eqstr_c(kernelType, "ck") || eqstr_c(kernelType, "CK"))
      {
         ckobj_c(kernelName, &ids);
         // get the list of objects (IDs) for which data exists in the CK kernel
         for (SpiceInt jj = 0;  jj < card_c(&ids);  jj++)
         {
            objId = SPICE_CELL_ELEM_I(&ids,jj);
            #ifdef DEBUG_CK_COVERAGE
               MessageInterface::ShowMessage(wxT("Kernel contains data for object %d\n"),
                     (Integer) objId);
            #endif
            // look to see if this kernel contains data for the object we're interested in
            if (objId == idSpice)
            {
               idOnKernel = true;
               break;
            }
//            if (objId == (idSpice * 1000))
//            {
//               idSpice     = idSpice * 1000;
//               naifIDSPICE = idSpice; // not the way to do this - should pass it back
//               idOnKernel  = true;
//               break;
//            }
         }
         // only deal with kernels containing data for the object we're interested in
         if (idOnKernel)
         {
            #ifdef DEBUG_CK_COVERAGE
               MessageInterface::ShowMessage(wxT("Checking kernel %s for data for object %d\n"),
                     (kernels.at(ii)).c_str(), (Integer) objId);
            #endif
            scard_c(0, &cover);   // reset the coverage cell
            ckcov_c (kernelName, idSpice, needAv, level, tol, timeSys, &cover);
            if (failed_c())
            {
               ConstSpiceChar option[] = "LONG";
               SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
               SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
               getmsg_c(option, numChar, err);
               wxString errStr(wxString::FromAscii(err));
               wxString errmsg = wxT("Error determining coverage for CK kernel \"");
               errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
               errmsg += errStr + wxT("\n");
               reset_c();
               throw UtilityException(errmsg);
            }
            numInt = wncard_c(&cover);
            #ifdef DEBUG_CK_COVERAGE
               MessageInterface::ShowMessage(wxT("Number of intervals found =  %d\n"),
                     (Integer) numInt);
            #endif
            if ((firstInt) && (numInt > 0))
            {
               wnfetd_c(&cover, 0, &b, &e);
               if (failed_c())
               {
                  ConstSpiceChar option[] = "LONG";
                  SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
                  SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
                  getmsg_c(option, numChar, err);
                  wxString errStr(wxString::FromAscii(err));
                  wxString errmsg = wxT("Error getting interval times for CK kernel \"");
                  errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
                  errmsg += errStr + wxT("\n");
                  reset_c();
                  throw UtilityException(errmsg);
               }
               start    = SpiceTimeToA1(b);
               end      = SpiceTimeToA1(e);
               firstInt = false;
            }
            for (SpiceInt jj = 0; jj < numInt; jj++)
            {
               wnfetd_c(&cover, jj, &b, &e);
               bA1 = SpiceTimeToA1(b);
               eA1 = SpiceTimeToA1(e);
               if (bA1 < start)  start = bA1;
               if (eA1 > end)    end   = eA1;
            }
         }

      }
   }
   if (firstInt)
   {
      char           itsName[256];
      SpiceChar      *itsNameSPICE = itsName;
      SpiceBoolean   found2;
      bodc2n_c(naifIDSPICE, 256, itsNameSPICE, &found2);
      if (found2 == SPICEFALSE)
      {
         wxString errmsg = wxT("Error - unable to find name for body in SPICE kernel pool");
         throw UtilityException(errmsg);
      }
      else
      {
         wxString nameStr = wxString::FromAscii(itsNameSPICE);
         wxString errmsg = wxT("Error - no data available for body ");
         errmsg += nameStr + wxT(" on specified CK kernels");
         throw UtilityException(errmsg);
      }
   }
}
示例#6
0
文件: main.c 项目: volt72/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();

	// Checking for storage devices...
	ShowMessageScreen("Checking storage devices...");

	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");
		ShowMessageScreenAndExit("Failed to load kernel from NAND!", 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();

	/* 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);
	}
示例#7
0
//------------------------------------------------------------------------------
void  SpiceOrbitKernelReader::GetCoverageStartAndEnd(StringArray       &kernels,
                                                     Integer           forNaifId,
                                                     Real              &start,
                                                     Real              &end)
{
   // first check to see if a kernel specified is not loaded; if not,
   // try to load it
   for (unsigned int ii = 0; ii < kernels.size(); ii++)
      if (!IsLoaded(kernels.at(ii)))   LoadKernel(kernels.at(ii));

   SpiceInt         idSpice     = forNaifId;
   SpiceInt         arclen      = 4;
   SpiceInt         typlen      = 5;
   bool             firstInt    = true;
   bool             idOnKernel  = false;
   ConstSpiceChar   *kernelName = NULL;
   SpiceInt         objId       = 0;
   SpiceInt         numInt      = 0;
   SpiceChar        *kernelType;
   SpiceChar        *arch;
   SpiceDouble      b;
   SpiceDouble      e;
   Real             bA1;
   Real             eA1;
   SPICEINT_CELL(ids, 200);
   SPICEDOUBLE_CELL(cover, 200000);
   char             kStr[5] = "    ";
   char             aStr[4] = "   ";

   // look through each kernel
   for (unsigned int ii = 0; ii < kernels.size(); ii++)
   {
      #ifdef DEBUG_SPK_COVERAGE
         MessageInterface::ShowMessage(wxT("Checking coverage for ID %d on kernel %s\n"),
               forNaifId, (kernels.at(ii)).c_str());
      #endif
      kernelName = kernels[ii].char_str();
      // check the type of kernel
      arch        = aStr;
      kernelType  = kStr;
      getfat_c(kernelName, arclen, typlen, arch, kernelType);
      if (failed_c())
      {
         ConstSpiceChar option[] = "LONG";
         SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
         //SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
         SpiceChar      *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
         getmsg_c(option, numChar, err);
         wxString errStr(wxString::FromAscii(err));
         wxString errmsg = wxT("Error determining type of kernel \"");
         errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
         errmsg += errStr + wxT("\n");
         reset_c();
         delete [] err;
         throw UtilityException(errmsg);
      }
      #ifdef DEBUG_SPK_COVERAGE
         MessageInterface::ShowMessage(wxT("Kernel is of type %s\n"),
               kernelType);
      #endif
      // only deal with SPK kernels
      if (eqstr_c( kernelType, "spk" ))
      {
         spkobj_c(kernelName, &ids);
         // get the list of objects (IDs) for which data exists in the SPK kernel
         for (SpiceInt jj = 0;  jj < card_c(&ids);  jj++)
         {
            objId = SPICE_CELL_ELEM_I(&ids,jj);
            #ifdef DEBUG_SPK_COVERAGE
               MessageInterface::ShowMessage(wxT("Kernel contains data for object %d\n"),
                     (Integer) objId);
            #endif
            // look to see if this kernel contains data for the object we're interested in
            if (objId == idSpice)
            {
               idOnKernel = true;
               break;
            }
         }
         // only deal with kernels containing data for the object we're interested in
         if (idOnKernel)
         {
            #ifdef DEBUG_SPK_COVERAGE
               MessageInterface::ShowMessage(wxT("Checking kernel %s for data for object %d\n"),
                     (kernels.at(ii)).c_str(), (Integer) objId);
            #endif
            scard_c(0, &cover);   // reset the coverage cell
            spkcov_c (kernelName, idSpice, &cover);
            if (failed_c())
            {
               ConstSpiceChar option[] = "LONG";
               SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
               //SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
               SpiceChar      *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
               getmsg_c(option, numChar, err);
               wxString errStr(wxString::FromAscii(err));
               wxString errmsg = wxT("Error determining coverage for SPK kernel \"");
               errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
               errmsg += errStr + wxT("\n");
               reset_c();
               delete [] err;
               throw UtilityException(errmsg);
            }
            numInt = wncard_c(&cover);
            #ifdef DEBUG_SPK_COVERAGE
               MessageInterface::ShowMessage(wxT("Number of intervals found =  %d\n"),
                     (Integer) numInt);
            #endif
            if ((firstInt) && (numInt > 0))
            {
               wnfetd_c(&cover, 0, &b, &e);
               if (failed_c())
               {
                  ConstSpiceChar option[] = "LONG";
                  SpiceInt       numChar  = MAX_LONG_MESSAGE_VALUE;
                  //SpiceChar      err[MAX_LONG_MESSAGE_VALUE];
                  SpiceChar      *err = new SpiceChar[MAX_LONG_MESSAGE_VALUE];
                  getmsg_c(option, numChar, err);
                  wxString errStr(wxString::FromAscii(err));
                  wxString errmsg = wxT("Error getting interval times for SPK kernel \"");
                  errmsg += kernels.at(ii) + wxT("\".  Message received from CSPICE is: ");
                  errmsg += errStr + wxT("\n");
                  reset_c();
                  delete [] err;
                  throw UtilityException(errmsg);
               }
               start    = SpiceTimeToA1(b);
               end      = SpiceTimeToA1(e);
               firstInt = false;
            }
            for (SpiceInt jj = 0; jj < numInt; jj++)
            {
               wnfetd_c(&cover, jj, &b, &e);
               bA1 = SpiceTimeToA1(b);
               eA1 = SpiceTimeToA1(e);
               if (bA1 < start)  start = bA1;
               if (eA1 > end)    end   = eA1;
            }
         }

      }
   }
   if (firstInt)
   {
      wxString errmsg(wxT(""));
      errmsg << wxT("Error - no data available for body with NAIF ID ") << forNaifId << wxT(" on specified SPK kernels\n");
      throw UtilityException(errmsg);
   }
}
/**
 * This is a wrapper of LoadKernel, which verifies the kernel image specified
 * by set_bootdev. The caller of this functions must have called set_bootdev
 * first.
 *
 * @param boot_flags are bitwise-or'ed of flags in load_kernel_fw.h
 * @param gbb_data points to a GBB blob
 * @param gbb_size is the size of the GBB blob
 * @param vbshared_data points to VbSharedData blob
 * @param vbshared_size is the size of the VbSharedData blob
 * @param nvcxt points to a VbNvContext object
 * @return LoadKernel's return value
 */
static int load_kernel_wrapper(LoadKernelParams *params, uint64_t boot_flags,
		void *gbb_data, uint32_t gbb_size,
		void *vbshared_data, uint32_t vbshared_size,
		VbNvContext *nvcxt)
{
	int status = LOAD_KERNEL_NOT_FOUND;

	memset(params, '\0', sizeof(*params));

	params->boot_flags = boot_flags;

	params->gbb_data = gbb_data;
	params->gbb_size = gbb_size;

	params->shared_data_blob = vbshared_data;
	params->shared_data_size = vbshared_size;

	params->bytes_per_lba = get_bytes_per_lba();
	params->ending_lba = get_ending_lba();

	params->kernel_buffer = (void*)CONFIG_CHROMEOS_KERNEL_LOADADDR;
	params->kernel_buffer_size = CONFIG_CHROMEOS_KERNEL_BUFSIZE;

	params->nv_context = nvcxt;

	VBDEBUG(PREFIX "call LoadKernel() with parameters...\n");
	VBDEBUG(PREFIX "shared_data_blob:     0x%p\n",
			params->shared_data_blob);
	VBDEBUG(PREFIX "bytes_per_lba:        %d\n",
			(int) params->bytes_per_lba);
	VBDEBUG(PREFIX "ending_lba:           0x%08x\n",
			(int) params->ending_lba);
	VBDEBUG(PREFIX "kernel_buffer:        0x%p\n",
			params->kernel_buffer);
	VBDEBUG(PREFIX "kernel_buffer_size:   0x%08x\n",
			(int) params->kernel_buffer_size);
	VBDEBUG(PREFIX "boot_flags:           0x%08x\n",
			(int) params->boot_flags);

	status = LoadKernel(params);

	VBDEBUG(PREFIX "LoadKernel status: %d\n", status);
	if (status == LOAD_KERNEL_SUCCESS) {
		VBDEBUG(PREFIX "partition_number:   0x%08x\n",
				(int) params->partition_number);
		VBDEBUG(PREFIX "bootloader_address: 0x%08x\n",
				(int) params->bootloader_address);
		VBDEBUG(PREFIX "bootloader_size:    0x%08x\n",
				(int) params->bootloader_size);

		/* TODO(clchiou): deprecated when we fix crosbug:14022 */
		if (params->partition_number == 2) {
			setenv("kernelpart", "2");
			setenv("rootpart", "3");
		} else if (params->partition_number == 4) {
			setenv("kernelpart", "4");
			setenv("rootpart", "5");
		} else {
			VBDEBUG(PREFIX "unknown kernel partition: %d\n",
					(int) params->partition_number);
			status = LOAD_KERNEL_NOT_FOUND;
		}
	}

	return status;
}
/**
 * Attempt loading a kernel from the specified type(s) of disks.
 *
 * If successful, sets p->disk_handle to the disk for the kernel and returns
 * VBERROR_SUCCESS.
 *
 * Returns VBERROR_NO_DISK_FOUND if no disks of the specified type were found.
 *
 * May return other VBERROR_ codes for other failures.
 */
uint32_t VbTryLoadKernel(VbCommonParams *cparams, LoadKernelParams *p,
                         uint32_t get_info_flags)
{
    VbError_t retval = VBERROR_UNKNOWN;
    VbDiskInfo* disk_info = NULL;
    uint32_t disk_count = 0;
    uint32_t i;

    VBDEBUG(("VbTryLoadKernel() start, get_info_flags=0x%x\n",
             (unsigned)get_info_flags));

    p->disk_handle = NULL;

    /* Find disks */
    if (VBERROR_SUCCESS != VbExDiskGetInfo(&disk_info, &disk_count,
                                           get_info_flags))
        disk_count = 0;

    VBDEBUG(("VbTryLoadKernel() found %d disks\n", (int)disk_count));
    if (0 == disk_count) {
        VbSetRecoveryRequest(VBNV_RECOVERY_RW_NO_DISK);
        return VBERROR_NO_DISK_FOUND;
    }

    /* Loop over disks */
    for (i = 0; i < disk_count; i++) {
        VBDEBUG(("VbTryLoadKernel() trying disk %d\n", (int)i));
        /*
         * Sanity-check what we can. FWIW, VbTryLoadKernel() is always
         * called with only a single bit set in get_info_flags.
         *
         * Ensure 512-byte sectors and non-trivially sized disk (for
         * cgptlib) and that we got a partition with only the flags we
         * asked for.
         */
        if (512 != disk_info[i].bytes_per_lba ||
                16 > disk_info[i].lba_count ||
                get_info_flags != (disk_info[i].flags & ~VB_DISK_FLAG_EXTERNAL_GPT)) {
            VBDEBUG(("  skipping: bytes_per_lba=%" PRIu64
                     " lba_count=%" PRIu64 " flags=0x%x\n",
                     disk_info[i].bytes_per_lba,
                     disk_info[i].lba_count,
                     disk_info[i].flags));
            continue;
        }
        p->disk_handle = disk_info[i].handle;
        p->bytes_per_lba = disk_info[i].bytes_per_lba;
        p->gpt_lba_count = disk_info[i].lba_count;
        p->streaming_lba_count = disk_info[i].streaming_lba_count
                                 ?: p->gpt_lba_count;
        p->boot_flags |= disk_info[i].flags & VB_DISK_FLAG_EXTERNAL_GPT
                         ? BOOT_FLAG_EXTERNAL_GPT : 0;
        retval = LoadKernel(p, cparams);
        VBDEBUG(("VbTryLoadKernel() LoadKernel() = %d\n", retval));

        /*
         * Stop now if we found a kernel.
         *
         * TODO: If recovery requested, should track the farthest we
         * get, instead of just returning the value from the last disk
         * attempted.
         */
        if (VBERROR_SUCCESS == retval)
            break;
    }

    /* If we didn't find any good kernels, don't return a disk handle. */
    if (VBERROR_SUCCESS != retval) {
        VbSetRecoveryRequest(VBNV_RECOVERY_RW_NO_KERNEL);
        p->disk_handle = NULL;
    }

    VbExDiskFreeInfo(disk_info, p->disk_handle);

    /*
     * Pass through return code.  Recovery reason (if any) has already been
     * set by LoadKernel().
     */
    return retval;
}
示例#10
0
int
Starcon2Main (void *threadArg)
{
#if CREATE_JOURNAL
{
int ac = argc;
char **av = argv;

while (--ac > 0)
{
	++av;
	if ((*av)[0] == '-')
	{
		switch ((*av)[1])
		{
#if CREATE_JOURNAL
			case 'j':
				++create_journal;
				break;
#endif //CREATE_JOURNAL
		}
	}
}
}
#endif // CREATE_JOURNAL

	{
		/* TODO: Put initAudio back in main where it belongs once threading
		 *       is gone.
		 */
		extern sint32 initAudio (sint32 driver, sint32 flags);
		initAudio (snddriver, soundflags);
	}

	if (!LoadKernel (0,0))
	{
		log_add (log_Fatal, "\n  *** FATAL ERROR: Could not load basic content ***\n\nUQM requires at least the base content pack to run properly.");
		log_add (log_Fatal, "This file is typically called uqm-%d.%d.0.uqm.  UQM was expecting it", P6014_MAJOR_VERSION, P6014_MINOR_VERSION);
		log_add (log_Fatal, "in the %s/packages directory.", baseContentPath);
		log_add (log_Fatal, "Either your installation did not install the content pack at all, or it\ninstalled it in a different directory.\n\nFix your installation and rerun UQM.\n\n  *******************\n");
		exit (EXIT_FAILURE);
	}
	log_add (log_Info, "We've loaded the Kernel");

	Logo ();
	
	GLOBAL (CurrentActivity) = 0;
	// show splash and init the kernel in the meantime
	SplashScreen (BackgroundInitKernel);

//	OpenJournal ();
	while (StartGame ())
	{
		// Initialise a new game
		if (!SetPlayerInputAll ()) {
			log_add (log_Fatal, "Could not set player input.");
			explode ();  // Does not return;
		}
		
		InitGameStructures ();
		InitGameClock ();
		AddInitialGameEvents();

		do
		{
#ifdef DEBUG
			if (debugHook != NULL)
			{
				void (*saveDebugHook) (void);
				saveDebugHook = debugHook;
				debugHook = NULL;
						// No further debugHook calls unless the called
						// function resets debugHook.
				(*saveDebugHook) ();
				continue;
			}
#endif
			SetStatusMessageMode (SMM_DEFAULT);

			if (!((GLOBAL (CurrentActivity) | NextActivity) & CHECK_LOAD))
				ZeroVelocityComponents (&GLOBAL (velocity));
					// not going into talking pet conversation
			else if (GLOBAL (CurrentActivity) & CHECK_LOAD)
				GLOBAL (CurrentActivity) = NextActivity;
			
			if ((GLOBAL (CurrentActivity) & START_ENCOUNTER)
					|| GET_GAME_STATE (CHMMR_BOMB_STATE) == 2)
			{
				if (GET_GAME_STATE (CHMMR_BOMB_STATE) == 2
						&& !GET_GAME_STATE (STARBASE_AVAILABLE))
				{	/* BGD mode */
					InstallBombAtEarth ();
				}
				else if (GET_GAME_STATE (GLOBAL_FLAGS_AND_DATA) == (BYTE)~0
						|| GET_GAME_STATE (CHMMR_BOMB_STATE) == 2)
				{
					GLOBAL (CurrentActivity) |= START_ENCOUNTER;
					VisitStarBase ();
				}
				else
				{
					GLOBAL (CurrentActivity) |= START_ENCOUNTER;
					RaceCommunication ();
				}

				if (!(GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_LOAD)))
				{
					GLOBAL (CurrentActivity) &= ~START_ENCOUNTER;
					if (LOBYTE (GLOBAL (CurrentActivity)) == IN_INTERPLANETARY)
						GLOBAL (CurrentActivity) |= START_INTERPLANETARY;
				}
			}
			else if (GLOBAL (CurrentActivity) & START_INTERPLANETARY)
			{
				GLOBAL (CurrentActivity) = MAKE_WORD (IN_INTERPLANETARY, 0);

				DrawAutoPilotMessage (TRUE);
				SetGameClockRate (INTERPLANETARY_CLOCK_RATE);
				ExploreSolarSys ();
			}
			else
			{
				// Entering HyperSpace or QuasiSpace.
				GLOBAL (CurrentActivity) = MAKE_WORD (IN_HYPERSPACE, 0);

				DrawAutoPilotMessage (TRUE);
				SetGameClockRate (HYPERSPACE_CLOCK_RATE);
				Battle (&on_battle_frame);
			}

			LockMutex (GraphicsLock);
			SetFlashRect (NULL);
			UnlockMutex (GraphicsLock);

			LastActivity = GLOBAL (CurrentActivity);

			if (!(GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_LOAD))
					&& (LOBYTE (GLOBAL (CurrentActivity)) == WON_LAST_BATTLE 
						|| LOBYTE (GLOBAL (CurrentActivity)) == BLACK_ORB_CUTSCENE 	// JMS: End demo at cutscene upon finding black orb.
						|| GLOBAL_SIS (CrewEnlisted) == (COUNT)~0)) // if died for some reason
			{
				if (GET_GAME_STATE (KOHR_AH_KILLED_ALL))
					InitCommunication (BLACKURQ_CONVERSATION);
						// surrendered to Ur-Quan
				else if (GLOBAL (CurrentActivity) & CHECK_RESTART)
					GLOBAL (CurrentActivity) &= ~CHECK_RESTART;
				break;
			}
		} while (!(GLOBAL (CurrentActivity) & CHECK_ABORT));

		StopSound ();
		UninitGameClock ();
		UninitGameStructures ();
		ClearPlayerInputAll ();
	}
//	CloseJournal ();

	UninitGameKernel ();
	FreeMasterShipList ();
	FreeKernel ();

	MainExited = TRUE;

	(void) threadArg;  /* Satisfying compiler (unused parameter) */
	return 0;
}