Ejemplo n.º 1
0
int
do_test (void)
{
  int result = 0;

  for (uint64_t i = 0; i < (~UINT64_C (0)) >> 2; i = (i << 1) + 3)
    {
      if (i < UINT64_C (65536))
	{
	  DIAG_PUSH_NEEDS_COMMENT;
	  DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
	  if (htobe16 (be16toh (i)) != i)
	    {
	      printf ("htobe16 (be16toh (%" PRIx64 ")) == %" PRIx16 "\n",
		      i, (uint16_t) htobe16 (be16toh (i)));
	      result = 1;
	    }
	  if (htole16 (le16toh (i)) != i)
	    {
	      printf ("htole16 (le16toh (%" PRIx64 ")) == %" PRIx16 "\n",
		      i, (uint16_t) htole16 (le16toh (i)));
	      result = 1;
	    }
	  DIAG_POP_NEEDS_COMMENT;

	  uint16_t n[2];
	  n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_16 (i);
	  n[__BYTE_ORDER == __BIG_ENDIAN] = i;
	  if (htole16 (i) != n[0])
	    {
	      printf ("htole16 (%" PRIx64 ") == %" PRIx16 " != %" PRIx16 "\n",
		      i, (uint16_t) htole16 (i), n[0]);
	      result = 1;
	    }
	  if (htobe16 (i) != n[1])
	    {
	      printf ("htobe16 (%" PRIx64 ") == %" PRIx16 " != %" PRIx16 "\n",
		      i, (uint16_t) htobe16 (i), n[1]);
	      result = 1;
	    }
	}

      if (i < UINT64_C (4294967296))
	{
	  DIAG_PUSH_NEEDS_COMMENT;
	  DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
	  if (htobe32 (be32toh (i)) != i)
	    {
	      printf ("htobe32 (be32toh (%" PRIx64 ")) == %" PRIx32 "\n",
		      i, (uint32_t) htobe32 (be32toh (i)));
	      result = 1;
	    }
	  if (htole32 (le32toh (i)) != i)
	    {
	      printf ("htole32 (le32toh (%" PRIx64 ")) == %" PRIx32 "\n",
		      i, (uint32_t) htole32 (le32toh (i)));
	      result = 1;
	    }
	  DIAG_POP_NEEDS_COMMENT;

	  uint32_t n[2];
	  n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_32 (i);
	  n[__BYTE_ORDER == __BIG_ENDIAN] = i;
	  if (htole32 (i) != n[0])
	    {
	      printf ("htole32 (%" PRIx64 ") == %" PRIx32 " != %" PRIx32 "\n",
		      i, (uint32_t) htole32 (i), n[0]);
	      result = 1;
	    }
	  if (htobe32 (i) != n[1])
	    {
	      printf ("htobe32 (%" PRIx64 ") == %" PRIx32 " != %" PRIx32 "\n",
		      i, (uint32_t) htobe32 (i), n[1]);
	      result = 1;
	    }
	}

      DIAG_PUSH_NEEDS_COMMENT;
      DIAG_IGNORE_NEEDS_COMMENT_TAUTOLOGICAL_COMPARE ();
      if (htobe64 (be64toh (i)) != i)
	{
	  printf ("htobe64 (be64toh (%" PRIx64 ")) == %" PRIx64 "\n",
		  i, htobe64 (be64toh (i)));
	  result = 1;
	}
      if (htole64 (le64toh (i)) != i)
	{
	  printf ("htole64 (le64toh (%" PRIx64 ")) == %" PRIx64 "\n",
		  i, htole64 (le64toh (i)));
	  result = 1;
	}
      DIAG_POP_NEEDS_COMMENT;

      uint64_t n[2];
      n[__BYTE_ORDER == __LITTLE_ENDIAN] = bswap_64 (i);
      n[__BYTE_ORDER == __BIG_ENDIAN] = i;
      if (htole64 (i) != n[0])
	{
	  printf ("htole64 (%" PRIx64 ") == %" PRIx64 " != %" PRIx64 "\n",
		  i, htole64 (i), n[0]);
	  result = 1;
	}
      if (htobe64 (i) != n[1])
	{
	  printf ("htobe64 (%" PRIx64 ") == %" PRIx64 " != %" PRIx64 "\n",
		  i, htobe64 (i), n[1]);
	  result = 1;
	}
    }

  return result;
}
Ejemplo n.º 2
0
static int
_aarch64_minidump_initvtop(kvm_t *kd)
{
	struct vmstate *vmst;
	off_t off, sparse_off;

	vmst = _kvm_malloc(kd, sizeof(*vmst));
	if (vmst == NULL) {
		_kvm_err(kd, kd->program, "cannot allocate vm");
		return (-1);
	}
	kd->vmst = vmst;
	if (pread(kd->pmfd, &vmst->hdr, sizeof(vmst->hdr), 0) !=
	    sizeof(vmst->hdr)) {
		_kvm_err(kd, kd->program, "cannot read dump header");
		return (-1);
	}
	if (strncmp(MINIDUMP_MAGIC, vmst->hdr.magic,
	    sizeof(vmst->hdr.magic)) != 0) {
		_kvm_err(kd, kd->program, "not a minidump for this platform");
		return (-1);
	}

	vmst->hdr.version = le32toh(vmst->hdr.version);
	if (vmst->hdr.version != MINIDUMP_VERSION) {
		_kvm_err(kd, kd->program, "wrong minidump version. "
		    "Expected %d got %d", MINIDUMP_VERSION, vmst->hdr.version);
		return (-1);
	}
	vmst->hdr.msgbufsize = le32toh(vmst->hdr.msgbufsize);
	vmst->hdr.bitmapsize = le32toh(vmst->hdr.bitmapsize);
	vmst->hdr.pmapsize = le32toh(vmst->hdr.pmapsize);
	vmst->hdr.kernbase = le64toh(vmst->hdr.kernbase);
	vmst->hdr.dmapphys = le64toh(vmst->hdr.dmapphys);
	vmst->hdr.dmapbase = le64toh(vmst->hdr.dmapbase);
	vmst->hdr.dmapend = le64toh(vmst->hdr.dmapend);

	/* Skip header and msgbuf */
	off = AARCH64_PAGE_SIZE + aarch64_round_page(vmst->hdr.msgbufsize);

	/* build physical address lookup table for sparse pages */
	sparse_off = off + aarch64_round_page(vmst->hdr.bitmapsize) +
	    aarch64_round_page(vmst->hdr.pmapsize);
	if (_kvm_pt_init(kd, vmst->hdr.bitmapsize, off, sparse_off,
	    AARCH64_PAGE_SIZE, sizeof(uint64_t)) == -1) {
		_kvm_err(kd, kd->program, "cannot load core bitmap");
		return (-1);
	}
	off += aarch64_round_page(vmst->hdr.bitmapsize);

	vmst->page_map = _kvm_malloc(kd, vmst->hdr.pmapsize);
	if (vmst->page_map == NULL) {
		_kvm_err(kd, kd->program,
		    "cannot allocate %d bytes for page_map",
		    vmst->hdr.pmapsize);
		return (-1);
	}
	/* This is the end of the dump, savecore may have truncated it. */
	/*
	 * XXX: This doesn't make sense.  The pmap is not at the end,
	 * and if it is truncated we don't have any actual data (it's
	 * all stored after the bitmap and pmap.  -- jhb
	 */
	if (pread(kd->pmfd, vmst->page_map, vmst->hdr.pmapsize, off) <
	    AARCH64_PAGE_SIZE) {
		_kvm_err(kd, kd->program, "cannot read %d bytes for page_map",
		    vmst->hdr.pmapsize);
		return (-1);
	}
	off += aarch64_round_page(vmst->hdr.pmapsize);

	return (0);
}
Ejemplo n.º 3
0
int main(int argc, char **argv)
{
	int i;
	FILE *in = stdin;
	int verbose = 1;
	int save_parts = 0;
	int part = -1;
	int opt;
	const char *dest = "%d.img";
	
	while ((opt = getopt(argc, argv, "vqso:p:?")) != -1) {
		switch(opt) {
		case 'v':
			verbose++;
			break;
		case 'q':
			if (verbose)
				verbose--;
			break;
		case 'o':
			dest = optarg;
			save_parts = 1;
			break;
		case 'p':
			save_parts = 1;
			part = atoi(optarg);
			break;
		case 's':
			save_parts = 1;
			break;
		default:
			usage(argv);
			exit(1);
			break;
		}
	}
	if (save_parts && !strchr(dest, '%')) {
		const char *t = dest;
		if (!*t)
			t = "./";
		if (t[strlen(t)-1] == '/' || !part) {
			int l = strlen(t) + strlen("/%d.img") + 1;
			char *tmp = malloc(l);
			snprintf(tmp, l, "%s/%%d.img", optarg);
			t = tmp;
		}
		dest = t;
	}
	if (argc > optind + 1) {
		usage(argv);
		exit(1);
	}
	if (optind < argc ) {
		in = fopen(argv[optind], "rb");
	}
	fseek(in, 0x1C00, SEEK_CUR);
	fread(&ptable, 1, 0x400, in);
	if (strncmp(ptable.signature, "PHOENIX_CARD_IMG", 16) != 0) {
		fprintf(stderr, "ERROR: Not a phoenix image\n");
		exit(1);
	}
	if (verbose > 1) {
		printf("????  : %08x\n", le32toh(ptable.unknown1));
		printf("Parts : %d\n", le16toh(ptable.parts));
		printf("????  : %08x\n", le16toh(ptable.unknown2));
		printf("pad   : %02x%02x%02x%02x%02x%02x%02x%02x\n", ptable.pad[0], ptable.pad[1], ptable.pad[2], ptable.pad[3], ptable.pad[4], ptable.pad[5], ptable.pad[6], ptable.pad[7]);
		printf("\n");
	}
	for (i = 0; i < le16toh(ptable.parts); i++) {
		if (verbose && (part == -1 || part == i)) {
			printf("part %d:\n", i);
			printf("\tstart: 0x%08x (%u / 0x%08x)\n", le32toh(ptable.part[i].start)*512, le32toh(ptable.part[i].start), le32toh(ptable.part[i].start));
			printf("\tsize : %u\n", le32toh(ptable.part[i].size));
			printf("\t?????: %08x\n", le32toh(ptable.part[i].unknown));
			if (verbose > 1 || le32toh(ptable.part[i].sig) != 0x00646461)
				printf("\tsig??: %08x\n", le32toh(ptable.part[i].sig));
			printf("\n");
		}
		if (save_parts && (part == -1 || part == i)) {
			save_part(&ptable, i, dest, in);
		}
	}
}
Ejemplo n.º 4
0
Archivo: pool.c Proyecto: krzycz/nvml
/*
 * pool_parse_params -- parse pool type, file size and block size
 */
static int
pool_params_parse(const PMEMpoolcheck *ppc, struct pool_params *params,
	int check)
{
	LOG(3, NULL);
	int is_btt = ppc->args.pool_type == PMEMPOOL_POOL_TYPE_BTT;

	params->type = POOL_TYPE_UNKNOWN;
	params->is_poolset = util_is_poolset_file(ppc->path) == 1;

	int fd = util_file_open(ppc->path, NULL, 0, O_RDONLY);
	if (fd < 0)
		return -1;

	int ret = 0;

	os_stat_t stat_buf;
	ret = os_fstat(fd, &stat_buf);
	if (ret)
		goto out_close;

	ASSERT(stat_buf.st_size >= 0);

	params->mode = stat_buf.st_mode;

	struct pool_set *set;
	void *addr;
	if (params->is_poolset) {
		/*
		 * Need to close the poolset because it will be opened with
		 * flock in the following instructions.
		 */
		os_close(fd);
		fd = -1;

		if (check) {
			if (pool_set_map(ppc->path, &set, 0))
				return -1;
		} else {
			ret = util_poolset_create_set(&set, ppc->path,
				0, 0, true);
			if (ret < 0) {
				LOG(2, "cannot open pool set -- '%s'",
					ppc->path);
				return -1;
			}
			if (set->remote) {
				ERR("poolsets with remote replicas are not "
					"supported");
				return -1;
			}
			if (util_pool_open_nocheck(set,
						POOL_OPEN_IGNORE_BAD_BLOCKS))
				return -1;
		}

		params->size = set->poolsize;
		addr = set->replica[0]->part[0].addr;

		/*
		 * XXX mprotect for device dax with length not aligned to its
		 * page granularity causes SIGBUS on the next page fault.
		 * The length argument of this call should be changed to
		 * set->poolsize once the kernel issue is solved.
		 */
		if (mprotect(addr, set->replica[0]->repsize,
			PROT_READ) < 0) {
			ERR("!mprotect");
			goto out_unmap;
		}
		params->is_dev_dax = set->replica[0]->part[0].is_dev_dax;
		params->is_pmem = set->replica[0]->is_pmem;
	} else if (is_btt) {
		params->size = (size_t)stat_buf.st_size;
#ifndef _WIN32
		if (params->mode & S_IFBLK)
			if (ioctl(fd, BLKGETSIZE64, &params->size)) {
				ERR("!ioctl");
				goto out_close;
			}
#endif
		addr = NULL;
	} else {
		enum file_type type = util_file_get_type(ppc->path);
		if (type < 0) {
			ret = -1;
			goto out_close;
		}

		ssize_t s = util_file_get_size(ppc->path);
		if (s < 0) {
			ret = -1;
			goto out_close;
		}
		params->size = (size_t)s;
		int map_sync;
		addr = util_map(fd, params->size, MAP_SHARED, 1, 0, &map_sync);
		if (addr == NULL) {
			ret = -1;
			goto out_close;
		}
		params->is_dev_dax = type == TYPE_DEVDAX;
		params->is_pmem = params->is_dev_dax || map_sync ||
			pmem_is_pmem(addr, params->size);
	}

	/* stop processing for BTT device */
	if (is_btt) {
		params->type = POOL_TYPE_BTT;
		params->is_part = false;
		goto out_close;
	}

	struct pool_hdr hdr;
	memcpy(&hdr, addr, sizeof(hdr));
	util_convert2h_hdr_nocheck(&hdr);
	pool_params_from_header(params, &hdr);

	if (ppc->args.pool_type != PMEMPOOL_POOL_TYPE_DETECT) {
		enum pool_type declared_type =
			pool_check_type_to_pool_type(ppc->args.pool_type);
		if ((params->type & ~declared_type) != 0) {
			ERR("declared pool type does not match");
			errno = EINVAL;
			ret = 1;
			goto out_unmap;
		}
	}

	if (params->type == POOL_TYPE_BLK) {
		struct pmemblk pbp;
		memcpy(&pbp, addr, sizeof(pbp));
		params->blk.bsize = le32toh(pbp.bsize);
	} else if (params->type == POOL_TYPE_OBJ) {
		struct pmemobjpool *pop = addr;
		memcpy(params->obj.layout, pop->layout,
			PMEMOBJ_MAX_LAYOUT);
	}

out_unmap:
	if (params->is_poolset) {
		ASSERTeq(fd, -1);
		ASSERTne(addr, NULL);
		util_poolset_close(set, DO_NOT_DELETE_PARTS);
	} else if (!is_btt) {
		ASSERTne(fd, -1);
		ASSERTne(addr, NULL);
		munmap(addr, params->size);
	}
out_close:
	if (fd != -1)
		os_close(fd);
	return ret;
}
Ejemplo n.º 5
0
int main(int argc, char *argv[])
{
	char *origin;
	char *bzImage;
	char *ramdisk;
	FILE *forigin;
	FILE *fbzImage;
	FILE *framdisk;
	uint32_t bzImageLen;
	uint32_t ramdiskLen;
	uint32_t missing;
	char buf[BUFSIZ];
	size_t size;

	if (argc != 4)
		ERROR("Usage: %s <image to unpack> <bzImage out> <ramdisk out>\n", argv[0]);

	origin = argv[1];
	bzImage = argv[2];
	ramdisk = argv[3];

	forigin = fopen(origin, "r");
	fbzImage = fopen(bzImage, "w");
	framdisk = fopen(ramdisk, "w");
	if (!forigin || !bzImage || !framdisk)
		ERROR("ERROR: failed to open origin or output images\n");

	/* Read bzImage length from the image to unpack */
	if (fseek(forigin, CMDLINE_END, SEEK_SET) == -1)
		ERROR("ERROR: failed to seek on image\n");

	if (fread(&bzImageLen, sizeof(uint32_t), 1, forigin) != 1)
		ERROR("ERROR: failed to read bzImage length\n");
	else
		bzImageLen = le32toh(bzImageLen);

	/* Read ramdisk length from the image to unpack */
	if (fseek(forigin, (CMDLINE_END+sizeof(uint32_t)), SEEK_SET) == -1)
		ERROR("ERROR: failed to seek on image\n");

	if (fread(&ramdiskLen, sizeof(uint32_t), 1, forigin) != 1)
		ERROR("ERROR: failed to read ramdisk length\n");
	else
		ramdiskLen = le32toh(ramdiskLen);

	/* Copy bzImage */
	if (fseek(forigin, sizeof(struct bootheader), SEEK_SET) == -1)
		ERROR("ERROR: failed to seek when copying bzImage\n");

	missing = bzImageLen;
	while (missing > 0) {
		size = fread(buf, 1, ((missing > BUFSIZ) ? BUFSIZ : missing), forigin);
		if (size != 0) {
			fwrite(buf, 1, size, fbzImage);
			missing -= size;
		}
	}

	/* Copy ramdisk */
	if (fseek(forigin, (sizeof(struct bootheader)+bzImageLen), SEEK_SET) == -1)
		ERROR("ERROR: failed to seek when copying ramdisk\n");

	missing = ramdiskLen;
	while (missing > 0) {
		size = fread(buf, 1, ((missing > BUFSIZ) ? BUFSIZ : missing), forigin);
		if (size != 0) {
			fwrite(buf, 1, size, framdisk);
			missing -= size;
		}
	}

	return 0;
}
Ejemplo n.º 6
0
/*
 * Handle the given receive status queue entry
 */
