Example #1
0
void *malloc(unsigned int size)
{
  // try small allocation first
  for (int i = 0; i < NUM_BLOCKSIZES; i++) {
    if (size <= smallblock[i].blocksize) {
      struct smallblock_info *elt, *head = &smallblock[i];
      int pieces_per_page = PAGE_SIZE / head->blocksize;

      // for each existing page of this blocksize
      for (elt = head->next; elt != head; elt = elt->next) {

	// for each of the blocks on this page (note: block 0 is reserved)
	for (int j = 1; j < pieces_per_page; j++) {

	  // if the block is free
	  if (bitmap_get(elt->bitmap, j) == 0) {

	    // then use that block
	    bitmap_set(elt->bitmap, j, 1);
	    void *pointer = (void *)elt + j * elt->blocksize;
	    return pointer;

	  }
	}
      }

      // there were no existing pages with free blocks
      void *p = alloc_pages(1);
      // first part of page is for accounting
      elt = p;
      elt->magic = 0xfeedface;
      elt->blocksize = head->blocksize;
      memset(elt->bitmap, 0, 16);
      // add to existing list
      elt->next = head;
      elt->prev = head->prev;
      elt->next->prev = elt;
      elt->prev->next = elt;
      // remainder of block is the actual data
      bitmap_set(elt->bitmap, 1, 1);
      void *pointer = p + 1 * elt->blocksize;
      return pointer;
    }
  }

  // resort to large allocation if it wasn't small
  size += sizeof(struct bigblock_info); // accounting overhead
  int n = (size + PAGE_SIZE - 1) / PAGE_SIZE;
  void *p = alloc_pages(n);
  // first part of page is for accounting
  struct bigblock_info *elt = p;
  elt->magic = 0xf00dface;
  elt->pagecount = n;
  // remainder of page is the actual data
  void *pointer = (p + sizeof(struct bigblock_info));
  return pointer;
}
Example #2
0
/* Establish the file system and write it to disk */
int
fs_format(mem_sblock_t sbp)
{
    blocknum_t inode_bitmap_size;
    blocknum_t block_bitmap_size;
    blocknum_t i;
    sbp->filesys_lock = semaphore_new(1);
    if (NULL == sbp->filesys_lock) {
        return -1;
    }

    fs_lock(sbp);

    /* Format super block */
    sblock_get(maindisk, sbp);
    sblock_format(sbp, disk_size);
    sblock_update(sbp);

    /* Format inode and block bitmaps */
    inode_bitmap_size = sbp->inode_bitmap_last - sbp->inode_bitmap_first + 1;
    sbp->inode_bitmap = malloc(inode_bitmap_size * DISK_BLOCK_SIZE);
    block_bitmap_size = sbp->block_bitmap_last - sbp->block_bitmap_first + 1;
    sbp->block_bitmap = malloc(block_bitmap_size * DISK_BLOCK_SIZE);
    if (NULL == sbp->block_bitmap || NULL == sbp->inode_bitmap) {
        semaphore_V(sbp->filesys_lock);
        return -1;
    }
    /* Clear bitmaps */
    bitmap_zeroall(sbp->inode_bitmap, inode_bitmap_size * BITS_PER_BLOCK);
    bitmap_zeroall(sbp->block_bitmap, block_bitmap_size * BITS_PER_BLOCK);
    /* Set file system blocks to be occupied */
    for (i = 0; i <= sbp->block_bitmap_last; ++i) {
        bitmap_set(sbp->block_bitmap, i);
    }
    /* Set inode 0 to be occupied */
    bitmap_set(sbp->inode_bitmap, 0);
    /* Push updates to disk */
    for (i = sbp->inode_bitmap_first; i <= sbp->inode_bitmap_last; ++i) {
        bpush(i, (char*) sbp->inode_bitmap + (i - sbp->inode_bitmap_first)
              * DISK_BLOCK_SIZE);
    }
    for (i = sbp->block_bitmap_first; i <= sbp->block_bitmap_last; ++i) {
        bpush(i, (char*) sbp->block_bitmap + (i - sbp->block_bitmap_first)
              * DISK_BLOCK_SIZE);
    }

    /* Count free inodes and free blocks */
    mainsb->free_inodes = bitmap_count_zero(mainsb->inode_bitmap,
                                            mainsb->total_inodes);
    mainsb->free_blocks = bitmap_count_zero(mainsb->block_bitmap,
                                            mainsb->disk_num_blocks);

    fs_unlock(sbp);
    return 0;
}
Example #3
0
/* 回收inode的数据块和inode本身 */
void inode_release(struct partition* part, uint32_t inode_no) {
   struct inode* inode_to_del = inode_open(part, inode_no);
   ASSERT(inode_to_del->i_no == inode_no);

/* 1 回收inode占用的所有块 */
   uint8_t block_idx = 0, block_cnt = 12;
   uint32_t block_bitmap_idx;
   uint32_t all_blocks[140] = {0};	  //12个直接块+128个间接块

   /* a 先将前12个直接块存入all_blocks */
   while (block_idx < 12) {
      all_blocks[block_idx] = inode_to_del->i_sectors[block_idx];
      block_idx++;
   }

   /* b 如果一级间接块表存在,将其128个间接块读到all_blocks[12~], 并释放一级间接块表所占的扇区 */
   if (inode_to_del->i_sectors[12] != 0) {
      ide_read(part->my_disk, inode_to_del->i_sectors[12], all_blocks + 12, 1);
      block_cnt = 140;

      /* 回收一级间接块表占用的扇区 */
      block_bitmap_idx = inode_to_del->i_sectors[12] - part->sb->data_start_lba;
      ASSERT(block_bitmap_idx > 0);
      bitmap_set(&part->block_bitmap, block_bitmap_idx, 0);
      bitmap_sync(cur_part, block_bitmap_idx, BLOCK_BITMAP);
   }
   
   /* c inode所有的块地址已经收集到all_blocks中,下面逐个回收 */
   block_idx = 0;
   while (block_idx < block_cnt) {
      if (all_blocks[block_idx] != 0) {
	 block_bitmap_idx = 0;
	 block_bitmap_idx = all_blocks[block_idx] - part->sb->data_start_lba;
	 ASSERT(block_bitmap_idx > 0);
	 bitmap_set(&part->block_bitmap, block_bitmap_idx, 0);
	 bitmap_sync(cur_part, block_bitmap_idx, BLOCK_BITMAP);
      }
      block_idx++; 
   }

/*2 回收该inode所占用的inode */
   bitmap_set(&part->inode_bitmap, inode_no, 0);  
   bitmap_sync(cur_part, inode_no, INODE_BITMAP);

   /******     以下inode_delete是调试用的    ******
   * 此函数会在inode_table中将此inode清0,
   * 但实际上是不需要的,inode分配是由inode位图控制的,
   * 硬盘上的数据不需要清0,可以直接覆盖*/
   void* io_buf = sys_malloc(1024);
   inode_delete(part, inode_no, io_buf);
   sys_free(io_buf);
   /***********************************************/
    
   inode_close(inode_to_del);
}
Example #4
0
/* For each queue, from the most- to least-constrained:
 * find an LSB that can be assigned to the queue. If there are N queues that
 * can only use M LSBs, where N > M, fail; otherwise, every queue will get a
 * dedicated LSB. Remaining LSB regions become a shared resource.
 * If we have fewer LSBs than queues, all LSB regions become shared resources.
 */
