Пример #1
0
int common_init() {
	_printf = find_printf();
	if(_printf == NULL) {
		fb_print("Unable to find printf\n");
		return -1;
	} else {
		printf("Found printf at 0x%x\n", _printf);
	}

	_malloc = find_malloc();
	if(_malloc == NULL) {
		puts("Unable to find malloc\n");
		return -1;
	} else {
		printf("Found malloc at 0x%x\n", _malloc);
	}

	_free = find_free();
	if(_free == NULL) {
		puts("Unable to find free\n");
		return -1;
	} else {
		printf("Found free at 0x%x\n", _free);
	}

	return 0;
}
Пример #2
0
int add_dword(char *str)
{
	char *equals = NULL;
	struct EntryContainer *entry;

	equals = strchr(str, '=');
	if(equals == NULL)
	{
		fprintf(stderr, "Invalid option (no =)\n");
		return 0;
	}

	*equals++ = 0;

	if ((entry = find_name(str)))
	{
		entry->value = strtoul(equals, NULL, 0);
	}
	else
	{
		entry = find_free();
		if(entry == NULL)
		{
			fprintf(stderr, "Maximum options reached\n");
			return 0;
		}

		memset(entry, 0, sizeof(struct EntryContainer));
		entry->name = str;
		entry->type = PSF_TYPE_VAL;
		entry->value = strtoul(equals, NULL, 0);		
	}

	return 1;
}
Пример #3
0
void enter(void){
	int slot;
	char str[80];
	slot = find_free();
	if(slot == -1){
		printf("\nList Full\n");
	}

	printf("Enter name: ");
	gets(addr_list[slot].name);

	printf("Enter street: ");
	gets(addr_list[slot].street);

	printf("Enter city: ");
	gets(addr_list[slot].city);
	
	printf("Enter state: ");
	gets(addr_list[slot].state);

	printf("Enter zip: ");
	gets(str);
	addr_list[slot].zip = strtoul(str, '\0', 10);

}
Пример #4
0
/* rounds up to nearest chunk size */
void *memory_allocate(uint32_t size, uint32_t type) {

	int first_chunk;
	int num_chunks;
	int i;
	int start,end;

	if (memory_debug) {
		printk("Allocating memory of size %d bytes\n",size);
	}

	if (size==0) size=1;

	num_chunks = ((size-1)/CHUNK_SIZE)+1;

	if (memory_debug) {
		printk("\tRounding up to %d %d chunks\n",num_chunks,CHUNK_SIZE);
	}

	if (type==MEMORY_KERNEL) {
		start=0;
		end=RESERVED_KERNEL/CHUNK_SIZE;
	}
	else if (type==MEMORY_USER) {
		start=RESERVED_KERNEL/CHUNK_SIZE;
		end=max_chunk;
	}
	else {
		printk("\tUnknown memory allocation type %d\n",type);
		return NULL;
	}

	mutex_lock(&memory_mutex);

	first_chunk=find_free(num_chunks,start,end);

	if (first_chunk<0) {
		printk("Error!  Could not allocate %d of memory!\n",size);
		mutex_unlock(&memory_mutex);
		return NULL;
	}

	for(i=0;i<num_chunks;i++) {
		memory_mark_used(first_chunk+i);
	}

	mutex_unlock(&memory_mutex);

	/* clear memory to zero, both for bss and also security reasons */
	memset((void *)(first_chunk*CHUNK_SIZE),0,num_chunks*CHUNK_SIZE);

	if (memory_debug) {
		printk("MEM: Allocated %d bytes at %x\n",
			size,first_chunk*CHUNK_SIZE);
	}

	return (void *)(first_chunk*CHUNK_SIZE);

}
Пример #5
0
// Find the first unused area of flash which is long enough
static bool
fis_find_free(CYG_ADDRESS *addr, unsigned long length)
{
#ifndef CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS
    unsigned long *fis_ptr, *fis_end, flash_data;
    unsigned long *area_start;
    void *err_addr;

    // Do not search the area reserved for pre-RedBoot systems:
    fis_ptr = (unsigned long *)((CYG_ADDRESS)flash_start + 
                                CYGNUM_REDBOOT_FLASH_RESERVED_BASE + 
                                CYGBLD_REDBOOT_MIN_IMAGE_SIZE);
    fis_end = (unsigned long *)(CYG_ADDRESS)flash_end;
    area_start = fis_ptr;
    while (fis_ptr < fis_end) {
        flash_read(fis_ptr, &flash_data, sizeof(unsigned long), (void **)&err_addr);
        if (flash_data != (unsigned long)0xFFFFFFFF) {
            if (area_start != fis_ptr) {
                // Assume that this is something
                if ((fis_ptr-area_start) >= (length/sizeof(unsigned))) {
                    *addr = (CYG_ADDRESS)area_start;
                    return true;
                }
            }
            // Find next blank block
            area_start = fis_ptr;
            while (area_start < fis_end) {
                flash_read(area_start, &flash_data, sizeof(unsigned long), (void **)&err_addr);
                if (flash_data == (unsigned long)0xFFFFFFFF) {
                    break;
                }
                area_start += flash_block_size / sizeof(CYG_ADDRESS);
            }
            fis_ptr = area_start;
        } else {
            fis_ptr += flash_block_size / sizeof(CYG_ADDRESS);
        }
    }
    if (area_start != fis_ptr) {
        if ((fis_ptr-area_start) >= (length/sizeof(unsigned))) {
            *addr = (CYG_ADDRESS)area_start;
            return true;
        }
    }
    return false;
#else
    struct free_chunk chunks[CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS];
    int idx, num_chunks;

    num_chunks = find_free(chunks);
    for (idx = 0;  idx < num_chunks;  idx++) {
        if ((chunks[idx].end - chunks[idx].start) >= length) {
            *addr = (CYG_ADDRESS)chunks[idx].start;
            return true;
        }
    }
    return false;
#endif
}
Пример #6
0
void add_entry()
{
   int slot;
   int curr_char;
   char in_char;

   slot = find_free ();
   if ( slot == -1 )
   {
      printf ("\nDatabase full !!");
      return;
   } /* if */

   printf ("Enter name ----> ");
   gets (account[slot].name);

   printf ("Enter street ----> ");
   gets (account[slot].street);

   printf ("Enter city ----> ");
   gets (account[slot].city);

   printf ("Enter deposit ----> ");
   scanf ("%f", &account[slot].balance);

   fflush(stdin);

   printf ("Enter phone number { (ac)num-numm } ---->(");

   get_numbers(&account[slot].phonenum[0],3);

   printf(")-");

   get_numbers(&account[slot].phonenum[3],3);

   printf("-");

   get_numbers(&account[slot].phonenum[6],4);

   printf("\n");

   printf ("Enter SS number { ###-##-#### } ---->");

   get_numbers(&account[slot].ssnum[0],3);

   printf("-");

   get_numbers(&account[slot].ssnum[3],2);

   printf("-");

   get_numbers(&account[slot].ssnum[5],4);

   printf("\n");


} /* add_entry */
Пример #7
0
static int alloc_block(struct filesys *fs)
{
	int bno;

	if((bno = find_free(fs->sb->bm, fs->sb->num_blocks)) == -1) {
		return -1;
	}
	BM_SET(fs->sb->bm, bno);
	return 0;
}
Пример #8
0
static int alloc_inode(struct filesys *fs)
{
	int ino;

	if((ino = find_free(fs->sb->ibm, fs->sb->num_inodes)) == -1) {
		return -1;
	}
	BM_SET(fs->sb->ibm, ino);
	return 0;
}
Пример #9
0
static void
fis_free(int argc, char *argv[])
{
#ifndef CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS
    unsigned long *fis_ptr, *fis_end, flash_data;
    unsigned long *area_start;
    void *err_addr;

    // Do not search the area reserved for pre-RedBoot systems:
    fis_ptr = (unsigned long *)((CYG_ADDRESS)flash_start + 
                                CYGNUM_REDBOOT_FLASH_RESERVED_BASE + 
                                CYGBLD_REDBOOT_MIN_IMAGE_SIZE);
    fis_end = (unsigned long *)(CYG_ADDRESS)flash_end;
    area_start = fis_ptr;
    while (fis_ptr < fis_end) {
        flash_read(fis_ptr, &flash_data, sizeof(unsigned long), (void **)&err_addr);
        if (flash_data != (unsigned long)0xFFFFFFFF) {
            if (area_start != fis_ptr) {
                // Assume that this is something
                diag_printf("  0x%08lX .. 0x%08lX\n",
                            (CYG_ADDRESS)area_start, (CYG_ADDRESS)fis_ptr);
            }
            // Find next blank block
            area_start = fis_ptr;
            while (area_start < fis_end) {
                flash_read(area_start, &flash_data, sizeof(unsigned long), (void **)&err_addr);
                if (flash_data == (unsigned long)0xFFFFFFFF) {
                    break;
                }
                area_start += flash_block_size / sizeof(CYG_ADDRESS);
            }
            fis_ptr = area_start;
        } else {
            fis_ptr += flash_block_size / sizeof(CYG_ADDRESS);
        }
    }
    if (area_start != fis_ptr) {
        diag_printf("  0x%08lX .. 0x%08lX\n", 
                    (CYG_ADDRESS)area_start, (CYG_ADDRESS)fis_ptr);
    }
#else
    struct free_chunk chunks[CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS];
    int idx, num_chunks;

    num_chunks = find_free(chunks);
    for (idx = 0;  idx < num_chunks;  idx++) {
        diag_printf("  0x%08lX .. 0x%08lX\n", chunks[idx].start, chunks[idx].end);
    }
#endif
}
Пример #10
0
/* Input the inventory information. */
void enter(void)
{
int slot;
slot = find_free();
if(slot == -1) {
printf("\nList Full");
return;
}
printf("Enter item: ");
gets(inv_info[slot].item);
printf("Enter cost: ");
scanf("%f", &inv_info[slot].cost);
printf("Enter number on hand: ");
scanf("%d%*c", &inv_info[slot].on_hand);
}
Пример #11
0
Файл: index.c Проект: Tzero2/pd
/* add a symbol to the map (if possible) */
static void index_add(t_index *x, t_symbol *s, t_float f)
{
  int newentry=(int)f;

  if (! (find_item(s, x->names, x->maxentries)+1) ) {
    if (x->auto_resize && (x->entries==x->maxentries || newentry>=x->maxentries)){
      /* do some resizing */
      int maxentries=(newentry>x->maxentries)?newentry:(x->maxentries*2);
      int i;
      t_symbol**buf=(t_symbol **)getbytes(sizeof(t_symbol *) * maxentries);
      if(buf!=0){
        memcpy(buf, x->names, sizeof(t_symbol *) * x->maxentries);
        for(i=x->maxentries; i<maxentries; i++)buf[i]=0;

        freebytes(x->names, sizeof(t_symbol *) * x->maxentries);

        x->names=buf;
        x->maxentries=maxentries;
      }
    }

    if ( x->entries < x->maxentries ) {
      if(newentry>0){
        newentry--;
        if(x->names[newentry]){ /* it is already taken! */
          z_verbose(1, "index :: couldn't add element '%s' at position %d (already taken)", s->s_name, newentry+1);
          outlet_float(x->x_obj.ob_outlet, -1.f);
          return;
        }
      } else {
        newentry=find_free(x->names, x->maxentries);
      }
      if (newentry + 1) {
	x->entries++;
	x->names[newentry]=s;
	outlet_float(x->x_obj.ob_outlet, (t_float)newentry+1);
        return;

      } else error("index :: couldn't find any place for new entry");
    } else error("index :: max number of elements (%d) reached !", x->maxentries);
  } else  z_verbose(1, "index :: element '%s' already exists", s->s_name);
  /* couldn't add the symbol to our index table */
  outlet_float(x->x_obj.ob_outlet, -1.f);
}
Пример #12
0
/* Initializes a position on the options table. This is intended to be used at
 * initialization to make a table of valid options and its default values. */