void
patm_rx(struct patm_softc *sc, struct idt_rsqe *rsqe)
{
    struct mbuf *m;
    void *buf;
    u_int stat, cid, w, cells, len, h;
    struct patm_vcc *vcc;
    struct atm_pseudohdr aph;
    u_char *trail;

    cid = le32toh(rsqe->cid);
    stat = le32toh(rsqe->stat);
    h = le32toh(rsqe->handle);

    cid = PATM_CID(sc, IDT_RSQE_VPI(cid), IDT_RSQE_VCI(cid));
    vcc = sc->vccs[cid];

    if (IDT_RSQE_TYPE(stat) == IDT_RSQE_IDLE) {
        /* connection has gone idle */
        if (stat & IDT_RSQE_BUF)
            patm_rcv_free(sc, patm_rcv_handle(sc, h), h);

        w = rct_read(sc, cid, 0);
        if (w != 0 && !(w & IDT_RCT_OPEN))
            rct_write(sc, cid, 0, 0);
        if (vcc != NULL && (vcc->vflags & PATM_VCC_RX_CLOSING)) {
            patm_debug(sc, VCC, "%u.%u RX closed", vcc->vcc.vpi,
                       vcc->vcc.vci);
            vcc->vflags &= ~PATM_VCC_RX_CLOSING;
            if (vcc->vcc.flags & ATMIO_FLAG_ASYNC) {
                patm_rx_vcc_closed(sc, vcc);
                if (!(vcc->vflags & PATM_VCC_OPEN))
                    patm_vcc_closed(sc, vcc);
            } else
                cv_signal(&sc->vcc_cv);
        }
        return;
    }

    buf = patm_rcv_handle(sc, h);

    if (vcc == NULL || (vcc->vflags & PATM_VCC_RX_OPEN) == 0) {
        patm_rcv_free(sc, buf, h);
        return;
    }

    cells = IDT_RSQE_CNT(stat);
    KASSERT(cells > 0, ("zero cell count"));

    if (vcc->vcc.aal == ATMIO_AAL_0) {
        /* deliver this packet as it is */
        if ((m = patm_rcv_mbuf(sc, buf, h, 1)) == NULL)
            return;

        m->m_len = cells * 48;
        m->m_pkthdr.len = m->m_len;
        m->m_pkthdr.rcvif = sc->ifp;

    } else if (vcc->vcc.aal == ATMIO_AAL_34) {
        /* XXX AAL3/4 */
        patm_rcv_free(sc, buf, h);
        return;

    } else if (vcc->vcc.aal == ATMIO_AAL_5) {
        if (stat & IDT_RSQE_CRC) {
            if_inc_counter(sc->ifp, IFCOUNTER_IERRORS, 1);
            if (vcc->chain != NULL) {
                m_freem(vcc->chain);
                vcc->chain = vcc->last = NULL;
            }
            return;
        }

        /* append to current chain */
        if (vcc->chain == NULL) {
            if ((m = patm_rcv_mbuf(sc, buf, h, 1)) == NULL)
                return;
            m->m_len = cells * 48;
            m->m_pkthdr.len = m->m_len;
            m->m_pkthdr.rcvif = sc->ifp;
            vcc->chain = vcc->last = m;
        } else {
            if ((m = patm_rcv_mbuf(sc, buf, h, 0)) == NULL)
                return;
            m->m_len = cells * 48;
            vcc->last->m_next = m;
            vcc->last = m;
            vcc->chain->m_pkthdr.len += m->m_len;
        }

        if (!(stat & IDT_RSQE_EPDU))
            return;

        trail = mtod(m, u_char *) + m->m_len - 6;
        len = (trail[0] << 8) + trail[1];

        if ((u_int)vcc->chain->m_pkthdr.len < len + 8) {
            patm_printf(sc, "%s: bad aal5 lengths %u %u\n",
                        __func__, (u_int)m->m_pkthdr.len, len);
            m_freem(vcc->chain);
            vcc->chain = vcc->last = NULL;
            return;
        }
        m->m_len -= vcc->chain->m_pkthdr.len - len;
        KASSERT(m->m_len >= 0, ("bad last mbuf"));

        m = vcc->chain;
        vcc->chain = vcc->last = NULL;
        m->m_pkthdr.len = len;
    } else
Ejemplo n.º 7
0
static option_status
getNextSignalOption(net_buffer* nbuf, size_t* off, l2cap_cfg_opt_t* hdr, l2cap_cfg_opt_val_t* val)
{
	int hint;
	size_t len = nbuf->size - (*off);

	if (len == 0)
		return OPTION_NOT_PRESENT;
	if (len < 0 || len < sizeof(*hdr))
		return HEADER_TOO_SHORT;

	gBufferModule->read(nbuf, *off, hdr, sizeof(*hdr));
	*off += sizeof(*hdr);
	len  -= sizeof(*hdr);

	hint = L2CAP_OPT_HINT(hdr->type);
	hdr->type &= L2CAP_OPT_HINT_MASK;

	switch (hdr->type) {
		case L2CAP_OPT_MTU:
			if (hdr->length != L2CAP_OPT_MTU_SIZE || len < hdr->length)
				return BAD_OPTION_LENGTH;

			gBufferModule->read(nbuf, *off, val, L2CAP_OPT_MTU_SIZE);
			val->mtu = le16toh(val->mtu);
			*off += L2CAP_OPT_MTU_SIZE;
			flowf("mtu specified\n");
		break;

		case L2CAP_OPT_FLUSH_TIMO:
			if (hdr->length != L2CAP_OPT_FLUSH_TIMO_SIZE ||
			    len < hdr->length)
				return BAD_OPTION_LENGTH;

			gBufferModule->read(nbuf, *off, val, L2CAP_OPT_FLUSH_TIMO_SIZE);
			val->flush_timo = le16toh(val->flush_timo);
			flowf("flush specified\n");
			*off += L2CAP_OPT_FLUSH_TIMO_SIZE;
		break;

		case L2CAP_OPT_QOS:
			if (hdr->length != L2CAP_OPT_QOS_SIZE || len < hdr->length)
				return BAD_OPTION_LENGTH;

			gBufferModule->read(nbuf, *off, val, L2CAP_OPT_QOS_SIZE);
			val->flow.token_rate = le32toh(val->flow.token_rate);
			val->flow.token_bucket_size =	le32toh(val->flow.token_bucket_size);
			val->flow.peak_bandwidth = le32toh(val->flow.peak_bandwidth);
			val->flow.latency = le32toh(val->flow.latency);
			val->flow.delay_variation = le32toh(val->flow.delay_variation);
			*off += L2CAP_OPT_QOS_SIZE;
			flowf("qos specified\n");
		break;

		default:
			if (hint)
				*off += hdr->length;
			else
				return OPTION_UNKNOWN;
		break;
	}

	return OPTION_PRESENT;
}
Ejemplo n.º 8
0
static inline uint32_t
load_le32(const void* p)
{
    return le32toh(*(uint32_t*)p);
}
Ejemplo n.º 9
0
static void
getparts(mbr_args_t *a, uint32_t off, uint32_t extoff)
{
	struct dkwedge_info dkw;
	struct mbr_partition *dp;
	struct mbr_sector *mbr;
	const char *ptype;
	int i, error;

	error = dkwedge_read(a->pdk, a->vp, off, a->buf, a->secsize);
	if (error) {
		aprint_error("%s: unable to read MBR @ %u/%u, "
		    "error = %d\n", a->pdk->dk_name, off, a->secsize, a->error);
		a->error = error;
		return;
	}

	mbr = a->buf;
	if (mbr->mbr_magic != htole16(MBR_MAGIC))
		return;

	dp = mbr->mbr_parts;

	for (i = 0; i < MBR_PART_COUNT; i++) {
		/* Extended partitions are handled below. */
		if (dp[i].mbrp_type == 0 ||
		    MBR_IS_EXTENDED(dp[i].mbrp_type))
		    	continue;

		if ((ptype = mbr_ptype_to_str(dp[i].mbrp_type)) == NULL) {
			/*
			 * XXX Should probably just add these...
			 * XXX maybe just have an empty ptype?
			 */
			aprint_verbose("%s: skipping partition %d, "
			    "type 0x%02x\n", a->pdk->dk_name, i,
			    dp[i].mbrp_type);
			continue;
		}
		strcpy(dkw.dkw_ptype, ptype);

		strcpy(dkw.dkw_parent, a->pdk->dk_name);
		dkw.dkw_offset = le32toh(dp[i].mbrp_start);
		dkw.dkw_size = le32toh(dp[i].mbrp_size);

		/*
		 * These get historical disk naming style
		 * wedge names.  We start at 'e', and reserve
		 * 4 slots for each MBR we parse.
		 *
		 * XXX For FAT, we should extract the FAT volume
		 * XXX name.
		 */
		snprintf(dkw.dkw_wname, sizeof(dkw.dkw_wname),
		    "%s%c", a->pdk->dk_name,
		    'e' + (a->mbr_count * MBR_PART_COUNT) + i);

		error = dkwedge_add(&dkw);
		if (error == EEXIST)
			aprint_error("%s: wedge named '%s' already "
			    "exists, manual intervention required\n",
			    a->pdk->dk_name, dkw.dkw_wname);
		else if (error)
			aprint_error("%s: error %d adding partition "
			    "%d type 0x%02x\n", a->pdk->dk_name, error,
			    (a->mbr_count * MBR_PART_COUNT) + i,
			    dp[i].mbrp_type);
	}

	/* We've parsed one MBR. */
	a->mbr_count++;

	/* Recursively scan extended partitions. */
	for (i = 0; i < MBR_PART_COUNT; i++) {
		uint32_t poff;

		if (MBR_IS_EXTENDED(dp[i].mbrp_type)) {
			poff = le32toh(dp[i].mbrp_start) + extoff;
			getparts(a, poff, extoff ? extoff : poff);
		}
	}
}
Ejemplo n.º 10
0
static uint32_t get_uint32(const unsigned char* p) {
  uint32_t i;
  memcpy(&i,p,4);
  return le32toh(i);
}
Ejemplo n.º 11
0
void* gme_get_ptr(struct gme* gme,uint32_t off) {
  off=le32toh(off);
  assert(off+sizeof(uint32_t)<=gme->size);
  return gme->u.raw+off;
}
Ejemplo n.º 12
0
static int
mpssas_add_device(struct mps_softc *sc, u16 handle, u8 linkrate){
	char devstring[80];
	struct mpssas_softc *sassc;
	struct mpssas_target *targ;
	Mpi2ConfigReply_t mpi_reply;
	Mpi2SasDevicePage0_t config_page;
	uint64_t sas_address, sata_sas_address;
	uint64_t parent_sas_address = 0;
	u16 ioc_pg8_flags = le16toh(sc->ioc_pg8.Flags);
	u32 device_info, parent_devinfo = 0;
	unsigned int id;
	int ret;
	int error = 0;
	struct mpssas_lun *lun;

	sassc = sc->sassc;
	mpssas_startup_increment(sassc);
	if ((mps_config_get_sas_device_pg0(sc, &mpi_reply, &config_page,
	     MPI2_SAS_DEVICE_PGAD_FORM_HANDLE, handle))) {
		printf("%s: error reading SAS device page0\n", __func__);
		error = ENXIO;
		goto out;
	}

	device_info = le32toh(config_page.DeviceInfo);

	if (((device_info & MPI2_SAS_DEVICE_INFO_SMP_TARGET) == 0)
	 && (le16toh(config_page.ParentDevHandle) != 0)) {
		Mpi2ConfigReply_t tmp_mpi_reply;
		Mpi2SasDevicePage0_t parent_config_page;

		if ((mps_config_get_sas_device_pg0(sc, &tmp_mpi_reply,
		     &parent_config_page, MPI2_SAS_DEVICE_PGAD_FORM_HANDLE,
		     le16toh(config_page.ParentDevHandle)))) {
			printf("%s: error reading SAS device %#x page0\n",
			       __func__, le16toh(config_page.ParentDevHandle));
		} else {
			parent_sas_address = parent_config_page.SASAddress.High;
			parent_sas_address = (parent_sas_address << 32) |
				parent_config_page.SASAddress.Low;
			parent_devinfo = le32toh(parent_config_page.DeviceInfo);
		}
	}
	/* TODO Check proper endianess */
	sas_address = config_page.SASAddress.High;
	sas_address = (sas_address << 32) | 
	    config_page.SASAddress.Low;

	if ((ioc_pg8_flags & MPI2_IOCPAGE8_FLAGS_MASK_MAPPING_MODE)
		    == MPI2_IOCPAGE8_FLAGS_DEVICE_PERSISTENCE_MAPPING) {
		if (device_info & MPI2_SAS_DEVICE_INFO_SATA_DEVICE) {
			ret = mpssas_get_sas_address_for_sata_disk(sc,
			    &sata_sas_address, handle, device_info);
			if (!ret)
				id = mps_mapping_get_sas_id(sc,
				    sata_sas_address, handle);
			else
				id = mps_mapping_get_sas_id(sc,
				    sas_address, handle);
		} else
			id = mps_mapping_get_sas_id(sc, sas_address,
			    handle);
	} else
		id = mps_mapping_get_sas_id(sc, sas_address, handle);

	if (id == MPS_MAP_BAD_ID) {
		printf("failure at %s:%d/%s()! Could not get ID for device "
		    "with handle 0x%04x\n", __FILE__, __LINE__, __func__,
		    handle);
		error = ENXIO;
		goto out;
	}
	mps_dprint(sc, MPS_INFO, "SAS Address from SAS device page0 = %jx\n",
	    sas_address);
	targ = &sassc->targets[id];
	targ->devinfo = device_info;
	targ->devname = le32toh(config_page.DeviceName.High);
	targ->devname = (targ->devname << 32) | 
	    le32toh(config_page.DeviceName.Low);
	targ->encl_handle = le16toh(config_page.EnclosureHandle);
	targ->encl_slot = le16toh(config_page.Slot);
	targ->handle = handle;
	targ->parent_handle = le16toh(config_page.ParentDevHandle);
	targ->sasaddr = mps_to_u64(&config_page.SASAddress);
	targ->parent_sasaddr = le64toh(parent_sas_address);
	targ->parent_devinfo = parent_devinfo;
	targ->tid = id;
	targ->linkrate = (linkrate>>4);
	targ->flags = 0;
	TAILQ_INIT(&targ->commands);
	TAILQ_INIT(&targ->timedout_commands);
	while(!SLIST_EMPTY(&targ->luns)) {
		lun = SLIST_FIRST(&targ->luns);
		SLIST_REMOVE_HEAD(&targ->luns, lun_link);
		free(lun, M_MPT2);
	}
	SLIST_INIT(&targ->luns);

	mps_describe_devinfo(targ->devinfo, devstring, 80);
	mps_dprint(sc, MPS_INFO, "Found device <%s> <%s> <0x%04x> <%d/%d>\n", devstring,
	    mps_describe_table(mps_linkrate_names, targ->linkrate),
	    targ->handle, targ->encl_handle, targ->encl_slot);
	if ((sassc->flags & MPSSAS_IN_STARTUP) == 0)
		mpssas_rescan_target(sc, targ);
	mps_dprint(sc, MPS_INFO, "Target id 0x%x added\n", targ->tid);
out:
	mpssas_startup_decrement(sassc);
	return (error);
	
}
Ejemplo n.º 13
0
/**
 * _mps_fw_work - delayed task for processing firmware events
 * @sc: per adapter object
 * @fw_event: The fw_event_work object
 * Context: user.
 *
 * Return nothing.
 */
static void
mpssas_fw_work(struct mps_softc *sc, struct mps_fw_event_work *fw_event)
{
	struct mpssas_softc *sassc;
	sassc = sc->sassc;

	mps_dprint(sc, MPS_INFO, "(%d)->(%s) Working on  Event: [%x]\n",
			event_count++,__func__,fw_event->event);
	switch (fw_event->event) {
	case MPI2_EVENT_SAS_TOPOLOGY_CHANGE_LIST: 
	{
		MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *data;
		MPI2_EVENT_SAS_TOPO_PHY_ENTRY *phy;
		int i;

		data = (MPI2_EVENT_DATA_SAS_TOPOLOGY_CHANGE_LIST *)
		    fw_event->event_data;

		mps_mapping_topology_change_event(sc, fw_event->event_data);

		for (i = 0; i < data->NumEntries; i++) {
			phy = &data->PHY[i];
			switch (phy->PhyStatus & MPI2_EVENT_SAS_TOPO_RC_MASK) {
			case MPI2_EVENT_SAS_TOPO_RC_TARG_ADDED:
				if (mpssas_add_device(sc,
				    le16toh(phy->AttachedDevHandle), phy->LinkRate)){
					printf("%s: failed to add device with "
					    "handle 0x%x\n", __func__,
					    le16toh(phy->AttachedDevHandle));
					mpssas_prepare_remove(sassc, le16toh(
						phy->AttachedDevHandle));
				}
				break;
			case MPI2_EVENT_SAS_TOPO_RC_TARG_NOT_RESPONDING:
				mpssas_prepare_remove(sassc,le16toh( 
					phy->AttachedDevHandle));
				break;
			case MPI2_EVENT_SAS_TOPO_RC_PHY_CHANGED:
			case MPI2_EVENT_SAS_TOPO_RC_NO_CHANGE:
			case MPI2_EVENT_SAS_TOPO_RC_DELAY_NOT_RESPONDING:
			default:
				break;
			}
		}
		/*
		 * refcount was incremented for this event in
		 * mpssas_evt_handler.  Decrement it here because the event has
		 * been processed.
		 */
		mpssas_startup_decrement(sassc);
		break;
	}
	case MPI2_EVENT_SAS_DISCOVERY:
	{
		MPI2_EVENT_DATA_SAS_DISCOVERY *data;

		data = (MPI2_EVENT_DATA_SAS_DISCOVERY *)fw_event->event_data;

		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_STARTED)
			mps_dprint(sc, MPS_TRACE,"SAS discovery start event\n");
		if (data->ReasonCode & MPI2_EVENT_SAS_DISC_RC_COMPLETED) {
			mps_dprint(sc, MPS_TRACE,"SAS discovery stop event\n");
			sassc->flags &= ~MPSSAS_IN_DISCOVERY;
			mpssas_discovery_end(sassc);
		}
		break;
	}
	case MPI2_EVENT_SAS_ENCL_DEVICE_STATUS_CHANGE:
	{
		Mpi2EventDataSasEnclDevStatusChange_t *data;
		data = (Mpi2EventDataSasEnclDevStatusChange_t *)
		    fw_event->event_data;
		mps_mapping_enclosure_dev_status_change_event(sc,
		    fw_event->event_data);
		break;
	}
	case MPI2_EVENT_IR_CONFIGURATION_CHANGE_LIST:
	{
		Mpi2EventIrConfigElement_t *element;
		int i;
		u8 foreign_config;
		Mpi2EventDataIrConfigChangeList_t *event_data;
		struct mpssas_target *targ;
		unsigned int id;

		event_data = fw_event->event_data;
		foreign_config = (le32toh(event_data->Flags) &
		    MPI2_EVENT_IR_CHANGE_FLAGS_FOREIGN_CONFIG) ? 1 : 0;

		element =
		    (Mpi2EventIrConfigElement_t *)&event_data->ConfigElement[0];
		id = mps_mapping_get_raid_id_from_handle
		    (sc, element->VolDevHandle);

		mps_mapping_ir_config_change_event(sc, event_data);

		for (i = 0; i < event_data->NumElements; i++, element++) {
			switch (element->ReasonCode) {
			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_CREATED:
			case MPI2_EVENT_IR_CHANGE_RC_ADDED:
				if (!foreign_config) {
					if (mpssas_volume_add(sc, le16toh(element->VolDevHandle))){
						printf("%s: failed to add RAID "
						    "volume with handle 0x%x\n",
						    __func__, le16toh(element->
						    VolDevHandle));
					}
				}
				break;
			case MPI2_EVENT_IR_CHANGE_RC_VOLUME_DELETED:
			case MPI2_EVENT_IR_CHANGE_RC_REMOVED:
				/*
				 * Rescan after volume is deleted or removed.
				 */
				if (!foreign_config) {
					if (id == MPS_MAP_BAD_ID) {
						printf("%s: could not get ID "
						    "for volume with handle "
						    "0x%04x\n", __func__,
						    le16toh(element->VolDevHandle));
						break;
					}
					
					targ = &sassc->targets[id];
					targ->handle = 0x0;
					targ->encl_slot = 0x0;
					targ->encl_handle = 0x0;
					targ->exp_dev_handle = 0x0;
					targ->phy_num = 0x0;
					targ->linkrate = 0x0;
					mpssas_rescan_target(sc, targ);
					printf("RAID target id 0x%x removed\n",
					    targ->tid);
				}
				break;
			case MPI2_EVENT_IR_CHANGE_RC_PD_CREATED:
			case MPI2_EVENT_IR_CHANGE_RC_HIDE:
				/*
				 * Phys Disk of a volume has been created.  Hide
				 * it from the OS.
				 */
				targ = mpssas_find_target_by_handle(sassc, 0, element->PhysDiskDevHandle);
				if (targ == NULL) 
					break;
				
				/* Set raid component flags only if it is not WD.
				 * OR WrapDrive with WD_HIDE_ALWAYS/WD_HIDE_IF_VOLUME is set in NVRAM
				 */
				if((!sc->WD_available) ||
				((sc->WD_available && 
				(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
				(sc->WD_valid_config && (sc->WD_hide_expose ==
				MPS_WD_HIDE_IF_VOLUME)))) {
					targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
				}
				mpssas_rescan_target(sc, targ);
				
				break;
			case MPI2_EVENT_IR_CHANGE_RC_PD_DELETED:
				/*
				 * Phys Disk of a volume has been deleted.
				 * Expose it to the OS.
				 */
				if (mpssas_add_device(sc,
				    le16toh(element->PhysDiskDevHandle), 0)){
					printf("%s: failed to add device with "
					    "handle 0x%x\n", __func__,
					    le16toh(element->PhysDiskDevHandle));
					mpssas_prepare_remove(sassc, le16toh(element->
					    PhysDiskDevHandle));
				}
				break;
			}
		}
		/*
		 * refcount was incremented for this event in
		 * mpssas_evt_handler.  Decrement it here because the event has
		 * been processed.
		 */
		mpssas_startup_decrement(sassc);
		break;
	}
	case MPI2_EVENT_IR_VOLUME:
	{
		Mpi2EventDataIrVolume_t *event_data = fw_event->event_data;

		/*
		 * Informational only.
		 */
		mps_dprint(sc, MPS_INFO, "Received IR Volume event:\n");
		switch (event_data->ReasonCode) {
		case MPI2_EVENT_IR_VOLUME_RC_SETTINGS_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Volume Settings "
  			    "changed from 0x%x to 0x%x for Volome with "
 			    "handle 0x%x", le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue),
 			    le16toh(event_data->VolDevHandle));
			break;
		case MPI2_EVENT_IR_VOLUME_RC_STATUS_FLAGS_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Volume Status "
  			    "changed from 0x%x to 0x%x for Volome with "
 			    "handle 0x%x", le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue),
 			    le16toh(event_data->VolDevHandle));
			break;
		case MPI2_EVENT_IR_VOLUME_RC_STATE_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Volume State "
  			    "changed from 0x%x to 0x%x for Volome with "
 			    "handle 0x%x", le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue),
 			    le16toh(event_data->VolDevHandle));
				u32 state;
				struct mpssas_target *targ;
				state = le32toh(event_data->NewValue);
				switch (state) {
				case MPI2_RAID_VOL_STATE_MISSING:
				case MPI2_RAID_VOL_STATE_FAILED:
					mpssas_prepare_volume_remove(sassc, event_data->
							VolDevHandle);
					break;
		 
				case MPI2_RAID_VOL_STATE_ONLINE:
				case MPI2_RAID_VOL_STATE_DEGRADED:
				case MPI2_RAID_VOL_STATE_OPTIMAL:
					targ = mpssas_find_target_by_handle(sassc, 0, event_data->VolDevHandle);
					if (targ) {
						printf("%s %d: Volume handle 0x%x is already added \n",
							       	__func__, __LINE__ , event_data->VolDevHandle);
						break;
					}
					if (mpssas_volume_add(sc, le16toh(event_data->VolDevHandle))) {
						printf("%s: failed to add RAID "
							"volume with handle 0x%x\n",
							__func__, le16toh(event_data->
							VolDevHandle));
					}
					break;
				default:
					break;
				}
			break;
		default:
			break;
		}
		break;
	}
	case MPI2_EVENT_IR_PHYSICAL_DISK:
	{
		Mpi2EventDataIrPhysicalDisk_t *event_data =
		    fw_event->event_data;
		struct mpssas_target *targ;

		/*
		 * Informational only.
		 */
		mps_dprint(sc, MPS_INFO, "Received IR Phys Disk event:\n");
		switch (event_data->ReasonCode) {
		case MPI2_EVENT_IR_PHYSDISK_RC_SETTINGS_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Phys Disk Settings "
  			    "changed from 0x%x to 0x%x for Phys Disk Number "
  			    "%d and handle 0x%x at Enclosure handle 0x%x, Slot "
 			    "%d", le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue),
 				event_data->PhysDiskNum,
 			    le16toh(event_data->PhysDiskDevHandle),
 			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
			break;
		case MPI2_EVENT_IR_PHYSDISK_RC_STATUS_FLAGS_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Phys Disk Status changed "
  			    "from 0x%x to 0x%x for Phys Disk Number %d and "
  			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
 				le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue), event_data->PhysDiskNum,
 			    le16toh(event_data->PhysDiskDevHandle),
 			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
			break;
		case MPI2_EVENT_IR_PHYSDISK_RC_STATE_CHANGED:
  			mps_dprint(sc, MPS_INFO, "   Phys Disk State changed "
  			    "from 0x%x to 0x%x for Phys Disk Number %d and "
  			    "handle 0x%x at Enclosure handle 0x%x, Slot %d",
 				le32toh(event_data->PreviousValue),
 			    le32toh(event_data->NewValue), event_data->PhysDiskNum,
 			    le16toh(event_data->PhysDiskDevHandle),
 			    le16toh(event_data->EnclosureHandle), le16toh(event_data->Slot));
			switch (event_data->NewValue) {
				case MPI2_RAID_PD_STATE_ONLINE:
				case MPI2_RAID_PD_STATE_DEGRADED:
				case MPI2_RAID_PD_STATE_REBUILDING:
				case MPI2_RAID_PD_STATE_OPTIMAL:
				case MPI2_RAID_PD_STATE_HOT_SPARE:
					targ = mpssas_find_target_by_handle(sassc, 0, 
							event_data->PhysDiskDevHandle);
					if (targ) {
						if(!sc->WD_available) {
							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
							printf("%s %d: Found Target for handle 0x%x.  \n",
							__func__, __LINE__ , event_data->PhysDiskDevHandle);
						} else if ((sc->WD_available && 
							(sc->WD_hide_expose == MPS_WD_HIDE_ALWAYS)) ||
        						(sc->WD_valid_config && (sc->WD_hide_expose ==
        						MPS_WD_HIDE_IF_VOLUME))) {
							targ->flags |= MPS_TARGET_FLAGS_RAID_COMPONENT;
							printf("%s %d: WD: Found Target for handle 0x%x.  \n",
							__func__, __LINE__ , event_data->PhysDiskDevHandle);
						}
 					}  		
				break;
				case MPI2_RAID_PD_STATE_OFFLINE:
				case MPI2_RAID_PD_STATE_NOT_CONFIGURED:
				case MPI2_RAID_PD_STATE_NOT_COMPATIBLE:
				default:
					targ = mpssas_find_target_by_handle(sassc, 0, 
							event_data->PhysDiskDevHandle);
					if (targ) {
						targ->flags |= ~MPS_TARGET_FLAGS_RAID_COMPONENT;
						printf("%s %d: Found Target for handle 0x%x.  \n",
						__func__, __LINE__ , event_data->PhysDiskDevHandle);
					}
				break;
			}
		default:
			break;
		}
		break;
	}
	case MPI2_EVENT_IR_OPERATION_STATUS:
	{
		Mpi2EventDataIrOperationStatus_t *event_data =
		    fw_event->event_data;

		/*
		 * Informational only.
		 */
		mps_dprint(sc, MPS_INFO, "Received IR Op Status event:\n");
		mps_dprint(sc, MPS_INFO, "   RAID Operation of %d is %d "
		    "percent complete for Volume with handle 0x%x",
		    event_data->RAIDOperation, event_data->PercentComplete,
		    le16toh(event_data->VolDevHandle));
		break;
	}
	case MPI2_EVENT_LOG_ENTRY_ADDED:
	{
		pMpi2EventDataLogEntryAdded_t	logEntry;
		uint16_t			logQualifier;
		uint8_t				logCode;

		logEntry = (pMpi2EventDataLogEntryAdded_t)fw_event->event_data;
		logQualifier = logEntry->LogEntryQualifier;

		if (logQualifier == MPI2_WD_LOG_ENTRY) {
			logCode = logEntry->LogData[0];

			switch (logCode) {
			case MPI2_WD_SSD_THROTTLING:
				printf("WarpDrive Warning: IO Throttling has "
				    "occurred in the WarpDrive subsystem. "
				    "Check WarpDrive documentation for "
				    "additional details\n");
				break;
			case MPI2_WD_DRIVE_LIFE_WARN:
				printf("WarpDrive Warning: Program/Erase "
				    "Cycles for the WarpDrive subsystem in "
				    "degraded range. Check WarpDrive "
				    "documentation for additional details\n");
				break;
			case MPI2_WD_DRIVE_LIFE_DEAD:
				printf("WarpDrive Fatal Error: There are no "
				    "Program/Erase Cycles for the WarpDrive "
				    "subsystem. The storage device will be in "
				    "read-only mode. Check WarpDrive "
				    "documentation for additional details\n");
				break;
			case MPI2_WD_RAIL_MON_FAIL:
				printf("WarpDrive Fatal Error: The Backup Rail "
				    "Monitor has failed on the WarpDrive "
				    "subsystem. Check WarpDrive documentation "
				    "for additional details\n");
				break;
			default:
				break;
			}
		}
		break;
	}
	case MPI2_EVENT_SAS_DEVICE_STATUS_CHANGE:
	case MPI2_EVENT_SAS_BROADCAST_PRIMITIVE:
	default:
		mps_dprint(sc, MPS_TRACE,"Unhandled event 0x%0X\n",
		    fw_event->event);
		break;

	}
	mps_dprint(sc, MPS_INFO, "(%d)->(%s) Event Free: [%x]\n",event_count,__func__, fw_event->event);
	mpssas_fw_event_free(sc, fw_event);
}
Ejemplo n.º 14
0
uint32_t Tx::txVersion() const
{
    return static_cast<int32_t>(le32toh(*((uint32_t*)m_data.begin())));
}
Ejemplo n.º 15
0
static int
yds_intr(void *p)
{
	struct yds_softc *sc = p;
#if NMPU > 0
	struct mpu_softc *sc_mpu = device_private(sc->sc_mpu);
#endif
	u_int status;

	mutex_spin_enter(&sc->sc_intr_lock);

	status = YREAD4(sc, YDS_STATUS);
	DPRINTFN(1, ("yds_intr: status=%08x\n", status));
	if ((status & (YDS_STAT_INT|YDS_STAT_TINT)) == 0) {
#if NMPU > 0
		if (sc_mpu)
			return mpu_intr(sc_mpu);
#endif
		mutex_spin_exit(&sc->sc_intr_lock);
		return 0;
	}

	if (status & YDS_STAT_TINT) {
		YWRITE4(sc, YDS_STATUS, YDS_STAT_TINT);
		printf ("yds_intr: timeout!\n");
	}

	if (status & YDS_STAT_INT) {
		int nbank;

		nbank = (YREAD4(sc, YDS_CONTROL_SELECT) == 0);
		/* Clear interrupt flag */
		YWRITE4(sc, YDS_STATUS, YDS_STAT_INT);

		/* Buffer for the next frame is always ready. */
		YWRITE4(sc, YDS_MODE, YREAD4(sc, YDS_MODE) | YDS_MODE_ACTV2);

		if (sc->sc_play.intr) {
			u_int dma, ccpu, blk, len;

			/* Sync play slot control data */
			bus_dmamap_sync(sc->sc_dmatag, sc->sc_ctrldata.map,
					sc->pbankoff,
					sizeof(struct play_slot_ctrl_bank)*
					    le32toh(*sc->ptbl)*
					    N_PLAY_SLOT_CTRL_BANK,
					BUS_DMASYNC_POSTWRITE|
					BUS_DMASYNC_POSTREAD);
			dma = le32toh(sc->pbankp[nbank]->pgstart) * sc->sc_play.factor;
			ccpu = sc->sc_play.offset;
			blk = sc->sc_play.blksize;
			len = sc->sc_play.length;

			if (((dma > ccpu) && (dma - ccpu > blk * 2)) ||
			    ((ccpu > dma) && (dma + len - ccpu > blk * 2))) {
				/* We can fill the next block */
				/* Sync ring buffer for previous write */
				bus_dmamap_sync(sc->sc_dmatag,
						sc->sc_play.dma->map,
						ccpu, blk,
						BUS_DMASYNC_POSTWRITE);
				sc->sc_play.intr(sc->sc_play.intr_arg);
				sc->sc_play.offset += blk;
				if (sc->sc_play.offset >= len) {
					sc->sc_play.offset -= len;
#ifdef DIAGNOSTIC
					if (sc->sc_play.offset != 0)
						printf ("Audio ringbuffer botch\n");
#endif
				}
				/* Sync ring buffer for next write */
				bus_dmamap_sync(sc->sc_dmatag,
						sc->sc_play.dma->map,
						ccpu, blk,
						BUS_DMASYNC_PREWRITE);
			}
		}
		if (sc->sc_rec.intr) {
			u_int dma, ccpu, blk, len;

			/* Sync rec slot control data */
			bus_dmamap_sync(sc->sc_dmatag, sc->sc_ctrldata.map,
					sc->rbankoff,
					sizeof(struct rec_slot_ctrl_bank)*
					    N_REC_SLOT_CTRL*
					    N_REC_SLOT_CTRL_BANK,
					BUS_DMASYNC_POSTWRITE|
					BUS_DMASYNC_POSTREAD);
			dma = le32toh(sc->rbank[YDS_INPUT_SLOT*2 + nbank].pgstartadr);
			ccpu = sc->sc_rec.offset;
			blk = sc->sc_rec.blksize;
			len = sc->sc_rec.length;

			if (((dma > ccpu) && (dma - ccpu > blk * 2)) ||
			    ((ccpu > dma) && (dma + len - ccpu > blk * 2))) {
				/* We can drain the current block */
				/* Sync ring buffer first */
				bus_dmamap_sync(sc->sc_dmatag,
						sc->sc_rec.dma->map,
						ccpu, blk,
						BUS_DMASYNC_POSTREAD);
				sc->sc_rec.intr(sc->sc_rec.intr_arg);
				sc->sc_rec.offset += blk;
				if (sc->sc_rec.offset >= len) {
					sc->sc_rec.offset -= len;
#ifdef DIAGNOSTIC
					if (sc->sc_rec.offset != 0)
						printf ("Audio ringbuffer botch\n");
#endif
				}
				/* Sync ring buffer for next read */
				bus_dmamap_sync(sc->sc_dmatag,
						sc->sc_rec.dma->map,
						ccpu, blk,
						BUS_DMASYNC_PREREAD);
			}
		}
	}

	mutex_spin_exit(&sc->sc_intr_lock);
	return 1;
}
Ejemplo n.º 16
0
void
manage_request()
{
    ntlmhdr *fast_header;
    char buf[BUFFER_SIZE];
    const char *ch;
    char *ch2, *decoded, *cred = NULL;
    int plen;

    if (fgets(buf, BUFFER_SIZE, stdin) == NULL) {
	fprintf(stderr, "fgets() failed! dying..... errno=%d (%s)\n", errno,
	    strerror(errno));
	exit(1);		/* BIIG buffer */
    }
    debug("managing request\n");
    ch2 = memchr(buf, '\n', BUFFER_SIZE);	/* safer against overrun than strchr */
    if (ch2) {
	*ch2 = '\0';		/* terminate the string at newline. */
	ch = ch2;
    }
    debug("ntlm authenticator. Got '%s' from Squid\n", buf);

    if (memcmp(buf, "KK ", 3) == 0) {	/* authenticate-request */
	/* figure out what we got */
	decoded = base64_decode(buf + 3);
	/* Note: we don't need to manage memory at this point, since
	 *  base64_decode returns a pointer to static storage.
	 */

	if (!decoded) {		/* decoding failure, return error */
	    SEND("NA Packet format error, couldn't base64-decode");
	    return;
	}
	/* fast-track-decode request type. */
	fast_header = (struct _ntlmhdr *) decoded;

	/* sanity-check: it IS a NTLMSSP packet, isn't it? */
	if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) {
	    SEND("NA Broken authentication packet");
	    return;
	}
	switch (le32toh(fast_header->type)) {
	case NTLM_NEGOTIATE:
	    SEND("NA Invalid negotiation request received");
	    return;
	    /* notreached */
	case NTLM_CHALLENGE:
	    SEND("NA Got a challenge. We refuse to have our authority disputed");
	    return;
	    /* notreached */
	case NTLM_AUTHENTICATE:
	    /* check against the DC */
	    plen = strlen(buf) * 3 / 4;		/* we only need it here. Optimization */
	    signal(SIGALRM, timeout_during_auth);
	    alarm(30);
	    cred = ntlm_check_auth((ntlm_authenticate *) decoded, plen);
	    alarm(0);
	    signal(SIGALRM, SIG_DFL);
	    if (got_timeout != 0) {
		fprintf(stderr, "ntlm-auth[%ld]: Timeout during authentication.\n", (long)getpid());
		SEND("BH Timeout during authentication");
		got_timeout = 0;
		return;
	    }
	    if (cred == NULL) {
		int smblib_err, smb_errorclass, smb_errorcode, nb_error;
		if (ntlm_errno == NTLM_LOGON_ERROR) {	/* hackish */
			SEND("NA Logon Failure");
			return;
		}
		/* there was an error. We have two errno's to look at.
		 * libntlmssp's erno is insufficient, we'll have to look at
		 * the actual SMB library error codes, to acually figure
		 * out what's happening. The thing has braindamaged interfacess..*/
		smblib_err = SMB_Get_Last_Error();
		smb_errorclass = SMBlib_Error_Class(SMB_Get_Last_SMB_Err());
		smb_errorcode = SMBlib_Error_Code(SMB_Get_Last_SMB_Err());
		nb_error = RFCNB_Get_Last_Error();
		debug("No creds. SMBlib error %d, SMB error class %d, SMB error code %d, NB error %d\n",
		    smblib_err, smb_errorclass, smb_errorcode, nb_error);
		/* Should I use smblib_err? Actually it seems I can do as well
		 * without it.. */
		if (nb_error != 0) {	/* netbios-level error */
		    send_bh_or_ld("NetBios error!",
			(ntlm_authenticate *) decoded, plen);
		    fprintf(stderr, "NetBios error code %d (%s)\n", nb_error,
			RFCNB_Error_Strings[abs(nb_error)]);
		    return;
		}
		switch (smb_errorclass) {
		case SMBC_SUCCESS:
		    debug("Huh? Got a SMB success code but could check auth..");
		    SEND("NA Authentication failed");
		    /*
		     * send_bh_or_ld("SMB success, but no creds. Internal error?",
		     * (ntlm_authenticate *) decoded, plen);
		     */
		    return;
		case SMBC_ERRDOS:
		    /*this is the most important one for errors */
		    debug("DOS error\n");
		    switch (smb_errorcode) {
			/* two categories matter to us: those which could be
			 * server errors, and those which are auth errors */
		    case SMBD_noaccess:	/* 5 */
			SEND("NA Access denied");
			return;
		    case SMBD_badformat:
			SEND("NA bad format in authentication packet");
			return;
		    case SMBD_badaccess:
			SEND("NA Bad access request");
			return;
		    case SMBD_baddata:
			SEND("NA Bad Data");
			return;
		    default:
			send_bh_or_ld("DOS Error",
			    (ntlm_authenticate *) decoded, plen);
			return;
		    }
		case SMBC_ERRSRV:	/* server errors */
		    debug("Server error");
		    switch (smb_errorcode) {
			/* mostly same as above */
		    case SMBV_badpw:
			SEND("NA Bad password");
			return;
		    case SMBV_access:
			SEND("NA Server access error");
			return;
		    default:
			send_bh_or_ld("Server Error",
			    (ntlm_authenticate *) decoded, plen);
			return;
		    }
		case SMBC_ERRHRD:	/* hardware errors don't really matter */
		    send_bh_or_ld("Domain Controller Hardware error",
			(ntlm_authenticate *) decoded, plen);
		    return;
		case SMBC_ERRCMD:
		    send_bh_or_ld("Domain Controller Command Error",
			(ntlm_authenticate *) decoded, plen);
		    return;
		}
                SEND("BH unknown internal error.");
                return;
	    }

	    lc(cred);		/* let's lowercase them for our convenience */
	    SEND2("AF %s", cred);
	    return;
	default:
	    SEND("BH unknown authentication packet type");
	    return;
	}


	return;
    }
    if (memcmp(buf, "YR", 2) == 0) {	/* refresh-request */
	dc_disconnect();
	ch = obtain_challenge();
	/* Robert says we can afford to wait forever. I'll trust him on this
	 * one */
	while (ch == NULL) {
	    sleep(30);
	    ch = obtain_challenge();
	}
	SEND2("TT %s", ch);
	return;
    }
    SEND("BH Helper detected protocol error");
    return;