static int ccp_assign_lsbs(struct ccp_device *ccp)
{
	DECLARE_BITMAP(lsb_pub, MAX_LSB_CNT);
	DECLARE_BITMAP(qlsb, MAX_LSB_CNT);
	int n_lsbs = 0;
	int bitno;
	int i, lsb_cnt;
	int rc = 0;

	bitmap_zero(lsb_pub, MAX_LSB_CNT);

	/* Create an aggregate bitmap to get a total count of available LSBs */
	for (i = 0; i < ccp->cmd_q_count; i++)
		bitmap_or(lsb_pub,
			  lsb_pub, ccp->cmd_q[i].lsbmask,
			  MAX_LSB_CNT);

	n_lsbs = bitmap_weight(lsb_pub, MAX_LSB_CNT);

	if (n_lsbs >= ccp->cmd_q_count) {
		/* We have enough LSBS to give every queue a private LSB.
		 * Brute force search to start with the queues that are more
		 * constrained in LSB choice. When an LSB is privately
		 * assigned, it is removed from the public mask.
		 * This is an ugly N squared algorithm with some optimization.
		 */
		for (lsb_cnt = 1;
		     n_lsbs && (lsb_cnt <= MAX_LSB_CNT);
		     lsb_cnt++) {
			rc = ccp_find_and_assign_lsb_to_q(ccp, lsb_cnt, n_lsbs,
							  lsb_pub);
			if (rc < 0)
				return -EINVAL;
			n_lsbs = rc;
		}
	}

	rc = 0;
	/* What's left of the LSBs, according to the public mask, now become
	 * shared. Any zero bits in the lsb_pub mask represent an LSB region
	 * that can't be used as a shared resource, so mark the LSB slots for
	 * them as "in use".
	 */
	bitmap_copy(qlsb, lsb_pub, MAX_LSB_CNT);

	bitno = find_first_zero_bit(qlsb, MAX_LSB_CNT);
	while (bitno < MAX_LSB_CNT) {
		bitmap_set(ccp->lsbmap, bitno * LSB_SIZE, LSB_SIZE);
		bitmap_set(qlsb, bitno, 1);
		bitno = find_first_zero_bit(qlsb, MAX_LSB_CNT);
	}

	return rc;
}
Example #5
0
uint64_t buddy_alloc(buddy_t *bd, unsigned sz) {

  /** Firstly we find the smallest power of 2 that will hold the allocation request, and take the log base 2 of it. { */
  unsigned log_sz = log2_roundup(sz);
  if (log_sz > MAX_BUDDY_SZ_LOG2)
    panic("buddy_alloc had request that was too large to handle!");

  unsigned orig_log_sz = log_sz;

  /** Then we try and find a free block of this size. This involves searching in the right bitmap for an set bit. If there are no set bits, we increase the size of the block we're searching for. { */

  /* Search for a free block - we may have to increase the size of the
     block to find a free one. */
  int64_t idx;
  while (log_sz <= MAX_BUDDY_SZ_LOG2) {
    idx = bitmap_first_set(&bd->orders[log_sz - MIN_BUDDY_SZ_LOG2]);
    if (idx != -1)
      /* Block found! */
      break;
    ++log_sz;
  }

  if (idx == -1)
    /* No free blocks :( */
    return ~0ULL;

  /** Now, if we couldn't get a block of the size we wanted, we'll have to
      split it down to the right size. { */

  /* We may have to split blocks to get back to a block of
     the minimum size. */
  for (; log_sz != orig_log_sz; --log_sz) {
    int order_idx = log_sz - MIN_BUDDY_SZ_LOG2;

    /* We're splitting a block, so deallocate it first... */
    bitmap_clear(&bd->orders[order_idx], idx);

    /* Then set both its children as free in the next order. */
    idx = INC_ORDER(idx);
    bitmap_set(&bd->orders[order_idx-1], idx);
    bitmap_set(&bd->orders[order_idx-1], idx+1);
  }

  /** By this point we have a block that is free. We should now mark it as allocated then calculate the address that actually equates to. { */

  /* Mark the block as not free. */
  int order_idx = log_sz - MIN_BUDDY_SZ_LOG2;
  bitmap_clear(&bd->orders[order_idx], idx);

  uint64_t addr = bd->start + ((uint64_t)idx << log_sz);
  return addr;  
}
Example #6
0
File: net.c Project: takayuki/al
/* =============================================================================
 * net_findAncestors
 * -- Contents of bitmapPtr set to 1 if ancestor, else 0
 * -- Returns false if id is not root node (i.e., has cycle back id)
 * =============================================================================
 */