static int option_init(const char *name, enum option_type type)
{
	unsigned int h=hash(name);
	int pos=find_free(h);
	
	assert (strlen(name) < OPTION_NAME_MAX);
	assert(pos>=0);
	
	strcpy (options[pos].name, name);
	options[pos].hash=h;
	options[pos].type = type;
	options[pos].ignore_in_config = 0;
	options[pos].set_in_config = 0;
	options[pos].check = option_check_true;
	options[pos].count = 0;
	options[pos].constraints = NULL;

	options_num++;
	return pos;
}
Пример #13
0
void addRecord()
{
    system("cls");
    int slot;
    slot=find_free();
    if(slot==-1)
    {
        printf("DB is full");
        return 0;
    }

    printf("Enter mountain name:\n");
    scanf("%s", &Mountain_list[slot].mountainName);
    printf("Enter mountain location:\n");
    scanf("%s", &Mountain_list[slot].mountainLocation);
    printf("Enter mountain height:\n");
    scanf("%d", &Mountain_list[slot].mountainHeight);
    printf("Enter mountain slope angle:\n");
    scanf("%d", &Mountain_list[slot].mountainSlopeAngle);
    printf("Mountain as a glacier(enter yes or no):\n");
    scanf("%s", &Mountain_list[slot].mountainHasAGlacier);
}
Пример #14
0
int parameter_flashfs_init(sector_descriptor_t *fconfig, uint8_t *buffer, uint16_t size)
{
	int rv = 0;
	sector_map = fconfig;
	working_buffer_static = buffer != NULL;

	if (!working_buffer_static) {
		size = 0;
	}

	working_buffer = buffer;
	working_buffer_size = size;
	last_erased = -1;

	/* Sanity check */

	flash_entry_header_t *pf = find_entry(parameters_token);

	/*  No paramaters */

	if (pf == NULL) {
		size_t total_size = size + sizeof(flash_entry_header_t);
		size_t alignment = sizeof(h_magic_t) - 1;
		size_t  size_adjust = ((total_size + alignment) & ~alignment) - total_size;
		total_size += size_adjust;

		/* Do we have free space ?*/

		if (find_free(total_size) == NULL) {

			/* No paramates and no free space => neeed erase */

			rv  = parameter_flashfs_erase();
		}
	}

	return rv;
}
Пример #15
0
void dfs(int from, int to)
{
	 if (position[to]!= 0)  // to的目标位置有人坐了
	 {
			if (visited[to]== false)
			{
				   visited[from]= true;
				   dfs(to,position[to]);
			}
			else  // 这个to
			{
				   flag = to;
				   free_c = find_free();
				   move(to,free_c);
			}
	 }

	 if (from !=flag)   // flag只记录那个被放到最后的位置号 
			move(from,to);
	 else
			move(free_c,to);

}
Пример #16
0
/* 
 * mm_malloc - Allocate a block by incrementing the brk pointer.
 *     Always allocate a block whose size is a multiple of the alignment.
 */