/********* END ********/


}
Ejemplo n.º 17
0
static struct mbuf *
rtwn_rx_copy_to_mbuf(struct rtwn_softc *sc, struct r92c_rx_stat *stat,
    int totlen)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct mbuf *m;
	uint32_t rxdw0;
	int pktlen;

	RTWN_ASSERT_LOCKED(sc);

	/* Dump Rx descriptor. */
	RTWN_DPRINTF(sc, RTWN_DEBUG_RECV_DESC,
	    "%s: dw: 0 %08X, 1 %08X, 2 %08X, 3 %08X, 4 %08X, tsfl %08X\n",
	    __func__, le32toh(stat->rxdw0), le32toh(stat->rxdw1),
	    le32toh(stat->rxdw2), le32toh(stat->rxdw3), le32toh(stat->rxdw4),
	    le32toh(stat->tsf_low));

	/*
	 * don't pass packets to the ieee80211 framework if the driver isn't
	 * RUNNING.
	 */
	if (!(sc->sc_flags & RTWN_RUNNING))
		return (NULL);

	rxdw0 = le32toh(stat->rxdw0);
	if (__predict_false(rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR))) {
		/*
		 * This should not happen since we setup our Rx filter
		 * to not receive these frames.
		 */
		RTWN_DPRINTF(sc, RTWN_DEBUG_RECV,
		    "%s: RX flags error (%s)\n", __func__,
		    rxdw0 & R92C_RXDW0_CRCERR ? "CRC" : "ICV");
		goto fail;
	}

	pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
	if (__predict_false(pktlen < sizeof(struct ieee80211_frame_ack))) {
		/*
		 * Should not happen (because of Rx filter setup).
		 */
		RTWN_DPRINTF(sc, RTWN_DEBUG_RECV,
		    "%s: frame is too short: %d\n", __func__, pktlen);
		goto fail;
	}

	m = m_get2(totlen, M_NOWAIT, MT_DATA, M_PKTHDR);
	if (__predict_false(m == NULL)) {
		device_printf(sc->sc_dev, "%s: could not allocate RX mbuf\n",
		    __func__);
		goto fail;
	}

	/* Finalize mbuf. */
	memcpy(mtod(m, uint8_t *), (uint8_t *)stat, totlen);
	m->m_pkthdr.len = m->m_len = totlen;

	if (rtwn_check_frame(sc, m) != 0) {
		m_freem(m);
		goto fail;
	}

	return (m);