bool_t
net_findAncestors (net_t* netPtr,
                   long id,
                   bitmap_t* ancestorBitmapPtr,
                   queue_t* workQueuePtr)
{
    bool_t status;

    vector_t* nodeVectorPtr = LocalLoad(&netPtr->nodeVectorPtr);
    assert(LocalLoad(&ancestorBitmapPtr->numBit) == vector_getSize(nodeVectorPtr));

    bitmap_clearAll(ancestorBitmapPtr);
    queue_clear(workQueuePtr);

    {
        net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, id);
        list_t* parentIdListPtr = LocalLoad(&nodePtr->parentIdListPtr);
        list_iter_t it;
        list_iter_reset(&it, parentIdListPtr);
        while (list_iter_hasNext(&it, parentIdListPtr)) {
            long parentId = (long)list_iter_next(&it, parentIdListPtr);
            status = bitmap_set(ancestorBitmapPtr, parentId);
            assert(status);
            status = queue_push(workQueuePtr, (void*)parentId);
            assert(status);
        }
    }

    while (!queue_isEmpty(workQueuePtr)) {
        long parentId = (long)queue_pop(workQueuePtr);
        if (parentId == id) {
            queue_clear(workQueuePtr);
            return FALSE;
        }
        net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, parentId);
        list_t* grandParentIdListPtr = LocalLoad(&nodePtr->parentIdListPtr);
        list_iter_t it;
        list_iter_reset(&it, grandParentIdListPtr);
        while (list_iter_hasNext(&it, grandParentIdListPtr)) {
            long grandParentId = (long)list_iter_next(&it, grandParentIdListPtr);
            if (!bitmap_isSet(ancestorBitmapPtr, grandParentId)) {
                status = bitmap_set(ancestorBitmapPtr, grandParentId);
                assert(status);
                status = queue_push(workQueuePtr, (void*)grandParentId);
                assert(status);
            }
        }
    }

    return TRUE;
}
Example #7
0
/* =============================================================================
 * net_findDescendants
 * -- Contents of bitmapPtr set to 1 if descendants, else 0
 * -- Returns false if id is not root node (i.e., has cycle back id)
 * =============================================================================
 */