void *mm_malloc(size_t size)
{
    /* Ignore spurious requests */
    if (size < 1)
        return NULL;

    /* The size of the new block is equal to the size of the header, plus
     * the size of the payload
     */
    int newsize = ALIGN(size + HSIZE);
    
    /* Try to find a free block that is large enough */
    hblock *bp = (hblock *) find_free(newsize);
   
    /* If a large enough free block was not found, then coalesce
     * the existing free blocks */ 

    /* After coalsecing, if a large enough free block cannot be found, then
     * extend the heap with a free block */
    if (bp == NULL) { 
        bp = mem_sbrk(newsize);
        if ((long)(bp) == -1)
            return NULL;
        else {
            bp->header = newsize | 0x1;
            bp->footer = bp->header;
        }
    }
    else {
        /* Otherwise, a free block of the appropriate size was found. Place
         * the block */
        place(bp, newsize); 
    }

    // Return a pointer to the payload
    return (char *) bp + HSIZE;
}
Пример #17
0
void* cuda_malloc(long size)
{
	if (cuda_memcache) {

		struct cuda_mem_s* nptr = find_free(size);

		if (NULL != nptr) {

			assert(nptr->device);
			assert(!nptr->free);

			nptr->thread_id = omp_get_thread_num();

			return (void*)(nptr->ptr);
		}
	}

	void* ptr;
        CUDA_ERROR(cudaMalloc(&ptr, size));

	insert(ptr, size, true);

	return ptr;
}
Пример #18
0
static void
fis_create(int argc, char *argv[])
{
    int i, stat;
    unsigned long length, img_size;
    CYG_ADDRESS mem_addr, exec_addr, flash_addr, entry_addr;
    char *name;
    bool mem_addr_set = false;
    bool exec_addr_set = false;
    bool entry_addr_set = false;
    bool flash_addr_set = false;
    bool length_set = false;
    bool img_size_set = false;
    bool no_copy = false;
    void *err_addr;
    struct fis_image_desc *img = NULL;
    bool defaults_assumed;
    struct option_info opts[7];
    bool prog_ok = true;

    init_opts(&opts[0], 'b', true, OPTION_ARG_TYPE_NUM, 
              (void *)&mem_addr, (bool *)&mem_addr_set, "memory base address");
    init_opts(&opts[1], 'r', true, OPTION_ARG_TYPE_NUM, 
              (void *)&exec_addr, (bool *)&exec_addr_set, "ram base address");
    init_opts(&opts[2], 'e', true, OPTION_ARG_TYPE_NUM, 
              (void *)&entry_addr, (bool *)&entry_addr_set, "entry point address");
    init_opts(&opts[3], 'f', true, OPTION_ARG_TYPE_NUM, 
              (void *)&flash_addr, (bool *)&flash_addr_set, "FLASH memory base address");
    init_opts(&opts[4], 'l', true, OPTION_ARG_TYPE_NUM, 
              (void *)&length, (bool *)&length_set, "image length [in FLASH]");
    init_opts(&opts[5], 's', true, OPTION_ARG_TYPE_NUM, 
              (void *)&img_size, (bool *)&img_size_set, "image size [actual data]");
    init_opts(&opts[6], 'n', false, OPTION_ARG_TYPE_FLG, 
              (void *)&no_copy, (bool *)0, "don't copy from RAM to FLASH, just update directory");
    if (!scan_opts(argc, argv, 2, opts, 7, (void *)&name, OPTION_ARG_TYPE_STR, "file name"))
    {
        fis_usage("invalid arguments");
        return;
    }

    fis_read_directory();
    defaults_assumed = false;
    if (name) {
        // Search existing files to acquire defaults for params not specified:
        img = fis_lookup(name, NULL);
        if (img) {
            // Found it, so get image size from there
            if (!length_set) {
                length_set = true;
                length = img->size;
                defaults_assumed = true;
            }
        }
    }
    if (!mem_addr_set && (load_address >= (CYG_ADDRESS)ram_start) &&
	(load_address_end) < (CYG_ADDRESS)ram_end) {
	mem_addr = load_address;
	mem_addr_set = true;
        defaults_assumed = true;
        // Get entry address from loader, unless overridden
        if (!entry_addr_set)
            entry_addr = entry_address;
	if (!length_set) {
	    length = load_address_end - load_address;
	    length_set = true;
	} else if (defaults_assumed && !img_size_set) {
	    /* We got length from the FIS table, so the size of the
	       actual loaded image becomes img_size */
	    img_size = load_address_end - load_address;
	    img_size_set = true;
	}
    }
    // Get the remaining fall-back values from the fis
    if (img) {
        if (!exec_addr_set) {
            // Preserve "normal" behaviour
            exec_addr_set = true;
            exec_addr = flash_addr_set ? flash_addr : mem_addr;
        }
        if (!flash_addr_set) {
            flash_addr_set = true;
            flash_addr = img->flash_base;
            defaults_assumed = true;
        }
    }

    if ((!no_copy && !mem_addr_set) || (no_copy && !flash_addr_set) ||
        !length_set || !name) {
        fis_usage("required parameter missing");
        return;
    }
    if (!img_size_set) {
        img_size = length;
    }
    // 'length' is size of FLASH image, 'img_size' is actual data size
    // Round up length to FLASH block size
#ifndef CYGPKG_HAL_MIPS // FIXME: compiler is b0rken
    length = ((length + flash_block_size - 1) / flash_block_size) * flash_block_size;
    if (length < img_size) {
        diag_printf("Invalid FLASH image size/length combination\n");
        return;
    }
#endif
    if (flash_addr_set &&
        ((stat = flash_verify_addr((void *)flash_addr)) ||
         (stat = flash_verify_addr((void *)(flash_addr+length-1))))) {
        _show_invalid_flash_address(flash_addr, stat);
        return;
    }
    if (flash_addr_set && ((flash_addr & (flash_block_size-1)) != 0)) {
        diag_printf("Invalid FLASH address: %p\n", (void *)flash_addr);
        diag_printf("   must be 0x%x aligned\n", flash_block_size);
        return;
    }
    if (strlen(name) >= sizeof(img->name)) {
        diag_printf("Name is too long, must be less than %d chars\n", (int)sizeof(img->name));
        return;
    }
    if (!no_copy) {
        if ((mem_addr < (CYG_ADDRESS)ram_start) ||
            ((mem_addr+img_size) >= (CYG_ADDRESS)ram_end)) {
            diag_printf("** WARNING: RAM address: %p may be invalid\n", (void *)mem_addr);
            diag_printf("   valid range is %p-%p\n", (void *)ram_start, (void *)ram_end);
        }
        if (!flash_addr_set && !fis_find_free(&flash_addr, length)) {
            diag_printf("Can't locate %lx(%ld) bytes free in FLASH\n", length, length);
            return;
        }
    }
    // First, see if the image by this name has agreable properties
    if (img) {
        if (flash_addr_set && (img->flash_base != flash_addr)) {
            diag_printf("Image found, but flash address (%p)\n"
                        "             is incorrect (present image location %p)\n",
                        flash_addr, img->flash_base);
            
            return;
        }
        if (img->size != length) {
            diag_printf("Image found, but length (0x%lx, necessitating image size 0x%lx)\n"
                        "             is incorrect (present image size 0x%lx)\n",
                        img_size, length, img->size);
            return;
        }
        if (!verify_action("An image named '%s' exists", name)) {
            return;
        } else {                
            if (defaults_assumed) {
                if (no_copy &&
                    !verify_action("* CAUTION * about to program '%s'\n            at %p..%p from %p", 
                                   name, (void *)flash_addr, (void *)(flash_addr+img_size-1),
                                   (void *)mem_addr)) {
                    return;  // The guy gave up
                }
            }
        }
    } else {
#ifdef CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS
        // Make sure that any FLASH address specified directly is truly free
        if (flash_addr_set && !no_copy) {
            struct free_chunk chunks[CYGDAT_REDBOOT_FIS_MAX_FREE_CHUNKS];
            int idx, num_chunks;
            bool is_free = false;

            num_chunks = find_free(chunks);
            for (idx = 0;  idx < num_chunks;  idx++) {
                if ((flash_addr >= chunks[idx].start) && 
                    ((flash_addr+length-1) <= chunks[idx].end)) {
                    is_free = true;
                }
            }
            if (!is_free) {
                diag_printf("Invalid FLASH address - not free!\n");
                return;
            }
        }
#endif
        // If not image by that name, try and find an empty slot
        img = (struct fis_image_desc *)fis_work_block;
        for (i = 0;  i < fisdir_size/sizeof(*img);  i++, img++) {
            if (img->name[0] == (unsigned char)0xFF) {
                break;
            }
        }
    }
    if (!no_copy) {
        // Safety check - make sure the address range is not within the code we're running
        if (flash_code_overlaps((void *)flash_addr, (void *)(flash_addr+img_size-1))) {
            diag_printf("Can't program this region - contains code in use!\n");
            return;
        }
        if (prog_ok) {
            // Erase area to be programmed
            if ((stat = flash_erase((void *)flash_addr, length, (void **)&err_addr)) != 0) {
                diag_printf("Can't erase region at %p: %s\n", err_addr, flash_errmsg(stat));
                prog_ok = false;
            }
        }
        if (prog_ok) {
            // Now program it
            if ((stat = FLASH_PROGRAM((void *)flash_addr, (void *)mem_addr, img_size, (void **)&err_addr)) != 0) {
                diag_printf("Can't program region at %p: %s\n", err_addr, flash_errmsg(stat));
                prog_ok = false;
            }
        }
    }
    if (prog_ok) {
        // Update directory
        memset(img, 0, sizeof(*img));
        strcpy(img->name, name);
        img->flash_base = flash_addr;
        img->mem_base = exec_addr_set ? exec_addr : (flash_addr_set ? flash_addr : mem_addr);
        img->entry_point = entry_addr_set ? entry_addr : (CYG_ADDRESS)entry_address;  // Hope it's been set
        img->size = length;
        img->data_length = img_size;
#ifdef CYGSEM_REDBOOT_FIS_CRC_CHECK
        if (!no_copy) {
            img->file_cksum = cyg_crc32((unsigned char *)mem_addr, img_size);
        } else {
            // No way to compute this, sorry
            img->file_cksum = 0;
        }
#endif
        fis_update_directory();
    }
}
Пример #19
0
int main(int argc, char **argv)
{
	FILE *fp;
	int i;
	char head[8192];
	char keys[8192];
	char data[8192];
	struct SfoHeader *h;
	struct SfoEntry  *e;
	char *k;
	char *d;
	unsigned int align;
	unsigned int keyofs;
	unsigned int count;
	
	for(i = 0; i < (sizeof(g_defaults) / sizeof(struct EntryContainer)); i++)
	{
		struct EntryContainer *entry = find_free();
		if(entry == NULL)
		{
			fprintf(stderr, "Maximum options reached\n");
			return 0;
		}
		*entry = g_defaults[i];
	}
	
	if(!process_args(argc, argv)) 
	{
		fprintf(stderr, "Usage: mksfoex [options] TITLE output.sfo\n");
		fprintf(stderr, "Options:\n");
		fprintf(stderr, "-d NAME=VALUE - Add a new DWORD value\n");
		fprintf(stderr, "-s NAME=STR   - Add a new string value\n");

		return 1;
	}
	
	if (g_title)
	{
		struct EntryContainer *entry = find_name("TITLE");
		entry->data = g_title;
		
		entry = find_name("STITLE");
		entry->data = g_title;
	}

	memset(head, 0, sizeof(head));
	memset(keys, 0, sizeof(keys));
	memset(data, 0, sizeof(data));
	h = (struct SfoHeader*) head;
	e = (struct SfoEntry*)  (head+sizeof(struct SfoHeader));
	k = keys;
	d = data;
	SW(&h->magic, PSF_MAGIC);
	SW(&h->version, PSF_VERSION);
	count = 0;

	for(i = 0; g_vals[i].name; i++)
	{
		SW(&h->count, ++count);
		SW(&e->nameofs, k-keys);
		SW(&e->dataofs, d-data);
		SW(&e->alignment, 4);
		SW(&e->type, g_vals[i].type);

		strcpy(k, g_vals[i].name);
		k += strlen(k)+1;
		if(e->type == PSF_TYPE_VAL)
		{
			SW(&e->valsize, 4);
			SW(&e->totalsize, 4);
			SW((uint32_t*) d, g_vals[i].value);
			d += 4;
		}
		else
		{
			int totalsize;
			int valsize = 0;

			if (g_vals[i].data)
				valsize = strlen(g_vals[i].data)+1;
			totalsize = (g_vals[i].value) ? (g_vals[i].value) : ((valsize + 3) & ~3);
			SW(&e->valsize, valsize);
			SW(&e->totalsize, totalsize);
			memset(d, 0, totalsize);
			
			if (g_vals[i].data)
				memcpy(d, g_vals[i].data, valsize);
			d += totalsize;
		}
		e++;
	}


	keyofs = (char*)e - head;
	SW(&h->keyofs, keyofs);
	align = 3 - ((unsigned int) (k-keys) & 3);
	while(align < 3)
	{
		k++;
		align--;
	}
	
	SW(&h->valofs, keyofs + (k-keys));

	fp = fopen(g_filename, "wb");
	if(fp == NULL)
	{
		fprintf(stderr, "Cannot open filename %s\n", g_filename);
		return 0;
	}

	fwrite(head, 1, (char*)e-head, fp);
	fwrite(keys, 1, k-keys, fp);
	fwrite(data, 1, d-data, fp);
	fclose(fp);

	return 0;
}
Пример #20
0
int
parameter_flashfs_write(flash_file_token_t token, uint8_t *buffer, size_t buf_size)
{
	int rv = -ENXIO;

	if (sector_map) {

		rv = 0;

		/* Calculate the total space needed */

		size_t total_size = buf_size + sizeof(flash_entry_header_t);
		size_t alignment = sizeof(h_magic_t) - 1;
		size_t  size_adjust = ((total_size + alignment) & ~alignment) - total_size;
		total_size += size_adjust;

		/* Is this and existing entry */

		flash_entry_header_t *pf = find_entry(token);

		if (!pf) {

			/* No Entry exists for this token so find a place for it */

			pf = find_free(total_size);

			/* No Space */

			if (pf == 0) {
				return -ENOSPC;
			}

		} else {

			/* Do we have space after the entry in the sector for the update */

			sector_descriptor_t *current_sector = check_free_space_in_sector(pf,
							      total_size);


			if (current_sector == 0) {

				/* Mark the last entry erased */

				/* todo:consider a 2 stage erase or write before erase and do a fs check
				 * at start up
				 */

				rv = erase_entry(pf);

				if (rv < 0) {
					return rv;
				}

				/* We had space and marked the last entry erased so use the  Next Free */

				pf = next_entry(pf);

			} else {

				/*
				 * We did not have space in the current sector so select the next sector
				 */

				current_sector = get_next_sector_descriptor(current_sector);

				/* Will the data fit */

				if (current_sector->size < total_size) {
					return -ENOSPC;
				}

				/* Mark the last entry erased */

				/* todo:consider a 2 stage erase or write before erase and do a fs check
				 * at start up
				 */

				rv = erase_entry(pf);

				if (rv < 0) {
					return rv;
				}

				pf = (flash_entry_header_t *) current_sector->address;
			}

			if (!blank_check(pf, total_size)) {
				rv = erase_sector(current_sector, pf);
			}
		}

		flash_entry_header_t *pn = (flash_entry_header_t *)(buffer - sizeof(flash_entry_header_t));
		pn->magic = MagicSig;
		pn->file_token.t = token.t;
		pn->flag = ValidEntry + size_adjust;
		pn->size = total_size;

		for (size_t a = 0; a < size_adjust; a++) {
			buffer[buf_size + a] = (uint8_t)BlankSig;
		}

		pn->crc = crc32(entry_crc_start(pn), entry_crc_length(pn));
		rv = up_progmem_write((size_t) pf, pn, pn->size);
		int system_bytes = (sizeof(flash_entry_header_t) + size_adjust);

		if (rv >= system_bytes) {
			rv -= system_bytes;
		}
	}

	return rv;
}
Пример #21
0
rrl_item_t* rrl_hash(rrl_table_t *t, const struct sockaddr_storage *a, rrl_req_t *p,
                     const zone_t *zone, uint32_t stamp, int *lock)
{
    char buf[RRL_CLSBLK_MAXLEN];
    int len = rrl_classify(buf, sizeof(buf), a, p, zone, t->seed);
    if (len < 0) {
        return NULL;
    }

    uint32_t id = hash(buf, len) % t->size;

    /* Lock for lookup. */
    pthread_mutex_lock(&t->ll);

    /* Find an exact match in <id, id + HOP_LEN). */
    uint16_t *qname = (uint16_t*)(buf + sizeof(uint8_t) + sizeof(uint64_t));
    rrl_item_t match = {
        0, *((uint64_t*)(buf + 1)), t->rate,    /* hop, netblk, ntok */
        buf[0], RRL_BF_NULL,                    /* cls, flags */
        hash((char*)(qname + 1), *qname), stamp /* qname, time*/
    };

    unsigned d = find_match(t, id, &match);
    if (d > HOP_LEN) { /* not an exact match, find free element [f] */
        d = find_free(t, id, stamp);
    }

    /* Reduce distance to fit <id, id + HOP_LEN) */
    unsigned f = (id + d) % t->size;
    while (d >= HOP_LEN) {
        d = reduce_dist(t, id, d, &f);
    }

    /* Assign granular lock and unlock lookup. */
    *lock = f % t->lk_count;
    rrl_lock(t, *lock);
    pthread_mutex_unlock(&t->ll);

    /* found free elm 'k' which is in <id, id + HOP_LEN) */
    t->arr[id].hop |= (1 << d);
    rrl_item_t* b = t->arr + f;
    assert(f == (id+d) % t->size);
    dbg_rrl("%s: classified pkt as %4x '%u+%u' bucket=%p \n", __func__, f, id, d, b);

    /* Inspect bucket state. */
    unsigned hop = b->hop;
    if (b->cls == CLS_NULL) {
        memcpy(b, &match, sizeof(rrl_item_t));
        b->hop = hop;
    }
    /* Check for collisions. */
    if (!bucket_match(b, &match)) {
        dbg_rrl("%s: collision in bucket '%4x'\n", __func__, id);
        if (!(b->flags & RRL_BF_SSTART)) {
            memcpy(b, &match, sizeof(rrl_item_t));
            b->hop = hop;
            b->ntok = t->rate + t->rate / RRL_SSTART;
            b->flags |= RRL_BF_SSTART;
            dbg_rrl("%s: bucket '%4x' slow-start\n", __func__, id);
        }
    }

    return b;
}
Пример #22
0
value_t *hhash_map(hhash_t* tbl, const char* key, uint16_t len, uint16_t mode)
{
	if (tbl == NULL) {
		return NULL;
	}

	/* Find an exact match in <id, id + HOP_LEN). */
	uint32_t id = hash(key, len) % tbl->size;
	int dist = find_match(tbl, id, key, len);
	if (dist <= HOP_LEN) {
		/* Found exact match, return value. */
		hhelem_t *match = &tbl->item[(id + dist) % tbl->size];
		return (value_t *)KEY_VAL(match->d);
	}

	/* We didn't find an exact match, continue only if inserting. */
	if (!(mode & HHASH_INSERT)) {
		return NULL;
	} else if (tbl->weight >= tbl->size) { /* Or full table. */
		return NULL;
	}

	/* Reduce distance to fit <id, id + HOP_LEN) */
	dist = find_free(tbl, id);
	if (dist < 0) { /* Did not find any fit. */
		return NULL;
	}
	int empty = (id + dist) % tbl->size;
	while (dist >= HOP_LEN) {
		dist = reduce_dist(tbl, dist, &empty);
		/* Couldn't reduce the distance, no fit available. */
		if (dist < 0) {
			return NULL;
		}
	}

	/* Insert to given position. */
	char *new_key = tbl->mm.alloc(tbl->mm.ctx, HHKEY_LEN + len);
	if (new_key != NULL) {
		memset(KEY_VAL(new_key), 0,    sizeof(value_t));
		memcpy(KEY_LEN(new_key), &len, sizeof(uint16_t));
		memcpy(KEY_STR(new_key), key,  len);
	} else {
		return NULL;
	}

	/* found free elm 'k' which is in <id, id + HOP_LEN) */
	assert(tbl->item[empty].d == NULL);
	tbl->item[id].hop |= HOP_BIT(dist);
	tbl->item[empty].d = new_key;

	++tbl->weight;

	/* Free old index. */
	if (tbl->index) {
		if (tbl->mm.free) {
			free(tbl->index);
		}
		tbl->index = NULL;
	}

	return (value_t *)KEY_VAL(new_key);
}
Пример #23
0
void data_migrate(struct pool_info *pool,unsigned int device)
{
	unsigned int i;

	/*
		use multiple FOR loop to make sure that there are enough space in SCM and SSD
		to satisfy the data migration from SSD or HDD.
	*/
	if(device==SCM)
	{
		for(i=pool->chunk_min;i<=pool->chunk_max;i++)
		{
			if(pool->chunk[i].location==SCM)
			{
				if(pool->chunk[i].location==SCM)
				{
					pool->migrate_scm_scm++;
				}
				else if(pool->chunk[i].location_next==HDD)
				{
					if(find_free(pool,HDD)==SUCCESS)
					{
						pool->migrate_scm_hdd++;
						pool->chunk[i].location=HDD;
						pool->free_chk_hdd--;
						pool->free_chk_scm++;
					}	
					else
					{
						printf("No free storage space in HDD ?\n");
					}
				}
				else if(pool->chunk[i].location_next==SSD)
				{
					if(find_free(pool,SSD)==SUCCESS)
					{
						pool->migrate_scm_ssd++;
						pool->chunk[i].location=SSD;
						pool->free_chk_ssd--;
						pool->free_chk_scm++;
					}
					else
					{
						printf("No free storage space in SSD ?\n");
					}

				}
			}//scm
		}//for
	}//if
	else if(device==SSD)
	{
		for(i=pool->chunk_min;i<=pool->chunk_max;i++)
		{
			if(pool->chunk[i].location==SSD)
			{
				if(pool->chunk[i].location==SSD)
				{
					pool->migrate_ssd_ssd++;
				}
				else if(pool->chunk[i].location_next==HDD)
				{
					if(find_free(pool,HDD)==SUCCESS)
					{
						pool->migrate_ssd_hdd++;
						pool->chunk[i].location=HDD;
						pool->free_chk_hdd--;
						pool->free_chk_ssd++;
					}
					else
					{
						printf("No free storage space in HDD ?\n");
					}
				}
				else if(pool->chunk[i].location_next==SCM)
				{
					if(find_free(pool,SCM)==SUCCESS)
					{
						pool->migrate_ssd_scm++;
						pool->chunk[i].location=SCM;
						pool->free_chk_scm--;
						pool->free_chk_ssd++;
					}
					else
					{
						printf("No free storage space in SCM ?\n");
					}
				}
			}//ssd
		}//for
	}//if
	else if(device==HDD)
	{
		for(i=pool->chunk_min;i<=pool->chunk_max;i++)
		{
			if(pool->chunk[i].location==HDD)
			{
				if(pool->chunk[i].location_next==HDD)
				{
					pool->migrate_hdd_hdd++;
				}
				else if(pool->chunk[i].location_next==SCM)
				{
					if(find_free(pool,SCM)==SUCCESS)
					{
						pool->migrate_hdd_scm++;
						pool->chunk[i].location=SCM;
						pool->free_chk_scm--;
						pool->free_chk_hdd++;
					}
					else
					{
						printf("No free storage space in SCM ?\n");
					}
				}
				else if(pool->chunk[i].location_next==SCM)
				{
					if(find_free(pool,SCM)==SUCCESS)
					{
						pool->migrate_hdd_ssd++;
						pool->chunk[i].location=SSD;
						pool->free_chk_ssd--;
						pool->free_chk_hdd++;
					}
					else
					{
						printf("No free storage space in SSD ?\n");
					}
				}
			}//if
		}//for
	}
	else
	{
		printf("Wrong Device! \n");
	}
}//end