fail:
	counter_u64_add(ic->ic_ierrors, 1);
	return (NULL);
}
Ejemplo n.º 18
0
int main(int argc, char** argv)
{
	unsigned char addr;
	unsigned char data[5];
	
	char device_name[20];
	
	int opt;
	int bus = 0;
	int n = 0;
	char mode = 'b';
	int num;
	char format = 'x';

	uint8_t array_byte[128];

	const char *fmt_byte;
	const char *fmt_short;
	const char *fmt_long;
	
	char *base_name;

	while ((opt = getopt(argc, argv, "d:f:m:r:wh")) != -1) {
		switch (opt) {
			case 'f':
				format = optarg[0];
				break;
			case 'd':
				bus = atoi(optarg);
				break;
			case 'm':
				mode = optarg[0];
				break;
			case 'r':
				n = atoi(optarg);
				break;			
			case 'h':
			default:
				base_name = basename(argv[0]);

				fprintf(stderr, "Usage: %s [-d I2CBUS] [[-r N] [-m MODE] [-f FORMAT]] ADDRESS [VAL1 VAL2 ...]\n"
						"       %s 0x20 0x00\n"
						"       %s 0x20 -r 1 -m s -f d\n"
						"  I2CBUS is an integer\n"
						"  N      is an integer the number of element to be read\n"
						"  MODE   is b|s|l   - byte|short|long\n"
						"  FORMAT is x|d|u   - hex|signed|unsigned\n",
                    			base_name, base_name, base_name);
				return -1;
		}
	}
	//fprintf(stderr, "bus=%d; mode=%c; n=%d; optind=%d\n", bus, mode, n, optind);

	if ( format == 'x' ) {
		fmt_byte = "0x%02X";
		fmt_short = "0x%04X";
		fmt_long = "0x%08lX";
	}
	else if ( format == 'd' ) {
		fmt_byte = "%d";
		fmt_short = "%d";
		fmt_long = "%ld";	
	}
	else {
		fmt_byte = "%u";
		fmt_short = "%u";
		fmt_long = "%lu";
	}

	if ( mode == 's' ) {
		n *= 2;
	}
	else if ( mode == 'l' ) {
		n *= 4;
	}
	else if ( mode == 'c' ) {
	}
	
	if ( optind >= argc ) {
        fprintf(stderr, "Expected ADDRESS\n");
        return -1;
    	}	
	addr = _atoi(argv[optind++]);
	//fprintf(stderr, "addr=0x%02X\n", addr);

	num = 0;
	for (;optind < argc; optind++) {
		if ( num >= 128 )
			break;
		array_byte[num++] = (uint8_t)_atoi(argv[optind]);
	}	
	//fprintf(stderr, "num=%d\n", num);	

	sprintf(device_name, "/dev/i2c-%u", bus);
	fd = open(device_name,O_RDWR);
	if ( fd < 0 ) {
		fprintf(stderr, "Couldn't open %s!\n", device_name);
		return -2;
	}
	
	setaddr(addr);

	if ( num ) {
		if ( write(fd, array_byte, num) < 0 ) {
			fprintf(stderr, "Unable to write!\n");
			close(fd);
			return -2;
		}
	}
	
	if ( n ) {
		int i;

		n = n < 128 ? n : 128;
		read(fd, array_byte, n);
		
		if ( mode == 'c' ) {
			for ( i = 0; i < n; i++ ) {
				char c;
				
				c = array_byte[i];
				printf("%c", iscntrl(c) ? '.' : c);
			}
		
		}
		else if ( mode == 's' ) {
			union {
				uint16_t u16;
				uint8_t arr[2];
			} w;
			
			for ( i = 0; i < n; i += 2 ) {
				w.arr[0] = array_byte[i];
				w.arr[1] = array_byte[i + 1];
				
				if ( i != 0 )
					printf(" ");

				if ( format == 'd' )
					printf(fmt_short, (int16_t)le16toh(w.u16));
				else
					printf(fmt_short, (uint16_t)le16toh(w.u16));
			}
		}
		else if ( mode == 'l' ) {
			union {
				uint32_t u32;
				uint8_t arr[4];
			} w;
			
			for ( i = 0; i < n; i += 4 ) {
				w.arr[0] = array_byte[i];
				w.arr[1] = array_byte[i + 1];
				w.arr[2] = array_byte[i + 2];
				w.arr[3] = array_byte[i + 3];
				
				if ( i != 0 )
					printf(" ");

				if ( format == 'd' )
					printf(fmt_long, (int32_t)le32toh(w.u32));
				else
					printf(fmt_long, (uint32_t)le32toh(w.u32));
			}
	
		}		
		else {
			for ( i = 0; i < n; i++ ) {				
				if ( i != 0 )
					printf(" ");

				if ( format == 'd' )
					printf(fmt_byte, (int8_t)array_byte[i]);
				else				
					printf(fmt_byte, array_byte[i]);
			}
		}
		printf("\n");
	}
	
	close(fd);
	return 0;
}
Ejemplo n.º 19
0
	void net_process() {
		while (true) {
			struct bitcoin_msg_header header;
			if (read_all(sock, (char*)&header, sizeof(header)) != sizeof(header))
				return disconnect("failed to read message header");

			if (header.magic != BITCOIN_MAGIC)
				return disconnect("invalid magic bytes");

			struct timeval start_read;
			gettimeofday(&start_read, NULL);

			header.length = le32toh(header.length);
			if (header.length > 5000000)
				return disconnect("got message too large");

			auto msg = std::make_shared<std::vector<unsigned char> > (sizeof(struct bitcoin_msg_header) + uint32_t(header.length));
			if (read_all(sock, (char*)&(*msg)[sizeof(struct bitcoin_msg_header)], header.length) != int(header.length))
				return disconnect("failed to read message");

			unsigned char fullhash[32];
			CSHA256 hash;
			hash.Write(&(*msg)[sizeof(struct bitcoin_msg_header)], header.length).Finalize(fullhash);
			hash.Reset().Write(fullhash, sizeof(fullhash)).Finalize(fullhash);
			if (memcmp((char*)fullhash, header.checksum, sizeof(header.checksum)))
				return disconnect("got invalid message checksum");

			if (!strncmp(header.command, "version", strlen("version"))) {
				if (connected != 0)
					return disconnect("got invalid version");
				connected = 1;

				if (header.length < sizeof(struct bitcoin_version_start))
					return disconnect("got short version");
				struct bitcoin_version_start *their_version = (struct bitcoin_version_start*) &(*msg)[sizeof(struct bitcoin_msg_header)];

				printf("%s Protocol version %u\n", host.c_str(), le32toh(their_version->protocol_version));

				struct bitcoin_version_with_header version_msg;
				version_msg.version.start.timestamp = htole64(time(0));
				memcpy(((char*)&version_msg.version.end.user_agent) + 27, location, 7);
				static_assert(BITCOIN_UA_LENGTH == 27 + 7 + 2 /* 27 + 7 + '/' + '\0' */, "BITCOIN_UA changed in header but file not updated");

				prepare_message("version", (unsigned char*)&version_msg, sizeof(struct bitcoin_version));
				if (send_all(sock, (char*)&version_msg, sizeof(struct bitcoin_version_with_header)) != sizeof(struct bitcoin_version_with_header))
					return disconnect("failed to send version message");

				struct bitcoin_msg_header verack_header;
				prepare_message("verack", (unsigned char*)&verack_header, 0);
				if (send_all(sock, (char*)&verack_header, sizeof(struct bitcoin_msg_header)) != sizeof(struct bitcoin_msg_header))
					return disconnect("failed to send verack");

				continue;
			} else if (!strncmp(header.command, "verack", strlen("verack"))) {
				if (connected != 1)
					return disconnect("got invalid verack");
				connected = 2;
				send_mutex.unlock();

				continue;
			}

			if (connected != 2)
				return disconnect("got non-version, non-verack before version+verack");

			if (!strncmp(header.command, "ping", strlen("ping"))) {
				memcpy(&header.command, "pong", sizeof("pong"));
				memcpy(&(*msg)[0], &header, sizeof(struct bitcoin_msg_header));
				std::lock_guard<std::mutex> lock(send_mutex);
				if (send_all(sock, (char*)&(*msg)[0], sizeof(struct bitcoin_msg_header) + header.length) != int64_t(sizeof(struct bitcoin_msg_header) + header.length))
					return disconnect("failed to send pong");
				continue;
			} else if (!strncmp(header.command, "inv", strlen("inv"))) {
				std::lock_guard<std::mutex> lock(send_mutex);

				try {
					std::set<std::vector<unsigned char> > setRequestBlocks;
					std::set<std::vector<unsigned char> > setRequestTxn;

					std::vector<unsigned char>::const_iterator it = msg->begin();
					it += sizeof(struct bitcoin_msg_header);
					uint64_t count = read_varint(it, msg->end());
					if (count > 50000)
						return disconnect("inv count > MAX_INV_SZ");

					uint32_t MSG_TX = htole32(1);
					uint32_t MSG_BLOCK = htole32(2);

					for (uint64_t i = 0; i < count; i++) {
						move_forward(it, 4 + 32, msg->end());
						std::vector<unsigned char> hash(it-32, it);

						const uint32_t type = (*(it-(1+32)) << 24) | (*(it-(2+32)) << 16) | (*(it-(3+32)) << 8) | *(it-(4+32));
						if (type == MSG_TX) {
							if (!txnAlreadySeen.insert(hash).second)
								continue;
							setRequestTxn.insert(hash);
						} else if (type == MSG_BLOCK) {
							if (!blocksAlreadySeen.insert(hash).second)
								continue;
							setRequestBlocks.insert(hash);
						} else
							return disconnect("unknown inv type");
					}

					if (setRequestBlocks.size()) {
						std::vector<unsigned char> getdataMsg;
						std::vector<unsigned char> invCount = varint(setRequestBlocks.size());
						getdataMsg.reserve(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36);

						getdataMsg.insert(getdataMsg.end(), sizeof(struct bitcoin_msg_header), 0);
						getdataMsg.insert(getdataMsg.end(), invCount.begin(), invCount.end());

						for (auto& hash : setRequestBlocks) {
							getdataMsg.insert(getdataMsg.end(), (unsigned char*)&MSG_BLOCK, ((unsigned char*)&MSG_BLOCK) + 4);
							getdataMsg.insert(getdataMsg.end(), hash.begin(), hash.end());
						}

						prepare_message("getdata", (unsigned char*)&getdataMsg[0], invCount.size() + setRequestBlocks.size()*36);
						if (send_all(sock, (char*)&getdataMsg[0], sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36) !=
								int(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestBlocks.size()*36))
							return disconnect("error sending getdata");

						for (auto& hash : setRequestBlocks) {
							struct timeval tv;
							gettimeofday(&tv, NULL);
							for (unsigned int i = 0; i < hash.size(); i++)
								printf("%02x", hash[hash.size() - i - 1]);
							printf(" requested from %s at %lu\n", host.c_str(), uint64_t(tv.tv_sec) * 1000 + uint64_t(tv.tv_usec) / 1000);
						}
					}

					if (setRequestTxn.size()) {
						std::vector<unsigned char> getdataMsg;
						std::vector<unsigned char> invCount = varint(setRequestTxn.size());
						getdataMsg.reserve(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36);

						getdataMsg.insert(getdataMsg.end(), sizeof(struct bitcoin_msg_header), 0);
						getdataMsg.insert(getdataMsg.end(), invCount.begin(), invCount.end());

						for (const std::vector<unsigned char>& hash : setRequestTxn) {
							getdataMsg.insert(getdataMsg.end(), (unsigned char*)&MSG_TX, ((unsigned char*)&MSG_TX) + 4);
							getdataMsg.insert(getdataMsg.end(), hash.begin(), hash.end());
						}

						prepare_message("getdata", (unsigned char*)&getdataMsg[0], invCount.size() + setRequestTxn.size()*36);
						if (send_all(sock, (char*)&getdataMsg[0], sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36) !=
								int(sizeof(struct bitcoin_msg_header) + invCount.size() + setRequestTxn.size()*36))
							return disconnect("error sending getdata");
					}
				} catch (read_exception) {
					return disconnect("failed to process inv");
				}
				continue;
			}

			memcpy(&(*msg)[0], &header, sizeof(struct bitcoin_msg_header));
			if (!strncmp(header.command, "block", strlen("block"))) {
				provide_block(this, msg, start_read);
			} else if (!strncmp(header.command, "tx", strlen("tx"))) {
				provide_transaction(this, msg);
			}
		}
	}