bool_t
net_findDescendants (net_t* netPtr,
                     long id,
                     bitmap_t* descendantBitmapPtr,
                     queue_t* workQueuePtr)
{
    bool_t status;

    vector_t* nodeVectorPtr = netPtr->nodeVectorPtr;
    assert(descendantBitmapPtr->numBit == vector_getSize(nodeVectorPtr));

    bitmap_clearAll(descendantBitmapPtr);
    queue_clear(workQueuePtr);

    {
        net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, id);
        list_t* childIdListPtr = nodePtr->childIdListPtr;
        list_iter_t it;
        list_iter_reset(&it, childIdListPtr);
        while (list_iter_hasNext(&it, childIdListPtr)) {
            long childId = (long)list_iter_next(&it, childIdListPtr);
            status = bitmap_set(descendantBitmapPtr, childId);
            assert(status);
            status = queue_push(workQueuePtr, (void*)childId);
            assert(status);
        }
    }

    while (!queue_isEmpty(workQueuePtr)) {
        long childId = (long)queue_pop(workQueuePtr);
        if (childId == id) {
            queue_clear(workQueuePtr);
            return FALSE;
        }
        net_node_t* nodePtr = (net_node_t*)vector_at(nodeVectorPtr, childId);
        list_t* grandChildIdListPtr = nodePtr->childIdListPtr;
        list_iter_t it;
        list_iter_reset(&it, grandChildIdListPtr);
        while (list_iter_hasNext(&it, grandChildIdListPtr)) {
            long grandChildId = (long)list_iter_next(&it, grandChildIdListPtr);
            if (!bitmap_isSet(descendantBitmapPtr, grandChildId)) {
                status = bitmap_set(descendantBitmapPtr, grandChildId);
                assert(status);
                status = queue_push(workQueuePtr, (void*)grandChildId);
                assert(status);
            }
        }
    }

    return TRUE;
}
Example #8
0
void wavefront_bitmap_initialize( struct bitmap *b )
{
	int i, j;

	bitmap_reset(b,WAVEFRONT_TASK_STATE_NOTREADY);

	for(i=0;i<=xsize;i++) {
		bitmap_set(b,i,0,WAVEFRONT_TASK_STATE_COMPLETE);
	}

	for(j=0;j<=ysize;j++) {
		bitmap_set(b,0,j,WAVEFRONT_TASK_STATE_COMPLETE);
	}
}
Example #9
0
File: state.c Project: dsaravel/dex
static void set_bits(unsigned char *bitmap, const unsigned char *pattern)
{
	int i;

	for (i = 0; pattern[i]; i++) {
		unsigned int ch = pattern[i];

		bitmap_set(bitmap, ch);
		if (pattern[i + 1] == '-' && pattern[i + 2]) {
			for (ch = ch + 1; ch <= pattern[i + 2]; ch++)
				bitmap_set(bitmap, ch);
			i += 2;
		}
	}
}
Example #10
0
/* Sets 'count' consecutive bits in 'bitmap', starting at bit offset 'start',
 * to 'value'. */
void
bitmap_set_multiple(unsigned long *bitmap, size_t start, size_t count,
                    bool value)
{
    for (; count && start % BITMAP_ULONG_BITS; count--) {
        bitmap_set(bitmap, start++, value);
    }
    for (; count >= BITMAP_ULONG_BITS; count -= BITMAP_ULONG_BITS) {
        *bitmap_unit__(bitmap, start) = -(unsigned long) value;
        start += BITMAP_ULONG_BITS;
    }
    for (; count; count--) {
        bitmap_set(bitmap, start++, value);
    }
}
Example #11
0
static int ep_fifo_alloc(struct mtu3_ep *mep, u32 seg_size)
{
	struct mtu3_fifo_info *fifo = mep->fifo;
	u32 num_bits = DIV_ROUND_UP(seg_size, MTU3_EP_FIFO_UNIT);
	u32 start_bit;

	/* ensure that @mep->fifo_seg_size is power of two */
	num_bits = roundup_pow_of_two(num_bits);
	if (num_bits > fifo->limit)
		return -EINVAL;

	mep->fifo_seg_size = num_bits * MTU3_EP_FIFO_UNIT;
	num_bits = num_bits * (mep->slot + 1);
	start_bit = bitmap_find_next_zero_area(fifo->bitmap,
			fifo->limit, 0, num_bits, 0);
	if (start_bit >= fifo->limit)
		return -EOVERFLOW;

	bitmap_set(fifo->bitmap, start_bit, num_bits);
	mep->fifo_size = num_bits * MTU3_EP_FIFO_UNIT;
	mep->fifo_addr = fifo->base + MTU3_EP_FIFO_UNIT * start_bit;

	dev_dbg(mep->mtu->dev, "%s fifo:%#x/%#x, start_bit: %d\n",
		__func__, mep->fifo_seg_size, mep->fifo_size, start_bit);

	return mep->fifo_addr;
}
Example #12
0
File: main.c Project: pacepi/bitmap
int check(bitmap_t bmp, int x)
{
    int fail = 0;
    int i = 0;

    for (i = 0; i < SIZE; i++) {
        if (i % x)
            bitmap_set(bmp, i);
        else
            bitmap_unset(bmp, i);
    }

    for (i = 0; i < SIZE; i++) {
        if (i % x) {
            if (bitmap_get(bmp, i) != 1)
                fail++;
        }
        else {
            if (bitmap_get(bmp, i) != 0)
                fail++;
        }
    }

    printf("%s : x = %d, fail = %d\n", __FUNCTION__, x, fail);
    return fail;
}
Example #13
0
File: mem.c Project: WWVincent/pa4
void *alloc_pages(unsigned int count)
{
  if (count == 0 || count > ram_pages - pages_reserved) {
    printf("alloc_pages: sorry, can't allocate %d pages (only %d RAM pages available)\n",
	count, ram_pages - pages_reserved);
    shutdown();
  }
  // look for count free pages in a row
  int seen = 0;
  for (int i = 0; i < ram_pages - pages_reserved; i++) {
    int end = (page_alloc_hint + i) % (ram_pages - pages_reserved);
    if (end == 0)
      seen = 0; // just wrapped around to the start of the bitmap
    if (bitmap_get(page_alloc_bitmap, end) == 0)
      seen++;
    if (seen == count) {
      int start = end - count + 1;
      // start through end (inclusive) are all free
      for (i = start; i <= end; i++)
	bitmap_set(page_alloc_bitmap, i, 1);
      page_alloc_hint = (end + 1) % (ram_pages - pages_reserved);
      return physical_to_virtual((ram_start_page + pages_reserved + start) << 12);
    }
  }
  printf("alloc_pages: no free pages left, sorry\n");
  shutdown();
}
Example #14
0
/*
 * reserve a port number.  if "0" specified, we will try to pick one
 * starting at roce_next_port.  roce_next_port will take on the values
 * 1..4096
 */