Ejemplo n.º 20
0
Archivo: dbzx.c Proyecto: cg011235/zxfs
int
main(int argc, char *argv[])
{
    char cmd;
    struct stat buf;
    int devfd;
    zx_super_t sb;
    zx_inode_t in;
    zx_dirent_t dir;
    char ibitmap[65];
    char bbitmap[577];
    int i, j, p;
    time_t t;
    struct tm *tm;
    char blk[ZX_BLOCK_SIZE];
    char tbuf[1];

    /*
     * Check if correct arguments are passed
     */
    if (argc != 2) {
        printf("Usage: dbzx <block device>\n");
        exit(EXIT_FAILURE);
    }

    /*
     * Confirm that we can access given device file
     * and is a block device.
     */
    if (stat(argv[1], &buf) < 0) {
        fprintf(stderr, "mkzx: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (!S_ISBLK(buf.st_mode)) {
        fprintf(stderr, "mkzx: %s is not a block device\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    printf("[OK]\tgiven device is block device\n");

    if ((devfd = open(argv[1], O_RDONLY)) < 0) {
        fprintf(stderr, "mkzx: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }
    printf("[OK]\topened devie\n");

    if (lseek(devfd, ZX_SEEK_BLOCKS * ZX_BLOCK_SIZE, SEEK_SET) < 0) {
        fprintf(stderr, "mkzx: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }
    printf("[OK]\tfound desirable space\n");

    printf("[OK]\tall set to launch dbzx (press h for help)\n");

    while (printf("dbzx:>") && scanf("%s", &cmd)) {
        switch (cmd) {
            case 'q' :
                exit(EXIT_SUCCESS);
                break;

            case 's' :
                if (lseek(devfd, ZX_SUPER_START * ZX_BLOCK_SIZE, SEEK_SET) < 0) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }
                memset(&sb, 0, ZX_SUPER_SIZE);
                if (read(devfd, &sb, ZX_SUPER_SIZE) != ZX_SUPER_SIZE) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }
                printf("\tmagic: %#x\n", le32toh(sb.s_magic));
                printf("\tstate: %#x\n", le32toh(sb.s_state));
                printf("\tfree inodes: %d\n", le32toh(sb.s_free_inodes));
                printf("\tfree blocks: %d\n", le32toh(sb.s_free_blocks));
                memset(ibitmap, 0, sizeof(ibitmap));
                for (i = 0; i < 64; i++) {
                    if (le64toh(sb.s_inode_list) & ((long)1 << (long)i)) {
                        ibitmap[i] = '1';
                    } else {
                        ibitmap[i] = '0';
                    }
                }
                ibitmap[64] ='\0';
                printf("\tinode bitmap: %s\n", ibitmap);

                memset(bbitmap, 0, sizeof(bbitmap));
                p = 0;
                for (i = 0; i < 18; i++) {
                    for (j = 0; j < 32; j++) {
                        if (sb.s_block_list[i] & (1 << j)) {
                            bbitmap[p++] = '1';
                        } else {
                            bbitmap[p++] = '0';
                        }
                    }
                }
                bbitmap[576] ='\0';
                printf("\tblock bitmap: %s\n", bbitmap);
                break;

            case 'i':
                printf("\tino:");
                scanf("%d", &i);

                if (lseek(devfd, ((ZX_INODE_START * ZX_BLOCK_SIZE) + (i * ZX_INODE_SIZE)), SEEK_SET) < 0) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }
                memset(&in, 0, ZX_INODE_SIZE);
                if (read(devfd, &in, ZX_INODE_SIZE) != ZX_INODE_SIZE) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }
                printf("\tmode: %#x\n", in.i_mode);
                printf("\tlinks: %hu\n", in.i_links);
                t = in.i_atime;
                tm = localtime (&t);
                printf("\tatime: %s", (char *) asctime(tm));
                t = in.i_mtime;
                tm = localtime (&t);
                printf("\tmtime: %s", (char *) asctime(tm));
                t = in.i_ctime;
                tm = localtime (&t);
                printf("\tctime: %s", (char *) asctime(tm));
                printf("\tuid: %hu\n", in.i_uid);
                printf("\tgid: %hu\n", in.i_gid);
                printf("\tsize: %hu\n", in.i_size);
                printf("\tblocks: %hu\n", in.i_blocks);
                printf("\tblock addr:\n");
                for (i = 0; i < le16toh(in.i_blocks); i++) {
                    printf("\t\t%d:%d\n", i + 1, le32toh(in.i_block[i]));
                }
                break;

            case 'd':
                printf("\tbno:");
                scanf("%d", &i);

                if (lseek(devfd, (i * ZX_BLOCK_SIZE), SEEK_SET) < 0) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }

                for (j = 0; j < 16; j++) {
                    memset(&dir, 0, ZX_DIR_SIZE);
                    if (read(devfd, &dir, ZX_DIR_SIZE) != ZX_DIR_SIZE) {
                        fprintf(stderr, ": %s\n", strerror(errno));
                        break;
                    }
                    printf("\t%d:\t%u\t%s\n", j, dir.d_inode, dir.d_name);
                }
                break;

            case 'h':
                printf("dbzx command help\n");
                printf("\th: print help menu\n");
                printf("\tq: quit\n");
                printf("\ts: print super block\n");
                printf("\ti: print inode\n");
                printf("\td: print directory entries\n");
                printf("\tp: print disk block in hex\n");
                break;

            case 'p':
                printf("\tbno:");
                scanf("%d", &i);

                if (lseek(devfd, (i * ZX_BLOCK_SIZE), SEEK_SET) < 0) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }
                memset(&blk, 0, ZX_BLOCK_SIZE);
                if (read(devfd, &blk, ZX_BLOCK_SIZE) != ZX_BLOCK_SIZE) {
                    fprintf(stderr, ": %s\n", strerror(errno));
                    break;
                }

                for (j = 1; j <= ZX_BLOCK_SIZE; j++) { 
                    printf("\t%#x", blk[j - 1]);
                    if (j % 9 == 0)
                        printf("\n");
                }
                printf("\n");
                break;
        }
    }

    return 0;
}
Ejemplo n.º 21
0
int journal_file_verify(
                JournalFile *f,
                const char *key,
                usec_t *first_contained, usec_t *last_validated, usec_t *last_contained,
                bool show_progress) {
        int r;
        Object *o;
        uint64_t p = 0, last_epoch = 0, last_tag_realtime = 0, last_sealed_realtime = 0;

        uint64_t entry_seqnum = 0, entry_monotonic = 0, entry_realtime = 0;
        sd_id128_t entry_boot_id;
        bool entry_seqnum_set = false, entry_monotonic_set = false, entry_realtime_set = false, found_main_entry_array = false;
        uint64_t n_weird = 0, n_objects = 0, n_entries = 0, n_data = 0, n_fields = 0, n_data_hash_tables = 0, n_field_hash_tables = 0, n_entry_arrays = 0, n_tags = 0;
        usec_t last_usec = 0;
        int data_fd = -1, entry_fd = -1, entry_array_fd = -1;
        char data_path[] = "/var/tmp/journal-data-XXXXXX",
                entry_path[] = "/var/tmp/journal-entry-XXXXXX",
                entry_array_path[] = "/var/tmp/journal-entry-array-XXXXXX";
        unsigned i;
        bool found_last;
#ifdef HAVE_GCRYPT
        uint64_t last_tag = 0;
#endif
        assert(f);

        if (key) {
#ifdef HAVE_GCRYPT
                r = journal_file_parse_verification_key(f, key);
                if (r < 0) {
                        log_error("Failed to parse seed.");
                        return r;
                }
#else
                return -ENOTSUP;
#endif
        } else if (f->seal)
                return -ENOKEY;

        data_fd = mkostemp(data_path, O_CLOEXEC);
        if (data_fd < 0) {
                log_error("Failed to create data file: %m");
                r = -errno;
                goto fail;
        }
        unlink(data_path);

        entry_fd = mkostemp(entry_path, O_CLOEXEC);
        if (entry_fd < 0) {
                log_error("Failed to create entry file: %m");
                r = -errno;
                goto fail;
        }
        unlink(entry_path);

        entry_array_fd = mkostemp(entry_array_path, O_CLOEXEC);
        if (entry_array_fd < 0) {
                log_error("Failed to create entry array file: %m");
                r = -errno;
                goto fail;
        }
        unlink(entry_array_path);

#ifdef HAVE_GCRYPT
        if ((le32toh(f->header->compatible_flags) & ~HEADER_COMPATIBLE_SEALED) != 0)
#else
        if (f->header->compatible_flags != 0)
#endif
        {
                log_error("Cannot verify file with unknown extensions.");
                r = -ENOTSUP;
                goto fail;
        }

        for (i = 0; i < sizeof(f->header->reserved); i++)
                if (f->header->reserved[i] != 0) {
                        log_error("Reserved field in non-zero.");
                        r = -EBADMSG;
                        goto fail;
                }

        /* First iteration: we go through all objects, verify the
         * superficial structure, headers, hashes. */

        p = le64toh(f->header->header_size);
        while (p != 0) {
                if (show_progress)
                        draw_progress(0x7FFF * p / le64toh(f->header->tail_object_offset), &last_usec);

                r = journal_file_move_to_object(f, -1, p, &o);
                if (r < 0) {
                        log_error("Invalid object at "OFSfmt, p);
                        goto fail;
                }

                if (p > le64toh(f->header->tail_object_offset)) {
                        log_error("Invalid tail object pointer");
                        r = -EBADMSG;
                        goto fail;
                }

                if (p == le64toh(f->header->tail_object_offset))
                        found_last = true;

                n_objects ++;

                r = journal_file_object_verify(f, p, o);
                if (r < 0) {
                        log_error("Invalid object contents at "OFSfmt": %s", p, strerror(-r));
                        goto fail;
                }

                if ((o->object.flags & OBJECT_COMPRESSED) && !JOURNAL_HEADER_COMPRESSED(f->header)) {
                        log_error("Compressed object in file without compression at "OFSfmt, p);
                        r = -EBADMSG;
                        goto fail;
                }

                switch (o->object.type) {

                case OBJECT_DATA:
                        r = write_uint64(data_fd, p);
                        if (r < 0)
                                goto fail;

                        n_data++;
                        break;

                case OBJECT_FIELD:
                        n_fields++;
                        break;

                case OBJECT_ENTRY:
                        if (JOURNAL_HEADER_SEALED(f->header) && n_tags <= 0) {
                                log_error("First entry before first tag at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        r = write_uint64(entry_fd, p);
                        if (r < 0)
                                goto fail;

                        if (le64toh(o->entry.realtime) < last_tag_realtime) {
                                log_error("Older entry after newer tag at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (!entry_seqnum_set &&
                            le64toh(o->entry.seqnum) != le64toh(f->header->head_entry_seqnum)) {
                                log_error("Head entry sequence number incorrect at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (entry_seqnum_set &&
                            entry_seqnum >= le64toh(o->entry.seqnum)) {
                                log_error("Entry sequence number out of synchronization at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        entry_seqnum = le64toh(o->entry.seqnum);
                        entry_seqnum_set = true;

                        if (entry_monotonic_set &&
                            sd_id128_equal(entry_boot_id, o->entry.boot_id) &&
                            entry_monotonic > le64toh(o->entry.monotonic)) {
                                log_error("Entry timestamp out of synchronization at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        entry_monotonic = le64toh(o->entry.monotonic);
                        entry_boot_id = o->entry.boot_id;
                        entry_monotonic_set = true;

                        if (!entry_realtime_set &&
                            le64toh(o->entry.realtime) != le64toh(f->header->head_entry_realtime)) {
                                log_error("Head entry realtime timestamp incorrect");
                                r = -EBADMSG;
                                goto fail;
                        }

                        entry_realtime = le64toh(o->entry.realtime);
                        entry_realtime_set = true;

                        n_entries ++;
                        break;

                case OBJECT_DATA_HASH_TABLE:
                        if (n_data_hash_tables > 1) {
                                log_error("More than one data hash table at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (le64toh(f->header->data_hash_table_offset) != p + offsetof(HashTableObject, items) ||
                            le64toh(f->header->data_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
                                log_error("Header fields for data hash table invalid");
                                r = -EBADMSG;
                                goto fail;
                        }

                        n_data_hash_tables++;
                        break;

                case OBJECT_FIELD_HASH_TABLE:
                        if (n_field_hash_tables > 1) {
                                log_error("More than one field hash table at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (le64toh(f->header->field_hash_table_offset) != p + offsetof(HashTableObject, items) ||
                            le64toh(f->header->field_hash_table_size) != le64toh(o->object.size) - offsetof(HashTableObject, items)) {
                                log_error("Header fields for field hash table invalid");
                                r = -EBADMSG;
                                goto fail;
                        }

                        n_field_hash_tables++;
                        break;

                case OBJECT_ENTRY_ARRAY:
                        r = write_uint64(entry_array_fd, p);
                        if (r < 0)
                                goto fail;

                        if (p == le64toh(f->header->entry_array_offset)) {
                                if (found_main_entry_array) {
                                        log_error("More than one main entry array at "OFSfmt, p);
                                        r = -EBADMSG;
                                        goto fail;
                                }

                                found_main_entry_array = true;
                        }

                        n_entry_arrays++;
                        break;

                case OBJECT_TAG:
                        if (!JOURNAL_HEADER_SEALED(f->header)) {
                                log_error("Tag object in file without sealing at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (le64toh(o->tag.seqnum) != n_tags + 1) {
                                log_error("Tag sequence number out of synchronization at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

                        if (le64toh(o->tag.epoch) < last_epoch) {
                                log_error("Epoch sequence out of synchronization at "OFSfmt, p);
                                r = -EBADMSG;
                                goto fail;
                        }

#ifdef HAVE_GCRYPT
                        if (f->seal) {
                                uint64_t q, rt;

                                log_debug("Checking tag %"PRIu64"...", le64toh(o->tag.seqnum));

                                rt = f->fss_start_usec + o->tag.epoch * f->fss_interval_usec;
                                if (entry_realtime_set && entry_realtime >= rt + f->fss_interval_usec) {
                                        log_error("Tag/entry realtime timestamp out of synchronization at "OFSfmt, p);
                                        r = -EBADMSG;
                                        goto fail;
                                }

                                /* OK, now we know the epoch. So let's now set
                                 * it, and calculate the HMAC for everything
                                 * since the last tag. */
                                r = journal_file_fsprg_seek(f, le64toh(o->tag.epoch));
                                if (r < 0)
                                        goto fail;

                                r = journal_file_hmac_start(f);
                                if (r < 0)
                                        goto fail;

                                if (last_tag == 0) {
                                        r = journal_file_hmac_put_header(f);
                                        if (r < 0)
                                                goto fail;

                                        q = le64toh(f->header->header_size);
                                } else
                                        q = last_tag;

                                while (q <= p) {
                                        r = journal_file_move_to_object(f, -1, q, &o);
                                        if (r < 0)
                                                goto fail;

                                        r = journal_file_hmac_put_object(f, -1, o, q);
                                        if (r < 0)
                                                goto fail;

                                        q = q + ALIGN64(le64toh(o->object.size));
                                }

                                /* Position might have changed, let's reposition things */
                                r = journal_file_move_to_object(f, -1, p, &o);
                                if (r < 0)
                                        goto fail;

                                if (memcmp(o->tag.tag, gcry_md_read(f->hmac, 0), TAG_LENGTH) != 0) {
                                        log_error("Tag failed verification at "OFSfmt, p);
                                        r = -EBADMSG;
                                        goto fail;
                                }

                                f->hmac_running = false;
                                last_tag_realtime = rt;
                                last_sealed_realtime = entry_realtime;
                        }

                        last_tag = p + ALIGN64(le64toh(o->object.size));
#endif

                        last_epoch = le64toh(o->tag.epoch);

                        n_tags ++;
                        break;

                default:
                        n_weird ++;
                }

                if (p == le64toh(f->header->tail_object_offset))
                        p = 0;
                else
                        p = p + ALIGN64(le64toh(o->object.size));
        }

        if (!found_last) {
                log_error("Tail object pointer dead");
                r = -EBADMSG;
                goto fail;
        }

        if (n_objects != le64toh(f->header->n_objects)) {
                log_error("Object number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (n_entries != le64toh(f->header->n_entries)) {
                log_error("Entry number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (JOURNAL_HEADER_CONTAINS(f->header, n_data) &&
            n_data != le64toh(f->header->n_data)) {
                log_error("Data number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (JOURNAL_HEADER_CONTAINS(f->header, n_fields) &&
            n_fields != le64toh(f->header->n_fields)) {
                log_error("Field number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (JOURNAL_HEADER_CONTAINS(f->header, n_tags) &&
            n_tags != le64toh(f->header->n_tags)) {
                log_error("Tag number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (JOURNAL_HEADER_CONTAINS(f->header, n_entry_arrays) &&
            n_entry_arrays != le64toh(f->header->n_entry_arrays)) {
                log_error("Entry array number mismatch");
                r = -EBADMSG;
                goto fail;
        }

        if (n_data_hash_tables != 1) {
                log_error("Missing data hash table");
                r = -EBADMSG;
                goto fail;
        }

        if (n_field_hash_tables != 1) {
                log_error("Missing field hash table");
                r = -EBADMSG;
                goto fail;
        }

        if (!found_main_entry_array) {
                log_error("Missing entry array");
                r = -EBADMSG;
                goto fail;
        }

        if (entry_seqnum_set &&
            entry_seqnum != le64toh(f->header->tail_entry_seqnum)) {
                log_error("Invalid tail seqnum");
                r = -EBADMSG;
                goto fail;
        }

        if (entry_monotonic_set &&
            (!sd_id128_equal(entry_boot_id, f->header->boot_id) ||
             entry_monotonic != le64toh(f->header->tail_entry_monotonic))) {
                log_error("Invalid tail monotonic timestamp");
                r = -EBADMSG;
                goto fail;
        }

        if (entry_realtime_set && entry_realtime != le64toh(f->header->tail_entry_realtime)) {
                log_error("Invalid tail realtime timestamp");
                r = -EBADMSG;
                goto fail;
        }

        /* Second iteration: we follow all objects referenced from the
         * two entry points: the object hash table and the entry
         * array. We also check that everything referenced (directly
         * or indirectly) in the data hash table also exists in the
         * entry array, and vice versa. Note that we do not care for
         * unreferenced objects. We only care that everything that is
         * referenced is consistent. */

        r = verify_entry_array(f,
                               data_fd, n_data,
                               entry_fd, n_entries,
                               entry_array_fd, n_entry_arrays,
                               &last_usec,
                               show_progress);
        if (r < 0)
                goto fail;

        r = verify_hash_table(f,
                              data_fd, n_data,
                              entry_fd, n_entries,
                              entry_array_fd, n_entry_arrays,
                              &last_usec,
                              show_progress);
        if (r < 0)
                goto fail;

        if (show_progress)
                flush_progress();

        mmap_cache_close_fd(f->mmap, data_fd);
        mmap_cache_close_fd(f->mmap, entry_fd);
        mmap_cache_close_fd(f->mmap, entry_array_fd);

        close_nointr_nofail(data_fd);
        close_nointr_nofail(entry_fd);
        close_nointr_nofail(entry_array_fd);

        if (first_contained)
                *first_contained = le64toh(f->header->head_entry_realtime);
        if (last_validated)
                *last_validated = last_sealed_realtime;
        if (last_contained)
                *last_contained = le64toh(f->header->tail_entry_realtime);

        return 0;

fail:
        if (show_progress)
                flush_progress();

        log_error("File corruption detected at %s:"OFSfmt" (of %llu bytes, %"PRIu64"%%).",
                  f->path,
                  p,
                  (unsigned long long) f->last_stat.st_size,
                  100 * p / f->last_stat.st_size);

        if (data_fd >= 0) {
                mmap_cache_close_fd(f->mmap, data_fd);
                close_nointr_nofail(data_fd);
        }

        if (entry_fd >= 0) {
                mmap_cache_close_fd(f->mmap, entry_fd);
                close_nointr_nofail(entry_fd);
        }

        if (entry_array_fd >= 0) {
                mmap_cache_close_fd(f->mmap, entry_array_fd);
                close_nointr_nofail(entry_array_fd);
        }

        return r;
}
Ejemplo n.º 22
0
int decompress_stream_lz4(int fdf, int fdt, off_t max_bytes) {

#ifdef HAVE_LZ4
        _cleanup_free_ char *buf = NULL, *out = NULL;
        size_t buf_size = 0;
        LZ4_streamDecode_t lz4_data = {};
        le32_t header;
        size_t total_in = sizeof(header), total_out = 0;

        assert(fdf >= 0);
        assert(fdt >= 0);

        out = malloc(4*LZ4_BUFSIZE);
        if (!out)
                return log_oom();

        for (;;) {
                ssize_t m;
                int r;

                r = loop_read_exact(fdf, &header, sizeof(header), false);
                if (r < 0)
                        return r;

                m = le32toh(header);
                if (m == 0)
                        break;

                /* We refuse to use a bigger decompression buffer than
                 * the one used for compression by 4 times. This means
                 * that compression buffer size can be enlarged 4
                 * times. This can be changed, but old binaries might
                 * not accept buffers compressed by newer binaries then.
                 */
                if (m > LZ4_COMPRESSBOUND(LZ4_BUFSIZE * 4)) {
                        log_error("Compressed stream block too big: %zd bytes", m);
                        return -EBADMSG;
                }

                total_in += sizeof(header) + m;

                if (!GREEDY_REALLOC(buf, buf_size, m))
                        return log_oom();

                r = loop_read_exact(fdf, buf, m, false);
                if (r < 0)
                        return r;

                r = LZ4_decompress_safe_continue(&lz4_data, buf, out, m, 4*LZ4_BUFSIZE);
                if (r <= 0)
                        log_error("LZ4 decompression failed.");

                total_out += r;

                if (max_bytes != -1 && total_out > (size_t) max_bytes) {
                        log_debug("Decompressed stream longer than %zd bytes", max_bytes);
                        return -EFBIG;
                }

                r = loop_write(fdt, out, r, false);
                if (r < 0)
                        return r;
        }

        log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
                  total_in, total_out,
                  (double) total_out / total_in * 100);

        return 0;
#else
        log_error("Cannot decompress file. Compiled without LZ4 support.");
        return -EPROTONOSUPPORT;
#endif
}
Ejemplo n.º 23
0
int main(int argc,char **argv) {
	struct libmsfat_disk_locations_and_info locinfo;
	struct libmsfat_file_io_ctx_t *fioctx = NULL;
	struct libmsfat_context_t *msfatctx = NULL;
	struct libmsfat_lfn_assembly_t lfn_name;
	struct libmsfat_dirent_t dirent;
	uint32_t first_lba=0,size_lba=0;
	const char *s_partition = NULL;
	const char *s_cluster = NULL;
	libmsfat_cluster_t cluster=0;
	const char *s_image = NULL;
	char tmp[512];
	int i,fd;

	for (i=1;i < argc;) {
		const char *a = argv[i++];

		if (*a == '-') {
			do { a++; } while (*a == '-');

			if (!strcmp(a,"image")) {
				s_image = argv[i++];
			}
			else if (!strcmp(a,"partition")) {
				s_partition = argv[i++];
			}
			else if (!strcmp(a,"cluster")) {
				s_cluster = argv[i++];
			}
			else {
				fprintf(stderr,"Unknown switch '%s'\n",a);
				return 1;
			}
		}
		else {
			fprintf(stderr,"Unexpected arg '%s'\n",a);
			return 1;
		}
	}

	if (libmsfat_sanity_check() != 0) {
		fprintf(stderr,"libmsfat sanity check fail\n");
		return 1;
	}

	if (s_image == NULL) {
		fprintf(stderr,"fatinfo --image <image> ...\n");
		fprintf(stderr,"\n");
		fprintf(stderr,"--partition <n>          Hard disk image, use partition N from the MBR\n");
		fprintf(stderr,"--cluster <n>            Which cluster to start from (if not root dir)\n");
		return 1;
	}
	if (s_cluster != NULL)
		cluster = (libmsfat_cluster_t)strtoul(s_cluster,NULL,0);
	else
		cluster = 0;

	fd = open(s_image,O_RDONLY|O_BINARY);
	if (fd < 0) {
		fprintf(stderr,"Unable to open disk image, %s\n",strerror(errno));
		return 1;
	}
	{
		/* make sure it's a file */
		_polyfill_struct_stat st;
		if (_polyfill_fstat(fd,&st) || (!S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode))) {
			fprintf(stderr,"Image is not a file\n");
			return 1;
		}
	}

	if (s_partition != NULL) {
		struct libpartmbr_context_t *ctx = NULL;
		int index = atoi(s_partition);
		int dfd = -1;

		if (index < 0) {
			fprintf(stderr,"Invalid index\n");
			return 1;
		}

		ctx = libpartmbr_context_create();
		if (ctx == NULL) {
			fprintf(stderr,"Cannot allocate libpartmbr context\n");
			return 1;
		}

		/* good! hand it off to the context. use dup() because it takes ownership */
		dfd = dup(fd);
		if (libpartmbr_context_assign_fd(ctx,dfd)) {
			fprintf(stderr,"libpartmbr did not accept file descriptor %d\n",fd);
			close(dfd); // dispose of it
			return 1;
		}
		dfd = -1;
		ctx->geometry.cylinders = 16384;
		ctx->geometry.sectors = 63;
		ctx->geometry.heads = 255;

		/* load the partition table! */
		if (libpartmbr_context_read_partition_table(ctx)) {
			fprintf(stderr,"Failed to read partition table\n");
			return 1;
		}

		/* index */
		if ((size_t)index >= ctx->list_count) {
			fprintf(stderr,"Index too large\n");
			return 1;
		}

		/* valid? */
		struct libpartmbr_context_entry_t *ent = &ctx->list[(size_t)index];

		if (ent->is_empty) {
			fprintf(stderr,"You chose an empty MBR partition\n");
			return 1;
		}

		/* show */
		printf("Chosen partition:\n");
		printf("    Type: 0x%02x %s\n",
			(unsigned int)ent->entry.partition_type,
			libpartmbr_partition_type_to_str(ent->entry.partition_type));

		if (!(ent->entry.partition_type == LIBPARTMBR_TYPE_FAT12_32MB ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16_32MB ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16B_8GB ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT32_CHS ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT32_LBA ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16B_LBA ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT12_32MB_HIDDEN ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16_32MB_HIDDEN ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16B_8GB_HIDDEN ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT32_CHS_HIDDEN ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT32_LBA_HIDDEN ||
			ent->entry.partition_type == LIBPARTMBR_TYPE_FAT16B_LBA_HIDDEN)) {
			fprintf(stderr,"MBR type does not suggest a FAT filesystem\n");
			return 1;
		}
		first_lba = ent->entry.first_lba_sector;
		size_lba = ent->entry.number_lba_sectors;

		/* done */
		ctx = libpartmbr_context_destroy(ctx);
	}
	else {
		lseek_off_t x;

		first_lba = 0;

		x = _polyfill_lseek(fd,0,SEEK_END);
		if (x < (lseek_off_t)0) x = 0;
		x /= (lseek_off_t)512UL;
		if (x > (lseek_off_t)0xFFFFFFFFUL) x = (lseek_off_t)0xFFFFFFFFUL;
		size_lba = (uint32_t)x;
		_polyfill_lseek(fd,0,SEEK_SET);
	}

	printf("Reading from disk sectors %lu-%lu (%lu sectors)\n",
		(unsigned long)first_lba,
		(unsigned long)first_lba+(unsigned long)size_lba-(unsigned long)1UL,
		(unsigned long)size_lba);

	{
		lseek_off_t x = (lseek_off_t)first_lba * (lseek_off_t)512UL;

		if (_polyfill_lseek(fd,x,SEEK_SET) != x || read(fd,sectorbuf,512) != 512) {
			fprintf(stderr,"Unable to read boot sector\n");
			return 1;
		}
	}

	{
		const char *err_str = NULL;

		if (!libmsfat_boot_sector_is_valid(sectorbuf,&err_str)) {
			printf("Boot sector is not valid: reason=%s\n",err_str);
			return 1;
		}
	}

	{
		struct libmsfat_bootsector *p_bs = (struct libmsfat_bootsector*)sectorbuf;
		int dfd;

		if (libmsfat_bs_compute_disk_locations(&locinfo,p_bs)) {
			printf("Unable to locate disk locations.\n");
			return 1;
		}

		printf("Disk location and FAT info:\n");
		printf("    FAT format:        FAT%u\n",
			locinfo.FAT_size);
		printf("    FAT tables:        %u\n",
			locinfo.FAT_tables);
		printf("    FAT table size:    %lu sectors\n",
			(unsigned long)locinfo.FAT_table_size);
		printf("    FAT offset:        %lu sectors\n",
			(unsigned long)locinfo.FAT_offset);
		printf("    Root directory:    %lu sectors\n",
			(unsigned long)locinfo.RootDirectory_offset);
		printf("    Root dir size:     %lu sectors\n",
			(unsigned long)locinfo.RootDirectory_size);
		printf("    Data offset:       %lu sectors\n",
			(unsigned long)locinfo.Data_offset);
		printf("    Data size:         %lu sectors\n",
			(unsigned long)locinfo.Data_size);
		printf("    Sectors/cluster:   %u\n",
			(unsigned int)locinfo.Sectors_Per_Cluster);
		printf("    Bytes per sector:  %u\n",
			(unsigned int)locinfo.BytesPerSector);
		printf("    Total clusters:    %lu\n",
			(unsigned long)locinfo.Total_clusters);
		printf("    Total data clusts: %lu\n",
			(unsigned long)locinfo.Total_data_clusters);
		printf("    Max clusters psbl: %lu\n",
			(unsigned long)locinfo.Max_possible_clusters);
		printf("    Max data clus psbl:%lu\n",
			(unsigned long)locinfo.Max_possible_data_clusters);
		printf("    Total sectors:     %lu sectors\n",
			(unsigned long)locinfo.TotalSectors);
		if (locinfo.FAT_size >= 32) {
			printf("    FAT32 FSInfo:      %lu sector\n",
				(unsigned long)locinfo.fat32.BPB_FSInfo);
			printf("    Root dir cluster:  %lu\n",
				(unsigned long)locinfo.fat32.RootDirectory_cluster);
		}

		msfatctx = libmsfat_context_create();
		if (msfatctx == NULL) {
			fprintf(stderr,"Failed to create msfat context\n");
			return -1;
		}
		dfd = dup(fd);
		if (libmsfat_context_assign_fd(msfatctx,dfd)) {
			fprintf(stderr,"Failed to assign file descriptor to msfat\n");
			close(dfd);
			return -1;
		}
		dfd = -1; /* takes ownership, drop it */

		msfatctx->partition_byte_offset = (uint64_t)first_lba * (uint64_t)512UL;
		if (libmsfat_context_set_fat_info(msfatctx,&locinfo)) {
			fprintf(stderr,"msfat library rejected disk location info\n");
			return -1;
		}
	}

	/* FAT32 always starts from a cluster.
	 * FAT12/FAT16 have a dedicated area for the root directory */
	if (locinfo.FAT_size == 32) {
		if (s_cluster == NULL)
			cluster = locinfo.fat32.RootDirectory_cluster;
	}

	if (cluster >= locinfo.Max_possible_clusters)
		fprintf(stderr,"WARNING: cluster %lu >= max possible clusters %lu\n",
			(unsigned long)cluster,
			(unsigned long)locinfo.Max_possible_clusters);
	else if (cluster >= locinfo.Total_clusters)
		fprintf(stderr,"WARNING: cluster %lu >= total clusters %lu\n",
			(unsigned long)cluster,
			(unsigned long)locinfo.Total_clusters);
	else if ((s_cluster != NULL || cluster != (libmsfat_cluster_t)0UL) && cluster < (libmsfat_cluster_t)2UL)
		fprintf(stderr,"WARNING: cluster %lu is known not to have corresponding data storage on disk\n",
			(unsigned long)cluster);

	if (s_cluster != NULL || cluster != (libmsfat_cluster_t)0UL)
		printf("Reading directory starting from cluster %lu\n",
			(unsigned long)cluster);
	else
		printf("Reading directory from FAT12/FAT16 root directory area\n");

	/* sanity check */
	if (locinfo.FAT_size >= 32) {
	}
	else if (locinfo.FAT_size < 32 && (locinfo.RootDirectory_offset == (uint32_t)0UL || locinfo.RootDirectory_size == (uint32_t)0UL)) {
		fprintf(stderr,"ERROR: FAT12/FAT16 root directory area does not exist\n");
		return 1;
	}

	fioctx = libmsfat_file_io_ctx_create();
	if (fioctx == NULL) {
		fprintf(stderr,"Cannot alloc FIO ctx\n");
		return 1;
	}

	if (s_cluster != NULL || cluster != (libmsfat_cluster_t)0UL) {
		if (libmsfat_file_io_ctx_assign_cluster_chain(fioctx,msfatctx,cluster)) {
			fprintf(stderr,"Cannot assign cluster\n");
			return 1;
		}
		fioctx->is_root_dir = 1;
		fioctx->is_directory = 1;
	}
	else {
		if (libmsfat_file_io_ctx_assign_root_directory(fioctx,msfatctx)) {
			fprintf(stderr,"Cannot assign root dir\n");
			return 1;
		}
	}

	if (libmsfat_file_io_ctx_rewinddir(fioctx,msfatctx,&lfn_name)) {
		fprintf(stderr,"Cannot rewinddir\n");
		return 1;
	}

	while (libmsfat_file_io_ctx_readdir(fioctx,msfatctx,&lfn_name,&dirent) == 0) {
		if (dirent.a.n.DIR_Attr & libmsfat_DIR_ATTR_VOLUME_ID) {
			libmsfat_dirent_volume_label_to_str(tmp,sizeof(tmp),&dirent);
			printf("    <VOL>  '%s'",tmp);
		}
		else {
			libmsfat_dirent_filename_to_str(tmp,sizeof(tmp),&dirent);
			if (dirent.a.n.DIR_Attr & libmsfat_DIR_ATTR_DIRECTORY)
				printf("    <DIR>  '%s'",tmp);
			else
				printf("    <FIL>  '%s'",tmp);
		}
		printf("\n");

		if (lfn_name.name_avail) {
#if defined(_WIN32) && defined(_MSC_VER) /* Windows + Microsoft C++ */
			// use widechar printf in Windows to show the name properly
			if (isatty(1/*STDOUT*/)) {
				if (sizeof(wchar_t) == 2) { /* Microsoft C runtime sets wchar_t == uint16_t aka WORD */
					size_t wl;

					libmsfat_dirent_lfn_to_str_utf16le(tmp,sizeof(tmp),&lfn_name);
					wl = wcslen((const wchar_t*)tmp);

					printf("        Long name:          '");
					fflush(stdout);
					{
						DWORD written = 0;
						WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), (const void*)tmp, (DWORD)wl, &written, NULL);
					}
					printf("'\n");
				}
			}
			else {
				libmsfat_dirent_lfn_to_str_utf8(tmp,sizeof(tmp),&lfn_name);
				printf("        Long name:          '%s'\n",tmp);
			}
#else
			// Linux terminals nowaways use UTF-8 encoding
			libmsfat_dirent_lfn_to_str_utf8(tmp,sizeof(tmp),&lfn_name);
			printf("        Long name:          '%s'\n",tmp);
#endif
		}

		printf("        File size:          %lu bytes\n",
			(unsigned long)le32toh(dirent.a.n.DIR_FileSize));
		printf("        Starting cluster:   %lu\n",
			(unsigned long)libmsfat_dirent_get_starting_cluster(msfatctx,&dirent));
	}

	fioctx = libmsfat_file_io_ctx_destroy(fioctx);
	msfatctx = libmsfat_context_destroy(msfatctx);
	close(fd);
	fd = -1;
	return 0;
}
Ejemplo n.º 24
0
void
terasic_mtl_reg_blend_get(struct terasic_mtl_softc *sc, uint32_t *blendp)
{

	*blendp = le32toh(bus_read_4(sc->mtl_reg_res, TERASIC_MTL_OFF_BLEND));
}
Ejemplo n.º 25
0
static int
iir_pci_attach(device_t dev)
{
    struct gdt_softc    *gdt;
    struct resource     *io = NULL, *irq = NULL;
    int                 retries, rid, error = 0;
    void                *ih;
    u_int8_t            protocol;

    /* map DPMEM */
    rid = PCI_DPMEM;
    io = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, RF_ACTIVE);
    if (io == NULL) {
        device_printf(dev, "can't allocate register resources\n");
        error = ENOMEM;
        goto err;
    }

    /* get IRQ */
    rid = 0;
    irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
                                 RF_ACTIVE | RF_SHAREABLE);
    if (irq == NULL) {
        device_printf(dev, "can't find IRQ value\n");
        error = ENOMEM;
        goto err;
    }

    gdt = device_get_softc(dev);
    gdt->sc_devnode = dev;
    gdt->sc_init_level = 0;
    gdt->sc_dpmemt = rman_get_bustag(io);
    gdt->sc_dpmemh = rman_get_bushandle(io);
    gdt->sc_dpmembase = rman_get_start(io);
    gdt->sc_hanum = device_get_unit(dev);
    gdt->sc_bus = pci_get_bus(dev);
    gdt->sc_slot = pci_get_slot(dev);
    gdt->sc_vendor = pci_get_vendor(dev);
    gdt->sc_device = pci_get_device(dev);
    gdt->sc_subdevice = pci_get_subdevice(dev);
    gdt->sc_class = GDT_MPR;
    /* no FC ctr.
        if (gdt->sc_device >= GDT_PCI_PRODUCT_FC)
            gdt->sc_class |= GDT_FC;
    */

    /* initialize RP controller */
    /* check and reset interface area */
    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC,
                      htole32(GDT_MPR_MAGIC));
    if (bus_space_read_4(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC) !=
            htole32(GDT_MPR_MAGIC)) {
        printf("cannot access DPMEM at 0x%jx (shadowed?)\n",
               (uintmax_t)gdt->sc_dpmembase);
        error = ENXIO;
        goto err;
    }
    bus_space_set_region_4(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_I960_SZ, htole32(0),
                           GDT_MPR_SZ >> 2);

    /* Disable everything */
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_EDOOR_EN,
                      bus_space_read_1(gdt->sc_dpmemt, gdt->sc_dpmemh,
                                       GDT_EDOOR_EN) | 4);
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_EDOOR, 0xff);
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_STATUS,
                      0);
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_CMD_INDEX,
                      0);

    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_INFO,
                      htole32(gdt->sc_dpmembase));
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_CMD_INDX,
                      0xff);
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_LDOOR, 1);

    DELAY(20);
    retries = GDT_RETRIES;
    while (bus_space_read_1(gdt->sc_dpmemt, gdt->sc_dpmemh,
                            GDT_MPR_IC + GDT_S_STATUS) != 0xff) {
        if (--retries == 0) {
            printf("DEINIT failed\n");
            error = ENXIO;
            goto err;
        }
        DELAY(1);
    }

    protocol = (uint8_t)le32toh(bus_space_read_4(gdt->sc_dpmemt, gdt->sc_dpmemh,
                                GDT_MPR_IC + GDT_S_INFO));
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_STATUS,
                      0);
    if (protocol != GDT_PROTOCOL_VERSION) {
        printf("unsupported protocol %d\n", protocol);
        error = ENXIO;
        goto err;
    }

    /* special commnd to controller BIOS */
    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_INFO,
                      htole32(0));
    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh,
                      GDT_MPR_IC + GDT_S_INFO + sizeof (u_int32_t), htole32(0));
    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh,
                      GDT_MPR_IC + GDT_S_INFO + 2 * sizeof (u_int32_t),
                      htole32(1));
    bus_space_write_4(gdt->sc_dpmemt, gdt->sc_dpmemh,
                      GDT_MPR_IC + GDT_S_INFO + 3 * sizeof (u_int32_t),
                      htole32(0));
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_CMD_INDX,
                      0xfe);
    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_LDOOR, 1);

    DELAY(20);
    retries = GDT_RETRIES;
    while (bus_space_read_1(gdt->sc_dpmemt, gdt->sc_dpmemh,
                            GDT_MPR_IC + GDT_S_STATUS) != 0xfe) {
        if (--retries == 0) {
            printf("initialization error\n");
            error = ENXIO;
            goto err;
        }
        DELAY(1);
    }

    bus_space_write_1(gdt->sc_dpmemt, gdt->sc_dpmemh, GDT_MPR_IC + GDT_S_STATUS,
                      0);

    gdt->sc_ic_all_size = GDT_MPR_SZ;

    gdt->sc_copy_cmd = gdt_mpr_copy_cmd;
    gdt->sc_get_status = gdt_mpr_get_status;
    gdt->sc_intr = gdt_mpr_intr;
    gdt->sc_release_event = gdt_mpr_release_event;
    gdt->sc_set_sema0 = gdt_mpr_set_sema0;
    gdt->sc_test_busy = gdt_mpr_test_busy;

    /* Allocate a dmatag representing the capabilities of this attachment */
    /* XXX Should be a child of the PCI bus dma tag */
    if (bus_dma_tag_create(/*parent*/NULL, /*alignemnt*/1, /*boundary*/0,
                                     /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
                                     /*highaddr*/BUS_SPACE_MAXADDR,
                                     /*filter*/NULL, /*filterarg*/NULL,
                                     /*maxsize*/BUS_SPACE_MAXSIZE_32BIT,
                                     /*nsegments*/GDT_MAXSG,
                                     /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
                                     /*flags*/0, /*lockfunc*/busdma_lock_mutex,
                                     /*lockarg*/&Giant, &gdt->sc_parent_dmat) != 0) {
        error = ENXIO;
        goto err;
    }
    gdt->sc_init_level++;

    if (iir_init(gdt) != 0) {
        iir_free(gdt);
        error = ENXIO;
        goto err;
    }

    /* Register with the XPT */
    iir_attach(gdt);

    /* associate interrupt handler */
    if (bus_setup_intr( dev, irq, INTR_TYPE_CAM,
                        NULL, iir_intr, gdt, &ih )) {
        device_printf(dev, "Unable to register interrupt handler\n");
        error = ENXIO;
        goto err;
    }

    gdt_pci_enable_intr(gdt);
    return (0);

err:
    if (irq)
        bus_release_resource( dev, SYS_RES_IRQ, 0, irq );
    /*
        if (io)
            bus_release_resource( dev, SYS_RES_MEMORY, rid, io );
    */
    return (error);
}
Ejemplo n.º 26
0
int rootOps(void* userData, UInt32 sector, void* buf, UInt8 op) {

    FILE* root = userData;
    int i;

    switch(op) {
    case BLK_OP_SIZE:

        if(sector == 0) {	//num blocks

            if(root) {

                i = fseeko(root, 0, SEEK_END);
                if(i) return false;

                *(unsigned long*)buf = (off_t)ftello(root) / (off_t)BLK_DEV_BLK_SZ;
            }
            else {

                *(unsigned long*)buf = 0;
            }
        }
        else if(sector == 1) {	//block size

            *(unsigned long*)buf = BLK_DEV_BLK_SZ;
        }
        else return 0;
        return 1;

    case BLK_OP_READ:

        i = fseeko(root, (off_t)sector * (off_t)BLK_DEV_BLK_SZ, SEEK_SET);
        if(i) return false;
#if BYTE_ORDER == LITTLE_ENDIAN
        return fread(buf, 1, BLK_DEV_BLK_SZ, root) == BLK_DEV_BLK_SZ;
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
        {
            UInt32 *ptr;
            ptr = malloc(BLK_DEV_BLK_SZ);
            if (ptr == NULL) {
                return (false);
            }
            if (fread(ptr, 1, BLK_DEV_BLK_SZ, root) != BLK_DEV_BLK_SZ) {
                free(ptr);
                return (false);
            }
            for (i = 0 ; i < (int)(BLK_DEV_BLK_SZ / sizeof(ptr[0])) ; i++) {
                ((UInt32 *)buf)[i] = le32toh(ptr[i]);
            }
            free(ptr);
            return (true);
        }
#endif /* BYTE_ORDER == BIG_ENDIAN */

    case BLK_OP_WRITE:

        i = fseeko(root, (off_t)sector * (off_t)BLK_DEV_BLK_SZ, SEEK_SET);
        if(i) return false;
#if BYTE_ORDER == LITTLE_ENDIAN
        return fwrite(buf, 1, BLK_DEV_BLK_SZ, root) == BLK_DEV_BLK_SZ;
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
        {
            UInt32 *ptr;
            ptr = malloc(BLK_DEV_BLK_SZ);
            if (ptr == NULL) {
                return (false);
            }
            for (i = 0 ; i < (int)(BLK_DEV_BLK_SZ / sizeof(ptr[0])) ; i++) {
                ptr[i] = htole32(((UInt32 *)buf)[i]);
            }
            if (fwrite(ptr, 1, BLK_DEV_BLK_SZ, root) != BLK_DEV_BLK_SZ) {
                free(ptr);
                return (false);
            }
            free(ptr);
            return (true);
        }
#endif /* BYTE_ORDER == BIG_ENDIAN */
    }
    return 0;
}
Ejemplo n.º 27
0
static int
scan_mbr(mbr_args_t *a, int (*actn)(mbr_args_t *, mbr_partition_t *, int, uint))
{
	mbr_partition_t ptns[MBR_PART_COUNT];
	mbr_partition_t *dp;
	struct mbr_sector *mbr;
	uint ext_base, this_ext, next_ext;
	int rval;
	int i;
	int j;
#ifdef COMPAT_386BSD_MBRPART
	int dp_386bsd = -1;
	int ap_386bsd = -1;
#endif

	ext_base = 0;
	this_ext = 0;
	for (;;) {
		if (read_sector(a, this_ext, 1)) {
			a->msg = "dos partition I/O error";
			return SCAN_ERROR;
		}

		/* Note: Magic number is little-endian. */
		mbr = (void *)a->bp->b_data;
		if (mbr->mbr_magic != htole16(MBR_MAGIC))
			return SCAN_CONTINUE;

		/* Copy data out of buffer so action can use bp */
		memcpy(ptns, &mbr->mbr_parts, sizeof ptns);

		/* Look for drivers and skip them */
		if (ext_base == 0 && ptns[0].mbrp_type == MBR_PTYPE_DM6_DDO) {
			/* We've found a DM6 DDO partition type (used by
			 * the Ontrack Disk Manager drivers).
			 *
			 * Ensure that there are no other partitions in the
			 * MBR and jump to the real partition table (stored
			 * in the first sector of the second track). */
			bool ok = true;

			for (i = 1; i < MBR_PART_COUNT; i++)
				if (ptns[i].mbrp_type != MBR_PTYPE_UNUSED)
					ok = false;

			if (ok) {
				this_ext = le32toh(a->lp->d_secpercyl /
				    a->lp->d_ntracks);
				continue;
			}
		}

		/* look for NetBSD partition */
		next_ext = 0;
		dp = ptns;
		j = 0;
		for (i = 0; i < MBR_PART_COUNT; i++, dp++) {
			if (dp->mbrp_type == MBR_PTYPE_UNUSED)
				continue;
			/* Check end of partition is inside disk limits */
			if ((uint64_t)ext_base + le32toh(dp->mbrp_start) +
			    le32toh(dp->mbrp_size) > a->lp->d_secperunit) {
				/* This mbr doesn't look good.... */
				a->msg = "mbr partition exceeds disk size";
				/* ...but don't report this as an error (yet) */
				return SCAN_CONTINUE;
			}
			a->found_mbr = 1;
			if (MBR_IS_EXTENDED(dp->mbrp_type)) {
				next_ext = le32toh(dp->mbrp_start);
				continue;
			}
#ifdef COMPAT_386BSD_MBRPART
			if (dp->mbrp_type == MBR_PTYPE_386BSD) {
				/*
				 * If more than one matches, take last,
				 * as NetBSD install tool does.
				 */
				if (this_ext == 0) {
					dp_386bsd = i;
					ap_386bsd = j;
				}
				continue;
			}
#endif
			rval = (*actn)(a, dp, j, this_ext);
			if (rval != SCAN_CONTINUE)
				return rval;
			j++;
		}
		if (next_ext == 0)
			break;
		if (ext_base == 0) {
			ext_base = next_ext;
			next_ext = 0;
		}
		next_ext += ext_base;
		if (next_ext <= this_ext)
			break;
		this_ext = next_ext;
	}
#ifdef COMPAT_386BSD_MBRPART
	if (this_ext == 0 && dp_386bsd != -1)
		return (*actn)(a, &ptns[dp_386bsd], ap_386bsd, 0);
#endif
	return SCAN_CONTINUE;
}
Ejemplo n.º 28
0
int getIntFromBuf(unsigned char* buf, int start) {
	uint32_t x = *(uint32_t*)(buf + start);
	return (int) le32toh(x);
}
Ejemplo n.º 29
0
static int
decode_tuple_bar(device_t cbdev, device_t child, int id,
    int len, uint8_t *tupledata, uint32_t start, uint32_t *off,
    struct tuple_callbacks *info, void *argp)
{
	struct cardbus_devinfo *dinfo = device_get_ivars(child);
	int type;
	uint8_t reg;
	uint32_t bar;

	if (len != 6) {
		device_printf(cbdev, "CIS BAR length not 6 (%d)\n", len);
		return (EINVAL);
	}

	reg = *tupledata;
	len = le32toh(*(uint32_t*)(tupledata + 2));
	if (reg & TPL_BAR_REG_AS)
		type = SYS_RES_IOPORT;
	else
		type = SYS_RES_MEMORY;

	bar = reg & TPL_BAR_REG_ASI_MASK;
	if (bar == 0) {
		device_printf(cbdev, "Invalid BAR type 0 in CIS\n");
		return (EINVAL);	/* XXX Return an error? */
	} else if (bar == 7) {
		/* XXX Should we try to map in Option ROMs? */
		return (0);
	}

	/* Convert from BAR type to BAR offset */
	bar = PCIR_BAR(bar - 1);

	if (type == SYS_RES_MEMORY) {
		if (reg & TPL_BAR_REG_PREFETCHABLE)
			dinfo->mprefetchable |= (1 << PCI_RID2BAR(bar));
		/*
		 * The PC Card spec says we're only supposed to honor this
		 * hint when the cardbus bridge is a child of pci0 (the main
		 * bus).  The PC Card spec seems to indicate that this should
		 * only be done on x86 based machines, which suggests that on
		 * non-x86 machines the addresses can be anywhere.  Since the
		 * hardware can do it on non-x86 machines, it should be able
		 * to do it on x86 machines too.  Therefore, we can and should
		 * ignore this hint.  Furthermore, the PC Card spec recommends
		 * always allocating memory above 1MB, contradicting the other
		 * part of the PC Card spec, it seems.  We make note of it,
		 * but otherwise don't use this information.
		 *
		 * Some Realtek cards have this set in their CIS, but fail
		 * to actually work when mapped this way, and experience
		 * has shown ignoring this big to be a wise choice.
		 *
		 * XXX We should cite chapter and verse for standard refs.
		 */
		if (reg & TPL_BAR_REG_BELOW1MB)
			dinfo->mbelow1mb |= (1 << PCI_RID2BAR(bar));
	}