u16 usnic_transport_rsrv_port(enum usnic_transport_type type, u16 port_num)
{
	if (type == USNIC_TRANSPORT_ROCE_CUSTOM) {
		spin_lock(&roce_bitmap_lock);
		if (!port_num) {
			port_num = bitmap_find_next_zero_area(roce_bitmap,
						ROCE_BITMAP_SZ,
						roce_next_port /* start */,
						1 /* nr */,
						0 /* align */);
			roce_next_port = (port_num & 4095) + 1;
		} else if (test_bit(port_num, roce_bitmap)) {
			usnic_err("Failed to allocate port for %s\n",
					usnic_transport_to_str(type));
			spin_unlock(&roce_bitmap_lock);
			goto out_fail;
		}
		bitmap_set(roce_bitmap, port_num, 1);
		spin_unlock(&roce_bitmap_lock);
	} else {
		usnic_err("Failed to allocate port - transport %s unsupported\n",
				usnic_transport_to_str(type));
		goto out_fail;
	}

	usnic_dbg("Allocating port %hu for %s\n", port_num,
			usnic_transport_to_str(type));
	return port_num;

out_fail:
	return 0;
}
Example #15
0
static void show_object(struct object *object, const struct name_path *path,
                        const char *last, void *data)
{
    struct bitmap *base = data;
    bitmap_set(base, find_object_pos(object->sha1));
    mark_as_seen(object);
}
Example #16
0
void recv_msg_get_mac(void *msg_hdr, struct arp_cache *arp_cache,
                      struct thread_context *contexts, cqueue_spsc *q) {
  struct msg_arpd_get_mac *msg;
  struct arp_cache_entry *e;
  uint32_t idx;
  int rv;

  assert(msg_hdr);
  assert(arp_cache);
  assert(contexts);
  assert(q);

  msg = msg_hdr;
  idx = ntohl(msg->ip.s_addr - arp_cache->baseline);
  e = &arp_cache->values[idx];

  if (e->timestamp.tv_sec != 0) {
    send_msg_get_mac_reply(&contexts[msg->thread_id], &msg->ip, &e->mac);
  } else { // uninitialized, so send a request
    // send_pkt_arp_request might fail, but it will get resent when
    // the arp cache is updated
    send_pkt_arp_request(q, &msg->ip);
    bitmap_set(e->waiters, msg->thread_id);
    rv = gettimeofday(&e->timestamp, NULL);
    assert(rv == 0);
    e->timestamp.tv_usec+= ARP_CACHE_RETRY_INTERVAL;
    if (e->timestamp.tv_usec > 999999) {
      e->timestamp.tv_sec++;
      e->timestamp.tv_usec-=1000000;
    }
    return;
  }
}
Example #17
0
static u32 ccp_alloc_ksb(struct ccp_cmd_queue *cmd_q, unsigned int count)
{
	int start;
	struct ccp_device *ccp = cmd_q->ccp;

	for (;;) {
		mutex_lock(&ccp->sb_mutex);

		start = (u32)bitmap_find_next_zero_area(ccp->sb,
							ccp->sb_count,
							ccp->sb_start,
							count, 0);
		if (start <= ccp->sb_count) {
			bitmap_set(ccp->sb, start, count);

			mutex_unlock(&ccp->sb_mutex);
			break;
		}

		ccp->sb_avail = 0;

		mutex_unlock(&ccp->sb_mutex);

		/* Wait for KSB entries to become available */
		if (wait_event_interruptible(ccp->sb_queue, ccp->sb_avail))
			return 0;
	}

	return KSB_START + start;
}
Example #18
0
//adds a page to swap space, gets called with the physical memory position
size_t add_swap (void * addr) {
	//init swap if necessary
	if (swap == NULL)   //init the swap table
  		init_swap ();

	//lock the swap table
	lock_acquire(&swap_lock);

	//find a free entry in the bitmap table
	size_t free = bitmap_scan (swap_table, 0, 1, false);
	//if the swap table is full panic the kernel
	if (free == BITMAP_ERROR) PANIC ("Swaptable is full\n");

	int i;
	//get frame and the memory position and write it to swap
	for (i = 0; i< SECPP; i++)
		//write block to swap, free * SECPP is the correct block position and + i because a page has a different size, same for addr
		block_write (swap, free * SECPP + i, addr + BLOCK_SECTOR_SIZE * i);

	//set the corresponding entry in the swap_table to true
	bitmap_set (swap_table, free, true);

	//release the lock for the swap table
	lock_release(&swap_lock);

	return free;

}
Example #19
0
/* Set a block to used */
void
bset(blocknum_t blocknum)
{
    blocknum_t bit = -1;
    blocknum_t block_offset;

    fs_lock(mainsb);
    if (blocknum <= mainsb->block_bitmap_last || blocknum >=mainsb->disk_num_blocks) {
        fs_unlock(mainsb);
        return;
    }

    /* Set the block to free */
    bit = blocknum;
    block_offset = bit / BITS_PER_BLOCK;

    if (bitmap_get(mainsb->block_bitmap, bit) == 0) {
        bitmap_set(mainsb->block_bitmap, bit);
        bpush(block_offset + mainsb->block_bitmap_first,
            (char*) mainsb->block_bitmap + block_offset * DISK_BLOCK_SIZE);
        mainsb->free_blocks--;
    }

    fs_unlock(mainsb);
}
Example #20
0
block_store_t *block_store_create() {
    // While assembly-wise it shouldn't change, it looks cleaner,
    //   even if we have extra free/destruct calls on the error path
    //   (but then again, who cares about the length of the error path?)

    // This will probably have to be encapsulated eventually, like bitmap's creations
    // (also because import is a MEEEESSSSSSSSS)
    // (Actually, with bitmap_overlay now, we may just be able to call create whenever)
    // (Although file-backed stuff will throw a wrench in it, but it's VERY different (just an fd?))
    // (file-backing is a headache for some other day)

    block_store_t *bs = calloc(sizeof(block_store_t), 1);
    if (bs) {
        if ((bs->data_blocks = calloc(BLOCK_SIZE, BLOCK_COUNT)) &&
                // Eh, calloc, why not (technically a security risk if we don't)
                (bs->fbm = bitmap_overlay(BLOCK_COUNT, bs->data_blocks)) &&
                (bs->dbm = bitmap_create(BLOCK_COUNT))) {
            for (size_t idx = 0; idx < FBM_BLOCK_COUNT; ++idx) {
                bitmap_set(bs->fbm, idx);
            }
            bitmap_format(bs->dbm, 0xFF);
            // we have never synced, mark all as changed
            bs->flags = DIRTY;
            bs->fd = -1;
            bs_errno = BS_OK;
            return bs;
        }
        free(bs->data_blocks);
        bitmap_destroy(bs->dbm);
        bitmap_destroy(bs->fbm);
        free(bs);
    }
    bs_errno = BS_MEMORY;
    return NULL;
}
static void check_output(struct gpio_kp *kp, int out, int polarity)
{
	struct gpio_keypad_info *kpinfo = kp->keypad_info;
	int key_index;
	int in;
	int gpio;
	int changed = 0;

	key_index = out * kpinfo->ninputs;
	for (in = 0; in < kpinfo->ninputs; in++, key_index++) {
		gpio = kpinfo->input_gpios[in];
		changed = 0;
		if (gpio_get(gpio) ^ !polarity) {
			if (kp->some_keys_pressed < 3)
				kp->some_keys_pressed++;
			changed = !bitmap_set(kp->keys_pressed, key_index);
		} else {
			changed = bitmap_clear(kp->keys_pressed, key_index);
		}
		if (changed) {
			int state = bitmap_test(kp->keys_pressed, key_index);
			keys_post_event(kpinfo->keymap[key_index], state);
		}
	}

	/* sets up the right state for the next poll cycle */
	gpio = kpinfo->output_gpios[out];
	if (kpinfo->flags & GPIOKPF_DRIVE_INACTIVE)
		gpio_set(gpio, !polarity);
	else
		gpio_config(gpio, GPIO_INPUT);
}
Example #22
0
File: block.c Project: ejrh/ejrh
static void bitmap_set(FS *fs, LOCATION location, int allocated)
{
    unsigned long int bitmap_num = location / fs->bitmap_size;
    unsigned long int bitmap_offset = location % fs->bitmap_size;
    unsigned long int bitmap_byte = bitmap_offset / 8;
    unsigned long int bitmap_bit = bitmap_offset % 8;
    BLOCK *bitmap;
    unsigned char *byte;
    int prev;

    if (fs->bitmaps[bitmap_num] == 0)
    {
        bitmap = allocate_block(fs, B_BITMAP, 0);
        fs->bitmaps[bitmap_num] = bitmap->location;
        bitmap_set(fs, bitmap->location, 1);
        set_flag(fs->superblock, F_DIRTY);
    }
    else
        bitmap = get_block(fs, fs->bitmaps[bitmap_num], 1);
    
    byte = (unsigned char *) bitmap->buffer + sizeof(struct bitmap_block_header) + bitmap_byte;
    prev = (*byte & (1 << bitmap_bit)) != 0;
    if (allocated)
        *byte = *byte | (1 << bitmap_bit);
    else
        *byte = *byte & ~(1 << bitmap_bit);
    set_flag(bitmap, F_DIRTY);
    
    if (prev == allocated)
        error("Not toggling bit!\n");
    
    //printf("Set bit %ld to %d from %d\n", location, allocated, prev);
}
Example #23
0
void wavefront_task_initialize( struct bitmap *b, struct list * list )
{
	int i, j;

	bitmap_reset(b,WAVEFRONT_TASK_STATE_NOTREADY);

	for(i=0;i<=xsize;i++) {
		bitmap_set(b,i,0,WAVEFRONT_TASK_STATE_COMPLETE);
	}

	for(j=0;j<=ysize;j++) {
		bitmap_set(b,0,j,WAVEFRONT_TASK_STATE_COMPLETE);
	}

	list_push_head(list,wavefront_task_create(xstart,ystart,block_size,block_size));
}
Example #24
0
static void mirror_iteration_done(MirrorOp *op, int ret)
{
    MirrorBlockJob *s = op->s;
    struct iovec *iov;
    int64_t chunk_num;
    int i, nb_chunks, sectors_per_chunk;

    trace_mirror_iteration_done(s, op->sector_num, op->nb_sectors, ret);

    s->in_flight--;
    iov = op->qiov.iov;
    for (i = 0; i < op->qiov.niov; i++) {
        MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
        QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
        s->buf_free_count++;
    }

    sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
    chunk_num = op->sector_num / sectors_per_chunk;
    nb_chunks = op->nb_sectors / sectors_per_chunk;
    bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
    if (s->cow_bitmap && ret >= 0) {
        bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
    }

    g_slice_free(MirrorOp, op);
    qemu_coroutine_enter(s->common.co, NULL);
}
Example #25
0
static struct cpdma_desc __iomem *
cpdma_desc_alloc(struct cpdma_desc_pool *pool, int num_desc, bool is_rx)
{
	unsigned long flags;
	int index;
	int desc_start;
	int desc_end;
	struct cpdma_desc __iomem *desc = NULL;

	spin_lock_irqsave(&pool->lock, flags);

	if (is_rx) {
		desc_start = 0;
		desc_end = pool->num_desc/2;
	 } else {
		desc_start = pool->num_desc/2;
		desc_end = pool->num_desc;
	}

	index = bitmap_find_next_zero_area(pool->bitmap,
				desc_end, desc_start, num_desc, 0);
	if (index < desc_end) {
		bitmap_set(pool->bitmap, index, num_desc);
		desc = pool->iomap + pool->desc_size * index;
		pool->used_desc++;
	}

	spin_unlock_irqrestore(&pool->lock, flags);
	return desc;
}
Example #26
0
static inline void release_ptd_buffers(struct isp1362_ep_queue *epq, struct isp1362_ep *ep)
{
	int last = ep->ptd_index + ep->num_ptds;

	if (last > epq->buf_count)
		pr_err("%s: ep %p req %d len %d %s PTD[%d] $%04x num_ptds %d buf_count %d buf_avail %d buf_map %08lx skip_map %08lx\n",
		    __func__, ep, ep->num_req, ep->length, epq->name, ep->ptd_index,
		    ep->ptd_offset, ep->num_ptds, epq->buf_count, epq->buf_avail,
		    epq->buf_map, epq->skip_map);
	BUG_ON(last > epq->buf_count);

	bitmap_clear(&epq->buf_map, ep->ptd_index, ep->num_ptds);
	bitmap_set(&epq->skip_map, ep->ptd_index, ep->num_ptds);
	epq->buf_avail += ep->num_ptds;
	epq->ptd_count--;

	BUG_ON(epq->buf_avail > epq->buf_count);
	BUG_ON(epq->ptd_count > epq->buf_count);

	DBG(1, "%s: Done %s PTDs $%04x released %d avail %d count %d\n",
	    __func__, epq->name,
	    ep->ptd_offset, ep->num_ptds, epq->buf_avail, epq->buf_count);
	DBG(1, "%s: buf_map %08lx skip_map %08lx\n", __func__,
	    epq->buf_map, epq->skip_map);

	ep->num_ptds = 0;
	ep->ptd_offset = -EINVAL;
	ep->ptd_index = -EINVAL;
}
Example #27
0
/* Get a free block number from the disk and mark the block used */
blocknum_t
balloc(disk_t* disk)
{
    blocknum_t free_bit = -1;
    blocknum_t block_offset = -1;

    /* Get super block */
    fs_lock(mainsb);
    if (mainsb->free_blocks <= 0) {
        fs_unlock(mainsb);
        return -1;
    }

    /* Get free block number */
    free_bit = bitmap_next_zero(mainsb->block_bitmap, mainsb->disk_num_blocks);
    block_offset = free_bit / BITS_PER_BLOCK;
    if (block_offset < 0 || block_offset >= mainsb->disk_num_blocks) {
        fs_unlock(mainsb);
        return -1;
    }

    /* Set the free block to used */
    bitmap_set(mainsb->block_bitmap, free_bit);
    bpush(block_offset + mainsb->block_bitmap_first,
          (char*) mainsb->block_bitmap + block_offset * DISK_BLOCK_SIZE);

    mainsb->free_blocks--;
    fs_unlock(mainsb);

    return free_bit;
}
Example #28
0
/**
 * irq_alloc_descs - allocate and initialize a range of irq descriptors
 * @irq:	Allocate for specific irq number if irq >= 0
 * @from:	Start the search from this irq number
 * @cnt:	Number of consecutive irqs to allocate.
 * @node:	Preferred node on which the irq descriptor should be allocated
 *
 * Returns the first irq number or error code
 */