	return (0);
}
Ejemplo n.º 30
0
int
reiserfs_lookup(struct vop_cachedlookup_args *ap)
{
	int error, retval;
	struct vnode *vdp         = ap->a_dvp;
	struct vnode **vpp        = ap->a_vpp;
	struct componentname *cnp = ap->a_cnp;

	int flags         = cnp->cn_flags;
	struct thread *td = cnp->cn_thread;
	struct cpu_key *saved_ino;

	struct vnode *vp;
	struct vnode *pdp;  /* Saved dp during symlink work */
	struct reiserfs_node *dp;
	struct reiserfs_dir_entry de;
	INITIALIZE_PATH(path_to_entry);

	char c = cnp->cn_nameptr[cnp->cn_namelen];
	cnp->cn_nameptr[cnp->cn_namelen] = '\0';
	reiserfs_log(LOG_DEBUG, "looking for `%s', %ld (%s)\n",
	    cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_pnbuf);
	cnp->cn_nameptr[cnp->cn_namelen] = c;

	vp = NULL;
	dp = VTOI(vdp);

	if (REISERFS_MAX_NAME(dp->i_reiserfs->s_blocksize) < cnp->cn_namelen)
		return (ENAMETOOLONG);

	reiserfs_log(LOG_DEBUG, "searching entry\n");
	de.de_gen_number_bit_string = 0;
	retval = reiserfs_find_entry(dp, cnp->cn_nameptr, cnp->cn_namelen,
	    &path_to_entry, &de);
	pathrelse(&path_to_entry);

	if (retval == NAME_FOUND) {
		reiserfs_log(LOG_DEBUG, "found\n");
	} else {
		reiserfs_log(LOG_DEBUG, "not found\n");
	}

	if (retval == NAME_FOUND) {
#if 0
		/* Hide the .reiserfs_priv directory */
		if (reiserfs_xattrs(dp->i_reiserfs) &&
		    !old_format_only(dp->i_reiserfs) &&
		    REISERFS_SB(dp->i_reiserfs)->priv_root &&
		    REISERFS_SB(dp->i_reiserfs)->priv_root->d_inode &&
		    de.de_objectid == le32toh(INODE_PKEY(REISERFS_SB(
		    dp->i_reiserfs)->priv_root->d_inode)->k_objectid)) {
			return (EACCES);
		}
#endif

		reiserfs_log(LOG_DEBUG, "reading vnode\n");
		pdp = vdp;
		if (flags & ISDOTDOT) {
			saved_ino = (struct cpu_key *)&(de.de_dir_id);
			VOP_UNLOCK(pdp, 0);
			error = reiserfs_iget(vdp->v_mount,
			    saved_ino, &vp, td);
			vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
			if (error != 0)
				return (error);
			*vpp = vp;
		} else if (de.de_objectid == dp->i_number &&
		    de.de_dir_id == dp->i_ino) {
			VREF(vdp); /* We want ourself, ie "." */
			*vpp = vdp;
		} else {
			if ((error = reiserfs_iget(vdp->v_mount,
			    (struct cpu_key *)&(de.de_dir_id), &vp, td)) != 0)
				return (error);
			*vpp = vp;
		}

		/*
		 * Propogate the priv_object flag so we know we're in the
		 * priv tree
		 */
		/*if (is_reiserfs_priv_object(dir))
			REISERFS_I(inode)->i_flags |= i_priv_object;*/
	} else {
		if (retval == IO_ERROR) {
			reiserfs_log(LOG_DEBUG, "IO error\n");
			return (EIO);
		}

		return (ENOENT);
	}

	/* Insert name into cache if appropriate. */
	if (cnp->cn_flags & MAKEENTRY)
		cache_enter(vdp, *vpp, cnp);

	reiserfs_log(LOG_DEBUG, "done\n");
	return (0);
}