int __ref
irq_alloc_descs(int irq, unsigned int from, unsigned int cnt, int node)
{
	int start, ret;

	if (!cnt)
		return -EINVAL;

	mutex_lock(&sparse_irq_lock);

	start = bitmap_find_next_zero_area(allocated_irqs, nr_irqs, from, cnt, 0);
	ret = -EEXIST;
	if (irq >=0 && start != irq)
		goto err;

	ret = -ENOMEM;
	if (start >= nr_irqs)
		goto err;

	bitmap_set(allocated_irqs, start, cnt);
	mutex_unlock(&sparse_irq_lock);
	return alloc_descs(start, cnt, node);

err:
	mutex_unlock(&sparse_irq_lock);
	return ret;
}
Example #29
0
/*
 * Allocate a free inode and return a pointer to free inode
 * Return NULL if fail.
 */
inodenum_t
ialloc(disk_t* disk)
{
    inodenum_t free_bit = -1;
    inodenum_t block_offset = -1;

    fs_lock(mainsb);
    if (mainsb->free_inodes <= 0) {
        fs_unlock(mainsb);
        return -1;
    }

    /* Get free inode number */
    free_bit = bitmap_next_zero(mainsb->inode_bitmap, mainsb->disk_num_blocks);
    block_offset = free_bit / BITS_PER_BLOCK;
    if (free_bit < 0 || block_offset >= mainsb->disk_num_blocks) {
        fs_unlock(mainsb);
        return -1;
    }

    /* Set the free inode to used */
    bitmap_set(mainsb->inode_bitmap, free_bit);
    bpush(block_offset + mainsb->inode_bitmap_first,
          (char*) mainsb->inode_bitmap + block_offset * DISK_BLOCK_SIZE);

    mainsb->free_inodes--;
    fs_unlock(mainsb);

    return free_bit;
}
Example #30
0
File: conn.c Project: jophxy/samba
/****************************************************************************
  find first available connection slot, starting from a random position.
The randomisation stops problems with the server dieing and clients
thinking the server is still available.
****************************************************************************/
connection_struct *conn_new(void)
{
	connection_struct *conn;
	int i;

	i = bitmap_find(bmap, 1);
	
	if (i == -1) {
		DEBUG(1,("ERROR! Out of connection structures\n"));	       
		return NULL;
	}

	conn = (connection_struct *)malloc(sizeof(*conn));
	if (!conn) return NULL;

	ZERO_STRUCTP(conn);
	conn->cnum = i;

	bitmap_set(bmap, i);

	num_open++;

	string_set(&conn->user,"");
	string_set(&conn->dirpath,"");
	string_set(&conn->connectpath,"");
	string_set(&conn->origpath,"");
	
	DLIST_ADD(Connections, conn);

	return conn;
}