OLeStream& operator << (int64_t v) { v = (int64_t)htole64((uint64_t)v); m_stream->write((char *)&v, sizeof(v)); return *this; }
_public_ int sd_journal_sendv(const struct iovec *iov, int n) { PROTECT_ERRNO; int fd, r; _cleanup_close_ int buffer_fd = -1; struct iovec *w; uint64_t *l; int i, j = 0; static const union sockaddr_union sa = { .un.sun_family = AF_UNIX, .un.sun_path = "/run/systemd/journal/socket", }; struct msghdr mh = { .msg_name = (struct sockaddr*) &sa.sa, .msg_namelen = SOCKADDR_UN_LEN(sa.un), }; ssize_t k; bool have_syslog_identifier = false; bool seal = true; assert_return(iov, -EINVAL); assert_return(n > 0, -EINVAL); w = newa(struct iovec, n * 5 + 3); l = newa(uint64_t, n); for (i = 0; i < n; i++) { char *c, *nl; if (_unlikely_(!iov[i].iov_base || iov[i].iov_len <= 1)) return -EINVAL; c = memchr(iov[i].iov_base, '=', iov[i].iov_len); if (_unlikely_(!c || c == iov[i].iov_base)) return -EINVAL; have_syslog_identifier = have_syslog_identifier || (c == (char *) iov[i].iov_base + 17 && startswith(iov[i].iov_base, "SYSLOG_IDENTIFIER")); nl = memchr(iov[i].iov_base, '\n', iov[i].iov_len); if (nl) { if (_unlikely_(nl < c)) return -EINVAL; /* Already includes a newline? Bummer, then * let's write the variable name, then a * newline, then the size (64bit LE), followed * by the data and a final newline */ w[j].iov_base = iov[i].iov_base; w[j].iov_len = c - (char*) iov[i].iov_base; j++; IOVEC_SET_STRING(w[j++], "\n"); l[i] = htole64(iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1); w[j].iov_base = &l[i]; w[j].iov_len = sizeof(uint64_t); j++; w[j].iov_base = c + 1; w[j].iov_len = iov[i].iov_len - (c - (char*) iov[i].iov_base) - 1; j++; } else /* Nothing special? Then just add the line and * append a newline */ w[j++] = iov[i]; IOVEC_SET_STRING(w[j++], "\n"); } if (!have_syslog_identifier && string_is_safe(program_invocation_short_name)) { /* Implicitly add program_invocation_short_name, if it * is not set explicitly. We only do this for * program_invocation_short_name, and nothing else * since everything else is much nicer to retrieve * from the outside. */ IOVEC_SET_STRING(w[j++], "SYSLOG_IDENTIFIER="); IOVEC_SET_STRING(w[j++], program_invocation_short_name); IOVEC_SET_STRING(w[j++], "\n"); } fd = journal_fd(); if (_unlikely_(fd < 0)) return fd; mh.msg_iov = w; mh.msg_iovlen = j; k = sendmsg(fd, &mh, MSG_NOSIGNAL); if (k >= 0) return 0; /* Fail silently if the journal is not available */ if (errno == ENOENT) return 0; if (errno != EMSGSIZE && errno != ENOBUFS) return -errno; /* Message doesn't fit... Let's dump the data in a memfd or * temporary file and just pass a file descriptor of it to the * other side. * * For the temporary files we use /dev/shm instead of /tmp * here, since we want this to be a tmpfs, and one that is * available from early boot on and where unprivileged users * can create files. */ buffer_fd = memfd_new(NULL); if (buffer_fd < 0) { if (buffer_fd == -ENOSYS) { buffer_fd = open_tmpfile_unlinkable("/dev/shm", O_RDWR | O_CLOEXEC); if (buffer_fd < 0) return buffer_fd; seal = false; } else return buffer_fd; } n = writev(buffer_fd, w, j); if (n < 0) return -errno; if (seal) { r = memfd_set_sealed(buffer_fd); if (r < 0) return r; } r = send_one_fd_sa(fd, buffer_fd, mh.msg_name, mh.msg_namelen, 0); if (r == -ENOENT) /* Fail silently if the journal is not available */ return 0; return r; } static int fill_iovec_perror_and_send(const char *message, int skip, struct iovec iov[]) { PROTECT_ERRNO; size_t n, k; k = isempty(message) ? 0 : strlen(message) + 2; n = 8 + k + 256 + 1; for (;;) { char buffer[n]; char* j; errno = 0; j = strerror_r(_saved_errno_, buffer + 8 + k, n - 8 - k); if (errno == 0) { char error[sizeof("ERRNO=")-1 + DECIMAL_STR_MAX(int) + 1]; if (j != buffer + 8 + k) memmove(buffer + 8 + k, j, strlen(j)+1); memcpy(buffer, "MESSAGE=", 8); if (k > 0) { memcpy(buffer + 8, message, k - 2); memcpy(buffer + 8 + k - 2, ": ", 2); } xsprintf(error, "ERRNO=%i", _saved_errno_); assert_cc(3 == LOG_ERR); IOVEC_SET_STRING(iov[skip+0], "PRIORITY=3"); IOVEC_SET_STRING(iov[skip+1], buffer); IOVEC_SET_STRING(iov[skip+2], error); return sd_journal_sendv(iov, skip + 3); } if (errno != ERANGE) return -errno; n *= 2; } } _public_ int sd_journal_perror(const char *message) { struct iovec iovec[3]; return fill_iovec_perror_and_send(message, 0, iovec); } _public_ int sd_journal_stream_fd(const char *identifier, int priority, int level_prefix) { static const union sockaddr_union sa = { .un.sun_family = AF_UNIX, .un.sun_path = "/run/systemd/journal/stdout", }; _cleanup_close_ int fd = -1; char *header; size_t l; int r; assert_return(priority >= 0, -EINVAL); assert_return(priority <= 7, -EINVAL); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) return -errno; r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un)); if (r < 0) return -errno; if (shutdown(fd, SHUT_RD) < 0) return -errno; fd_inc_sndbuf(fd, SNDBUF_SIZE); if (!identifier) identifier = ""; l = strlen(identifier); header = alloca(l + 1 + 1 + 2 + 2 + 2 + 2 + 2); memcpy(header, identifier, l); header[l++] = '\n'; header[l++] = '\n'; /* unit id */ header[l++] = '0' + priority; header[l++] = '\n'; header[l++] = '0' + !!level_prefix; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; header[l++] = '0'; header[l++] = '\n'; r = loop_write(fd, header, l, false); if (r < 0) return r; r = fd; fd = -1; return r; } _public_ int sd_journal_print_with_location(int priority, const char *file, const char *line, const char *func, const char *format, ...) { int r; va_list ap; va_start(ap, format); r = sd_journal_printv_with_location(priority, file, line, func, format, ap); va_end(ap); return r; } _public_ int sd_journal_printv_with_location(int priority, const char *file, const char *line, const char *func, const char *format, va_list ap) { char buffer[8 + LINE_MAX], p[sizeof("PRIORITY=")-1 + DECIMAL_STR_MAX(int) + 1]; struct iovec iov[5]; char *f; assert_return(priority >= 0, -EINVAL); assert_return(priority <= 7, -EINVAL); assert_return(format, -EINVAL); xsprintf(p, "PRIORITY=%i", priority & LOG_PRIMASK); memcpy(buffer, "MESSAGE=", 8); vsnprintf(buffer+8, sizeof(buffer) - 8, format, ap); /* Strip trailing whitespace, keep prefixing whitespace */ (void) strstrip(buffer); /* Suppress empty lines */ if (isempty(buffer+8)) return 0; /* func is initialized from __func__ which is not a macro, but * a static const char[], hence cannot easily be prefixed with * CODE_FUNC=, hence let's do it manually here. */ ALLOCA_CODE_FUNC(f, func); zero(iov); IOVEC_SET_STRING(iov[0], buffer); IOVEC_SET_STRING(iov[1], p); IOVEC_SET_STRING(iov[2], file); IOVEC_SET_STRING(iov[3], line); IOVEC_SET_STRING(iov[4], f); return sd_journal_sendv(iov, ELEMENTSOF(iov)); }
static int resize(gpt_t gpt, u_int entry, off_t alignment, off_t sectors, off_t size) { map_t map; struct gpt_hdr *hdr; struct gpt_ent *ent; unsigned int i; off_t alignsecs, newsize; uint64_t end; if ((hdr = gpt_hdr(gpt)) == NULL) return -1; i = entry - 1; ent = gpt_ent_primary(gpt, i); if (gpt_uuid_is_nil(ent->ent_type)) { gpt_warnx(gpt, "Entry at index %u is unused", entry); return -1; } alignsecs = alignment / gpt->secsz; for (map = map_first(gpt); map != NULL; map = map->map_next) { if (entry == map->map_index) break; } if (map == NULL) { gpt_warnx(gpt, "Could not find map entry corresponding " "to index"); return -1; } if (sectors > 0 && sectors == map->map_size) if (alignment == 0 || (alignment > 0 && sectors % alignsecs == 0)) { /* nothing to do */ gpt_warnx(gpt, "partition does not need resizing"); return 0; } newsize = map_resize(gpt, map, sectors, alignsecs); if (newsize == -1) return -1; end = htole64((uint64_t)(map->map_start + newsize - 1LL)); ent->ent_lba_end = end; if (gpt_write_primary(gpt) == -1) return -1; ent = gpt_ent(gpt->gpt, gpt->lbt, i); ent->ent_lba_end = end; if (gpt_write_backup(gpt) == -1) return -1; gpt_msg(gpt, "Partition %d resized: %" PRIu64 " %" PRIu64, entry, map->map_start, newsize); return 0; }
static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node) { uint64_t i; struct trie_node_f n = { .prefix_off = htole64(trie->strings_off + node->prefix_off), .children_count = node->children_count, .values_count = htole64(node->values_count), }; struct trie_child_entry_f *children = NULL; int64_t node_off; if (node->children_count) { children = new0(struct trie_child_entry_f, node->children_count); if (!children) return -ENOMEM; } /* post-order recursion */ for (i = 0; i < node->children_count; i++) { int64_t child_off; child_off = trie_store_nodes(trie, node->children[i].child); if (child_off < 0) { free(children); return child_off; } children[i].c = node->children[i].c; children[i].child_off = htole64(child_off); } /* write node */ node_off = ftello(trie->f); if (fwrite(&n, sizeof(struct trie_node_f), 1, trie->f) != 1) log_error("Failed to write sizeof struct trie_node_f to n in %s\n", "[udevadm-hwdb.c:trie_store_nodes]"); trie->nodes_count++; /* append children array */ if (node->children_count) { if (fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f) != node->children_count) log_error("Failed to write children_count in %s\n", "[udevadm-hwdb.c:trie_store_nodes]"); trie->children_count += node->children_count; free(children); } /* append values array */ for (i = 0; i < node->values_count; i++) { struct trie_value_entry_f v = { .key_off = htole64(trie->strings_off + node->values[i].key_off), .value_off = htole64(trie->strings_off + node->values[i].value_off), }; if (fwrite(&v, sizeof(struct trie_value_entry_f), 1, trie->f) != 1) log_error("Failed to write sizeof trie_value_entry_f to v in %s\n", "[udevadm-hwdb.c:trie_store_nodes]"); trie->values_count++; } return node_off; } static int trie_store(struct trie *trie, const char *filename) { struct trie_f t = { .trie = trie, }; char *filename_tmp; int64_t pos; int64_t root_off; int64_t size; struct trie_header_f h = { .signature = HWDB_SIG, .tool_version = htole64(atoi(VERSION)), .header_size = htole64(sizeof(struct trie_header_f)), .node_size = htole64(sizeof(struct trie_node_f)), .child_entry_size = htole64(sizeof(struct trie_child_entry_f)), .value_entry_size = htole64(sizeof(struct trie_value_entry_f)), }; int err; /* calculate size of header, nodes, children entries, value entries */ t.strings_off = sizeof(struct trie_header_f); trie_store_nodes_size(&t, trie->root); err = fopen_temporary(filename , &t.f, &filename_tmp); if (err < 0) return err; fchmod(fileno(t.f), 0444); /* write nodes */ fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET); root_off = trie_store_nodes(&t, trie->root); h.nodes_root_off = htole64(root_off); pos = ftello(t.f); h.nodes_len = htole64(pos - sizeof(struct trie_header_f)); /* write string buffer */ if (fwrite(trie->strings->buf, trie->strings->len, 1, t.f) != 1) log_error("Failed to write into trie->strings->buf in %s\n", "[udevadm-hwdb.c:trie_store]"); h.strings_len = htole64(trie->strings->len); /* write header */ size = ftello(t.f); h.file_size = htole64(size); fseeko(t.f, 0, SEEK_SET); if (fwrite(&h, sizeof(struct trie_header_f), 1, t.f) != 1) log_error("Failed to write into h in %s\n", "[udevadm-hwdb.c:trie_store]"); err = ferror(t.f); if (err) err = -errno; fclose(t.f); if (err < 0 || rename(filename_tmp, filename) < 0) { unlink(filename_tmp); goto out; } log_debug("=== trie on-disk ===\n"); log_debug("size: %8llu bytes\n", (unsigned long long)size); log_debug("header: %8zu bytes\n", sizeof(struct trie_header_f)); log_debug("nodes: %8llu bytes (%8llu)\n", (unsigned long long)t.nodes_count * sizeof(struct trie_node_f), (unsigned long long)t.nodes_count); log_debug("child pointers: %8llu bytes (%8llu)\n", (unsigned long long)t.children_count * sizeof(struct trie_child_entry_f), (unsigned long long)t.children_count); log_debug("value pointers: %8llu bytes (%8llu)\n", (unsigned long long)t.values_count * sizeof(struct trie_value_entry_f), (unsigned long long)t.values_count); log_debug("string store: %8llu bytes\n", (unsigned long long)trie->strings->len); log_debug("strings start: %8llu\n", (unsigned long long) t.strings_off); out: free(filename_tmp); return err; } static int insert_data(struct trie *trie, struct udev_list *match_list, char *line, const char *filename) { char *value; struct udev_list_entry *entry; value = strchr(line, '='); if (!value) { log_error("Error, key/value pair expected but got '%s' in '%s':\n", line, filename); return -EINVAL; } value[0] = '\0'; value++; if (line[0] == '\0' || value[0] == '\0') { log_error("Error, empty key or value '%s' in '%s':\n", line, filename); return -EINVAL; } udev_list_entry_foreach(entry, udev_list_get_entry(match_list)) trie_insert(trie, trie->root, udev_list_entry_get_name(entry), line, value); return 0; } static int import_file(struct udev *udev, struct trie *trie, const char *filename) { enum { HW_MATCH, HW_DATA, HW_NONE, } state = HW_NONE; FILE *f; char line[LINE_MAX]; struct udev_list match_list; udev_list_init(udev, &match_list, false); f = fopen(filename, "re"); if (f == NULL) return -errno; while (fgets(line, sizeof(line), f)) { size_t len; char *pos; /* comment line */ if (line[0] == '#') continue; /* strip trailing comment */ pos = strchr(line, '#'); if (pos) pos[0] = '\0'; /* strip trailing whitespace */ len = strlen(line); while (len > 0 && isspace(line[len-1])) len--; line[len] = '\0'; switch (state) { case HW_NONE: if (len == 0) break; if (line[0] == ' ') { log_error("Error, MATCH expected but got '%s' in '%s':\n", line, filename); break; } /* start of record, first match */ state = HW_MATCH; udev_list_entry_add(&match_list, line, NULL); break; case HW_MATCH: if (len == 0) { log_error("Error, DATA expected but got empty line in '%s':\n", filename); state = HW_NONE; udev_list_cleanup(&match_list); break; } /* another match */ if (line[0] != ' ') { udev_list_entry_add(&match_list, line, NULL); break; } /* first data */ state = HW_DATA; insert_data(trie, &match_list, line, filename); break; case HW_DATA: /* end of record */ if (len == 0) { state = HW_NONE; udev_list_cleanup(&match_list); break; } if (line[0] != ' ') { log_error("Error, DATA expected but got '%s' in '%s':\n", line, filename); state = HW_NONE; udev_list_cleanup(&match_list); break; } insert_data(trie, &match_list, line, filename); break; }; } fclose(f); udev_list_cleanup(&match_list); return 0; } static void help(void) { printf("Usage: udevadm hwdb OPTIONS\n" " --update update the hardware database\n" " --test=<modalias> query database and print result\n" " --root=<path> alternative root path in the filesystem\n" " --help\n\n"); }
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); } } }
/* * util_header_create -- (internal) create header of a single pool set file */ static int util_header_create(struct pool_set *set, unsigned repidx, unsigned partidx, const char *sig, uint32_t major, uint32_t compat, uint32_t incompat, uint32_t ro_compat) { LOG(3, "set %p repidx %u partidx %u sig %s major %u " "compat %#x incompat %#x ro_comapt %#x", set, repidx, partidx, sig, major, compat, incompat, ro_compat); struct pool_replica *rep = set->replica[repidx]; /* opaque info lives at the beginning of mapped memory pool */ struct pool_hdr *hdrp = rep->part[partidx].addr; /* check if the pool header is all zeros */ if (!util_is_zeroed(hdrp, sizeof (*hdrp))) { ERR("Non-empty file detected"); errno = EINVAL; return -1; } /* create pool's header */ strncpy(hdrp->signature, sig, POOL_HDR_SIG_LEN); hdrp->major = htole32(major); hdrp->compat_features = htole32(compat); hdrp->incompat_features = htole32(incompat); hdrp->ro_compat_features = htole32(ro_compat); memcpy(hdrp->poolset_uuid, set->uuid, POOL_HDR_UUID_LEN); memcpy(hdrp->uuid, PART(rep, partidx).uuid, POOL_HDR_UUID_LEN); /* link parts */ memcpy(hdrp->prev_part_uuid, PART(rep, partidx - 1).uuid, POOL_HDR_UUID_LEN); memcpy(hdrp->next_part_uuid, PART(rep, partidx + 1).uuid, POOL_HDR_UUID_LEN); /* link replicas */ memcpy(hdrp->prev_repl_uuid, PART(REP(set, repidx - 1), 0).uuid, POOL_HDR_UUID_LEN); memcpy(hdrp->next_repl_uuid, PART(REP(set, repidx + 1), 0).uuid, POOL_HDR_UUID_LEN); hdrp->crtime = htole64((uint64_t)time(NULL)); if (util_get_arch_flags(&hdrp->arch_flags)) { ERR("Reading architecture flags failed\n"); errno = EINVAL; return -1; } hdrp->arch_flags.alignment_desc = htole64(hdrp->arch_flags.alignment_desc); hdrp->arch_flags.e_machine = htole16(hdrp->arch_flags.e_machine); util_checksum(hdrp, sizeof (*hdrp), &hdrp->checksum, 1); /* store pool's header */ pmem_msync(hdrp, sizeof (*hdrp)); return 0; }
//make archive footer: Central Directory, Zip64 Central Directory End, Zip64 locator and Central Directory end chunks ngx_chain_t * ngx_http_zip_central_directory_chain_link(ngx_http_request_t *r, ngx_http_zip_ctx_t *ctx, ngx_http_zip_piece_t *piece, ngx_http_zip_range_t *range) { //nb: this is to be called only after 'generate pieces' ngx_chain_t *trailer; ngx_buf_t *trailer_buf; u_char *p; off_t cd_size; ngx_uint_t i; ngx_array_t *files; ngx_zip_end_of_central_directory_record_t eocdr; ngx_zip_zip64_end_of_central_directory_record_t eocdr64; ngx_zip_zip64_end_of_central_directory_locator_t locator64; if (!ctx || !ctx->cd_size || (trailer = ngx_alloc_chain_link(r->pool)) == NULL || (trailer_buf = ngx_calloc_buf(r->pool)) == NULL || (p = ngx_palloc(r->pool, ctx->cd_size)) == NULL) return NULL; files = &ctx->files; trailer->buf = trailer_buf; trailer->next = NULL; trailer_buf->pos = p; trailer_buf->last = p + ctx->cd_size; trailer_buf->last_buf = 1; trailer_buf->sync = 1; trailer_buf->memory = 1; for (i = 0; i < files->nelts; i++) p = ngx_http_zip_write_central_directory_entry(p, &((ngx_http_zip_file_t *)files->elts)[i], ctx); eocdr = ngx_zip_end_of_central_directory_record_template; eocdr.signature = htole32(eocdr.signature); if (files->nelts < NGX_MAX_UINT16_VALUE) { eocdr.disk_entries_n = htole16(files->nelts); eocdr.entries_n = htole16(files->nelts); } cd_size = ctx->cd_size - sizeof(ngx_zip_end_of_central_directory_record_t) - (!!ctx->zip64_used)*(sizeof(ngx_zip_zip64_end_of_central_directory_record_t) + sizeof(ngx_zip_zip64_end_of_central_directory_locator_t)); if (cd_size < (off_t) NGX_MAX_UINT32_VALUE) eocdr.size = htole32(cd_size); if (piece->range.start < (off_t) NGX_MAX_UINT32_VALUE) eocdr.offset = htole32(piece->range.start); if (ctx->zip64_used) { eocdr64 = ngx_zip_zip64_end_of_central_directory_record_template; eocdr64.signature = htole32(eocdr64.signature); eocdr64.size = htole64(eocdr64.size); eocdr64.version_made_by = htole16(eocdr64.version_made_by); eocdr64.version_needed = htole16(eocdr64.version_made_by); eocdr64.cd_n_entries_on_this_disk = eocdr64.cd_n_entries_total = htole64(files->nelts); eocdr64.cd_size = htole64(cd_size); eocdr64.cd_offset = htole64(piece->range.start); ngx_memcpy(p, &eocdr64, sizeof(ngx_zip_zip64_end_of_central_directory_record_t)); p += sizeof(ngx_zip_zip64_end_of_central_directory_record_t); locator64 = ngx_zip_zip64_end_of_central_directory_locator_template; locator64.signature = htole32(locator64.signature); locator64.disks_total_n = htole32(locator64.disks_total_n); locator64.cd_relative_offset = htole64(piece->range.start + cd_size); ngx_memcpy(p, &locator64, sizeof(ngx_zip_zip64_end_of_central_directory_locator_t)); p += sizeof(ngx_zip_zip64_end_of_central_directory_locator_t); } ngx_memcpy(p, &eocdr, sizeof(ngx_zip_end_of_central_directory_record_t)); ngx_http_zip_truncate_buffer(trailer->buf, &piece->range, range); return trailer; }
inline uint64_t htofx(uint64_t hostbits) { return elf_little_endian ? htole64(hostbits) : htobe64(hostbits); }
std::vector<unsigned char> generate_version() { struct bitcoin_version_with_header version_msg; version_msg.version.start.timestamp = htole64(time(0)); version_msg.version.start.user_agent_length = BITCOIN_UA_LENGTH; // Work around apparent gcc bug return std::vector<unsigned char>((unsigned char*)&version_msg, (unsigned char*)&version_msg + sizeof(version_msg)); }
/** * Attempts to the read the given number of bytes from the given file. * * @param client The relevant AFC client * @param handle File handle of a previously opened file * @param data The pointer to the memory region to store the read data * @param length The number of bytes to read * @param bytes_read The number of bytes actually read. * * @return AFC_E_SUCCESS on success or an AFC_E_* error value. */ idevice_error_t afc_file_read(afc_client_t client, uint64_t handle, char *data, uint32_t length, uint32_t *bytes_read) { char *input = NULL; uint32_t current_count = 0, bytes_loc = 0; const uint32_t MAXIMUM_READ_SIZE = 1 << 16; afc_error_t ret = AFC_E_SUCCESS; if (!client || !client->afc_packet || !client->parent || handle == 0) return AFC_E_INVALID_ARG; debug_info("called for length %i", length); afc_lock(client); /* Looping here to get around the maximum amount of data that afc_receive_data can handle */ while (current_count < length) { debug_info("current count is %i but length is %i", current_count, length); /* Send the read command */ AFCFilePacket *packet = (AFCFilePacket *) malloc(sizeof(AFCFilePacket)); packet->filehandle = handle; packet->size = htole64(((length - current_count) < MAXIMUM_READ_SIZE) ? (length - current_count) : MAXIMUM_READ_SIZE); client->afc_packet->operation = AFC_OP_READ; client->afc_packet->entire_length = client->afc_packet->this_length = 0; ret = afc_dispatch_packet(client, (char *) packet, sizeof(AFCFilePacket), &bytes_loc); free(packet); if (ret != AFC_E_SUCCESS) { afc_unlock(client); return AFC_E_NOT_ENOUGH_DATA; } /* Receive the data */ ret = afc_receive_data(client, &input, &bytes_loc); debug_info("afc_receive_data returned error: %d", ret); debug_info("bytes returned: %i", bytes_loc); if (ret != AFC_E_SUCCESS) { afc_unlock(client); return ret; } else if (bytes_loc == 0) { if (input) free(input); afc_unlock(client); *bytes_read = current_count; /* FIXME: check that's actually a success */ return ret; } else { if (input) { debug_info("%d", bytes_loc); memcpy(data + current_count, input, (bytes_loc > length) ? length : bytes_loc); free(input); input = NULL; current_count += (bytes_loc > length) ? length : bytes_loc; } } } debug_info("returning current_count as %i", current_count); afc_unlock(client); *bytes_read = current_count; return ret; }
int mb_put_int64le(struct mbchain *mbp, int64_t x) { x = htole64(x); return mb_put_mem(mbp, (void *)&x, sizeof(x), MB_MSYSTEM); }
/* * pmemlog_map_common -- (internal) map a log memory pool * * This routine does all the work, but takes a rdonly flag so internal * calls can map a read-only pool if required. */ static PMEMlog * pmemlog_map_common(int fd, int rdonly) { LOG(3, "fd %d rdonly %d", fd, rdonly); struct stat stbuf; if (fstat(fd, &stbuf) < 0) { LOG(1, "!fstat"); return NULL; } if (stbuf.st_size < PMEMLOG_MIN_POOL) { LOG(1, "size %lld smaller than %zu", (long long)stbuf.st_size, PMEMLOG_MIN_POOL); errno = EINVAL; return NULL; } void *addr; if ((addr = util_map(fd, stbuf.st_size, rdonly)) == NULL) return NULL; /* util_map() set errno, called LOG */ /* check if the mapped region is located in persistent memory */ int is_pmem = pmem_is_pmem(addr, stbuf.st_size); /* opaque info lives at the beginning of mapped memory pool */ struct pmemlog *plp = addr; struct pool_hdr hdr; memcpy(&hdr, &plp->hdr, sizeof (hdr)); if (util_convert_hdr(&hdr)) { /* * valid header found */ if (strncmp(hdr.signature, LOG_HDR_SIG, POOL_HDR_SIG_LEN)) { LOG(1, "wrong pool type: \"%s\"", hdr.signature); errno = EINVAL; goto err; } if (hdr.major != LOG_FORMAT_MAJOR) { LOG(1, "log pool version %d (library expects %d)", hdr.major, LOG_FORMAT_MAJOR); errno = EINVAL; goto err; } uint64_t hdr_start = le64toh(plp->start_offset); uint64_t hdr_end = le64toh(plp->end_offset); uint64_t hdr_write = le64toh(plp->write_offset); if ((hdr_start != roundup(sizeof (*plp), LOG_FORMAT_DATA_ALIGN)) || (hdr_end != stbuf.st_size) || (hdr_start > hdr_end)) { LOG(1, "wrong start/end offsets (start: %ju end: %ju), " "pool size %lld", hdr_start, hdr_end, (long long)stbuf.st_size); errno = EINVAL; goto err; } if ((hdr_write > hdr_end) || (hdr_write < hdr_start)) { LOG(1, "wrong write offset " "(start: %ju end: %ju write: %ju)", hdr_start, hdr_end, hdr_write); errno = EINVAL; goto err; } LOG(3, "start: %ju, end: %ju, write: %ju", hdr_start, hdr_end, hdr_write); int retval = util_feature_check(&hdr, LOG_FORMAT_INCOMPAT, LOG_FORMAT_RO_COMPAT, LOG_FORMAT_COMPAT); if (retval < 0) goto err; else if (retval == 0) rdonly = 1; } else { /* * no valid header was found */ if (rdonly) { LOG(1, "read-only and no header found"); errno = EROFS; goto err; } LOG(3, "creating new log memory pool"); struct pool_hdr *hdrp = &plp->hdr; memset(hdrp, '\0', sizeof (*hdrp)); strncpy(hdrp->signature, LOG_HDR_SIG, POOL_HDR_SIG_LEN); hdrp->major = htole32(LOG_FORMAT_MAJOR); hdrp->compat_features = htole32(LOG_FORMAT_COMPAT); hdrp->incompat_features = htole32(LOG_FORMAT_INCOMPAT); hdrp->ro_compat_features = htole32(LOG_FORMAT_RO_COMPAT); uuid_generate(hdrp->uuid); hdrp->crtime = htole64((uint64_t)time(NULL)); util_checksum(hdrp, sizeof (*hdrp), &hdrp->checksum, 1); hdrp->checksum = htole64(hdrp->checksum); /* store pool's header */ libpmem_persist(is_pmem, hdrp, sizeof (*hdrp)); /* create rest of required metadata */ plp->start_offset = htole64(roundup(sizeof (*plp), LOG_FORMAT_DATA_ALIGN)); plp->end_offset = htole64(stbuf.st_size); plp->write_offset = plp->start_offset; /* store non-volatile part of pool's descriptor */ libpmem_persist(is_pmem, &plp->start_offset, 3 * sizeof (uint64_t)); } /* * Use some of the memory pool area for run-time info. This * run-time state is never loaded from the file, it is always * created here, so no need to worry about byte-order. */ plp->addr = addr; plp->size = stbuf.st_size; plp->rdonly = rdonly; plp->is_pmem = is_pmem; if ((plp->rwlockp = Malloc(sizeof (*plp->rwlockp))) == NULL) { LOG(1, "!Malloc for a RW lock"); goto err; } if (pthread_rwlock_init(plp->rwlockp, NULL)) { LOG(1, "!pthread_rwlock_init"); goto err_free; } /* * If possible, turn off all permissions on the pool header page. * * The prototype PMFS doesn't allow this when large pages are in * use. It is not considered an error if this fails. */ util_range_none(addr, sizeof (struct pool_hdr)); /* the rest should be kept read-only (debug version only) */ RANGE_RO(addr + sizeof (struct pool_hdr), stbuf.st_size - sizeof (struct pool_hdr)); LOG(3, "plp %p", plp); return plp; err_free: Free((void *)plp->rwlockp); err: LOG(4, "error clean up"); int oerrno = errno; util_unmap(addr, stbuf.st_size); errno = oerrno; return NULL; }
/* * write_layout -- (internal) write out the initial btt metadata layout * * Called with write == 1 only once in the life time of a btt namespace, when * the first write happens. The caller of this routine is responsible for * locking out multiple threads. This routine doesn't read anything -- by the * time it is called, it is known there's no layout in the namespace and a new * layout should be written. * * Calling with write == 0 tells this routine to do the calculations for * bttp->narena and bttp->nlba, but don't write out any metadata. * * If successful, sets bttp->layout to 1 and returns 0. Otherwise -1 * is returned and errno is set, and bttp->layout remains 0 so that * later attempts to write will try again to create the layout. */ static int write_layout(struct btt *bttp, int lane, int write) { LOG(3, "bttp %p lane %d write %d", bttp, lane, write); ASSERT(bttp->rawsize >= BTT_MIN_SIZE); ASSERT(bttp->nfree); /* * The number of arenas is the number of full arena of * size BTT_MAX_ARENA that fit into rawsize and then, if * the remainder is at least BTT_MIN_SIZE in size, then * that adds one more arena. */ bttp->narena = bttp->rawsize / BTT_MAX_ARENA; if (bttp->rawsize % BTT_MAX_ARENA >= BTT_MIN_SIZE) bttp->narena++; LOG(4, "narena %u", bttp->narena); int flog_size = bttp->nfree * 2 * sizeof (struct btt_flog); flog_size = roundup(flog_size, BTT_ALIGNMENT); uint32_t internal_lbasize = bttp->lbasize; if (internal_lbasize < BTT_MIN_LBA) internal_lbasize = BTT_MIN_LBA; internal_lbasize = roundup(internal_lbasize, BTT_INTERNAL_LBA_ALIGNMENT); LOG(4, "adjusted internal_lbasize %u", internal_lbasize); uint64_t total_nlba = 0; uint64_t rawsize = bttp->rawsize; int arena_num = 0; off_t arena_off = 0; /* * for each arena... */ while (rawsize >= BTT_MIN_SIZE) { LOG(4, "layout arena %u", arena_num); uint64_t arena_rawsize = rawsize; if (arena_rawsize > BTT_MAX_ARENA) { arena_rawsize = BTT_MAX_ARENA; } rawsize -= arena_rawsize; arena_num++; uint64_t arena_datasize = arena_rawsize; arena_datasize -= 2 * sizeof (struct btt_info); arena_datasize -= flog_size; /* allow for map alignment padding */ uint64_t internal_nlba = (arena_datasize - BTT_ALIGNMENT) / (internal_lbasize + BTT_MAP_ENTRY_SIZE); uint64_t external_nlba = internal_nlba - bttp->nfree; LOG(4, "internal_nlba %zu external_nlba %zu", internal_nlba, external_nlba); total_nlba += external_nlba; /* * The rest of the loop body calculates metadata structures * and lays it out for this arena. So only continue if * the write flag is set. */ if (!write) continue; uint64_t mapsize = roundup(external_nlba * BTT_MAP_ENTRY_SIZE, BTT_ALIGNMENT); arena_datasize -= mapsize; ASSERT(arena_datasize / internal_lbasize >= internal_nlba); /* * Calculate offsets for the BTT info block. These are * all relative to the beginning of the arena. */ uint64_t nextoff; if (rawsize) nextoff = arena_rawsize; else nextoff = 0; uint64_t infooff = arena_rawsize - sizeof (struct btt_info); uint64_t flogoff = infooff - flog_size; uint64_t mapoff = flogoff - mapsize; uint64_t dataoff = sizeof (struct btt_info); LOG(4, "nextoff 0x%016lx", nextoff); LOG(4, "dataoff 0x%016lx", dataoff); LOG(4, "mapoff 0x%016lx", mapoff); LOG(4, "flogoff 0x%016lx", flogoff); LOG(4, "infooff 0x%016lx", infooff); ASSERTeq(arena_datasize, mapoff - dataoff); /* write out the initial map, identity style */ off_t map_entry_off = arena_off + mapoff; uint32_t *mapp = NULL; int mlen = 0; int next_index = 0; int remaining = 0; for (int i = 0; i < external_nlba; i++) { if (remaining == 0) { /* flush previous mapped area */ if (mapp != NULL) { /* * Protect the memory again * (debug version only). * If (mapp != NULL) it had to be * unprotected earlier. */ RANGE_RO(mapp, mlen); (*bttp->ns_cbp->nssync)(bttp->ns, lane, mapp, mlen); } /* request a mapping of remaining map area */ mlen = (*bttp->ns_cbp->nsmap)(bttp->ns, lane, (void **)&mapp, (external_nlba - i) * sizeof (uint32_t), map_entry_off); if (mlen < 0) return -1; /* unprotect the memory (debug version only) */ RANGE_RW(mapp, mlen); remaining = mlen; next_index = 0; } mapp[next_index++] = htole32(i | BTT_MAP_ENTRY_ZERO); remaining -= sizeof (uint32_t); } /* protect the memory again (debug version only) */ RANGE_RO(mapp, mlen); /* flush previous mapped area */ if (mapp != NULL) (*bttp->ns_cbp->nssync)(bttp->ns, lane, mapp, mlen); /* write out the initial flog */ off_t flog_entry_off = arena_off + flogoff; uint32_t next_free_lba = external_nlba; for (int i = 0; i < bttp->nfree; i++) { struct btt_flog flog; flog.lba = 0; flog.old_map = flog.new_map = htole32(next_free_lba | BTT_MAP_ENTRY_ZERO); flog.seq = htole32(1); /* * Write both btt_flog structs in the pair, writing * the second one as all zeros. */ LOG(6, "flog[%d] entry off %zu initial %u + zero = %u", i, flog_entry_off, next_free_lba, next_free_lba | BTT_MAP_ENTRY_ZERO); if ((*bttp->ns_cbp->nswrite)(bttp->ns, lane, &flog, sizeof (flog), flog_entry_off) < 0) return -1; flog_entry_off += sizeof (flog); LOG(6, "flog[%d] entry off %zu zeros", i, flog_entry_off); if ((*bttp->ns_cbp->nswrite)(bttp->ns, lane, &Zflog, sizeof (Zflog), flog_entry_off) < 0) return -1; flog_entry_off += sizeof (flog); next_free_lba++; } /* * Construct the BTT info block and write it out * at both the beginning and end of the arena. */ struct btt_info info; memset(&info, '\0', sizeof (info)); memcpy(info.sig, Sig, BTTINFO_SIG_LEN); memcpy(info.parent_uuid, bttp->parent_uuid, BTTINFO_UUID_LEN); info.major = htole16(BTTINFO_MAJOR_VERSION); info.minor = htole16(BTTINFO_MINOR_VERSION); info.external_lbasize = htole32(bttp->lbasize); info.external_nlba = htole32(external_nlba); info.internal_lbasize = htole32(internal_lbasize); info.internal_nlba = htole32(internal_nlba); info.nfree = htole32(bttp->nfree); info.infosize = htole32(sizeof (info)); info.nextoff = htole64(nextoff); info.dataoff = htole64(dataoff); info.mapoff = htole64(mapoff); info.flogoff = htole64(flogoff); info.infooff = htole64(infooff); util_checksum(&info, sizeof (info), &info.checksum, 1); if ((*bttp->ns_cbp->nswrite)(bttp->ns, lane, &info, sizeof (info), arena_off) < 0) return -1; if ((*bttp->ns_cbp->nswrite)(bttp->ns, lane, &info, sizeof (info), arena_off + nextoff) < 0) return -1; arena_off += nextoff; } ASSERTeq(bttp->narena, arena_num); bttp->nlba = total_nlba; if (write) { /* * The layout is written now, so load up the arenas. */ return read_arenas(bttp, lane, bttp->narena); } return 0; }
//in the write function len is expressed in bits int bitio_write(bitio* f, uint64_t d, int len) { //len is expressed in bits int space, ofs, n, i, result, original; uint64_t* p; uint64_t tmp; original=(int) d; //check all the parameters if((f==NULL)||(len<1)||(len>8*sizeof(d))) { errno=EINVAL; fprintf(stderr, "Error1\n"); return -1; } //check if we do the right operation if(!f->writing) { errno=EINVAL; fprintf(stderr, "Error2\n"); return -1; } again: space=f->end-f->next; //check if there's enough space on the buffer if(space<0) { errno=EINVAL; fprintf(stderr, "Error3\n"); return -1; } //check if the buffer is full if(space==0) { //write the buffer in the file result=(int)write(f->fd, f->buf, MAX_SIZE*8); if(result<0) { fprintf(stderr, "Error in write\n"); return -1; } //reset the buffer for(i=0; i<MAX_SIZE; i++) { f->buf[i]=0; } //reset the structure f->size=MAX_SIZE*64; f->end=f->size; f->next=0; } //go to the right address in the buffer p=f->buf+(f->next/64); //go to the right offset ofs=f->next%64; n=64-ofs; if(len<n) n=len; //convert *p from little endian tmp=le64toh(*p); //shift the datum of ofs positions tmp|=(d<<ofs); if((ofs+n)>64) { tmp&=((1<<(ofs+n))-1); } *p=htole64(tmp); //update the structure f->next+=n; len-=n; d>>=n; //check if there are bits left to put in the buffer if(len>0) goto again; if(original==EOFC) { //fprintf(stderr, "\n\t\tEOF written\n"); //f->buf[(MAX_SIZE-1)]=d; result=(int)write(f->fd, f->buf, (f->next/8)+1); if(result<0) fprintf(stderr, "Error in write\n"); return 1; } //if the operation succedes return 1 return 1; }
struct virtio_blk_config blk_config; } virtblk_dev_page = { .dd = { .type = VIRTIO_ID_BLOCK, .num_vq = ARRAY_SIZE(virtblk_dev_page.vqconfig), .feature_len = sizeof(virtblk_dev_page.host_features), .config_len = sizeof(virtblk_dev_page.blk_config), }, .vqconfig[0] = { .num = htole16(MIC_VRING_ENTRIES), }, .host_features = htole32(1<<VIRTIO_BLK_F_SEG_MAX), .blk_config = { .seg_max = htole32(MIC_VRING_ENTRIES - 2), .capacity = htole64(0), } }; static int tap_configure(struct mic_info *mic, char *dev) { pid_t pid; char *ifargv[7]; int ret = 0; pid = fork(); if (pid == 0) { ifargv[0] = "ip"; ifargv[1] = "link"; ifargv[2] = "set";
bool UP3D_GetPrinterStatus(TT_tagPrinterStatus *status) { int32_t sysvar, sysvar2 = 0; if( UP3D_GetSystemVar( 0, &sysvar) ) //PARA_SYSTEM_STATUS status->SystemStatus = (uint8_t)sysvar; if( !UP3D_GetSystemVar( 0x10, &sysvar) ) //PARA_PRINT_STATUS return false; status->PrintStatus = (uint8_t)sysvar; if( UP3D_GetSystemVar( 0x0A, &sysvar) ) //PARA_REPORT_LAYER status->ReportLayer = htole16((uint16_t)sysvar); if( UP3D_GetSystemVar( 0x0B, &sysvar) ) //PARA_REPORT_HEIGHT status->ReportHeight = htole16((int16_t)floor( (*((float*)&sysvar))*10.0 ) ); if( UP3D_GetSystemVar( 0x4D, &sysvar) && UP3D_GetSystemVar( 0x4C, &sysvar2) ) //PARA_REPORT_TIME_REMAIN PARA_REPORT_PERCENT status->ReportTimeAndPercent = htole32(sysvar2 + (sysvar<<8)); if( UP3D_GetSystemVar( 6, &sysvar) ) //NOZZLE1 TEMP status->Nozzle1Temp = htole16((int16_t)floor( (*((float*)&sysvar))*50.0 )); if( UP3D_GetSystemVar( 7, &sysvar) ) //NOZZLE2 TEMP status->Nozzle2Temp = htole16((int16_t)floor( (*((float*)&sysvar))*50.0 )); if( UP3D_GetSystemVar( 8, &sysvar) ) //BED TEMP status->BedTemp = htole16((int16_t)floor( (*((float*)&sysvar))*50.0 )); if( UP3D_GetSystemVar( 9, &sysvar) ) //ROOM TEMP status->RoomTemp = htole16((int16_t)floor( (*((float*)&sysvar))*50.0 )); status->HeaterStatus = 0; if( UP3D_GetSystemVar( 0x14, &sysvar) ) //HEATER NOZZLE1 STATUS status->HeaterStatus |= sysvar?1:0; if( UP3D_GetSystemVar( 0x15, &sysvar) ) //HEATER NOZZLE2 STATUS status->HeaterStatus |= sysvar?2:0; if( UP3D_GetSystemVar( 0x16, &sysvar) ) //HEATER BED STATUS status->HeaterStatus |= sysvar?4:0; UP3D_SetParameter( 0x94, 999 ); //SET_Z_PRECISION uint32_t v; for( v=0; v<4; v++ ) { status->AxisStatus[v] = 0; if( UP3D_GetSystemVar( v+2, &sysvar) ) //MOTOR STATUS status->AxisStatus[v] |= sysvar & 7; if( UP3D_GetSystemVar( v+0x18, &sysvar) ) //HF? status->AxisStatus[v] |= sysvar?8:0; if( UP3D_GetSystemVar( v+0x26, &sysvar) ) //NL? status->AxisStatus[v] |= sysvar?16:0; if( UP3D_GetSystemVar( v+0x22, &sysvar) ) //ENDSTOP status->AxisStatus[v] |= sysvar?32:0; if( UP3D_GetSystemVar( v+0x1E, &sysvar) ) //ERROR status->AxisStatus[v] |= sysvar<<6; sysvar = UP3D_GetAxisPosition(v); float f = ((float)sysvar) / 854.0; //FIXED VALUE FOR NOW status->AxisPosition[v] = htole32( *((uint32_t*)&f) ); } UP3D_SetParameter( 0x94, 0 ); //SET_Z_PRECISION if( UP3D_GetSystemVar( 0x5E, &sysvar) ) //? status->Para_x5E = htole32(sysvar); if( UP3D_GetSystemVar( 0x5F, &sysvar) ) //? status->Para_x5F = htole32(sysvar); if( UP3D_GetSystemVar( 0x56, &sysvar) ) //? status->Para_x56 = htole32(sysvar); if( UP3D_GetSystemVar( 0x57, &sysvar) ) //? status->Para_x57 = htole32(sysvar); status->UnkMinusOne = htole64((int64_t)-1); return true; }
int igb_xmit(device_t *dev, unsigned int queue_index, struct igb_packet *packet) { struct adapter *adapter; struct tx_ring *txr; struct igb_tx_buffer *tx_buffer; union e1000_adv_tx_desc *txd = NULL; u32 cmd_type_len, olinfo_status = 0; int i, first, last = 0; int error = 0; if (NULL == dev) return EINVAL; adapter = (struct adapter *)dev->private_data; if (NULL == adapter) return ENXIO; txr = &adapter->tx_rings[queue_index]; if( !txr ) return EINVAL; if (queue_index > adapter->num_queues) return EINVAL; if (NULL == packet) return EINVAL; if( sem_wait( adapter->memlock ) != 0 ) { return errno; } packet->next = NULL; /* used for cleanup */ /* Set basic descriptor constants */ cmd_type_len = E1000_ADVTXD_DTYP_DATA; cmd_type_len |= E1000_ADVTXD_DCMD_IFCS | E1000_ADVTXD_DCMD_DEXT; /* cmd_type_len |= E1000_ADVTXD_DCMD_VLE; to enable VLAN insertion */ /* * Map the packet for DMA * * Capture the first descriptor index, * this descriptor will have the index * of the EOP which is the only one that * now gets a DONE bit writeback. */ first = txr->next_avail_desc; tx_buffer = &txr->tx_buffers[first]; /* ** Make sure we don't overrun the ring, ** we need nsegs descriptors and one for ** the context descriptor used for the ** offloads. */ if (txr->tx_avail <= 2) { error = ENOSPC; goto unlock; } /* * Set up the context descriptor to specify * launchtimes for the packet. */ igb_tx_ctx_setup(txr, packet); /* * for performance monitoring, report the DMA time of the tx desc wb */ olinfo_status |= E1000_TXD_DMA_TXDWB; /* set payload length */ olinfo_status |= packet->len << E1000_ADVTXD_PAYLEN_SHIFT; /* Set up our transmit descriptors */ i = txr->next_avail_desc; /* we assume every packet is contiguous */ tx_buffer = &txr->tx_buffers[i]; txd = (union e1000_adv_tx_desc *)&txr->tx_base[i]; txd->read.buffer_addr = htole64(packet->map.paddr + packet->offset); txd->read.cmd_type_len = htole32(cmd_type_len | packet->len); txd->read.olinfo_status = htole32(olinfo_status); last = i; if (++i == adapter->num_tx_desc) i = 0; tx_buffer->packet = NULL; tx_buffer->next_eop = -1; txr->next_avail_desc = i; txr->tx_avail-- ; tx_buffer->packet = packet; /* * Last Descriptor of Packet * needs End Of Packet (EOP) * and Report Status (RS) */ txd->read.cmd_type_len |= htole32(E1000_ADVTXD_DCMD_EOP | E1000_ADVTXD_DCMD_RS); /* * Keep track in the first buffer which * descriptor will be written back */ tx_buffer = &txr->tx_buffers[first]; tx_buffer->next_eop = last; /* * Advance the Transmit Descriptor Tail (TDT), this tells the E1000 * that this frame is available to transmit. */ E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), i); ++txr->tx_packets; unlock: if( sem_post( adapter->memlock ) != 0 ) { return errno; } return(error); }
static int ixl_xmit(struct ixl_queue *que, struct mbuf **m_headp) { struct ixl_vsi *vsi = que->vsi; struct i40e_hw *hw = vsi->hw; struct tx_ring *txr = &que->txr; struct ixl_tx_buf *buf; struct i40e_tx_desc *txd = NULL; struct mbuf *m_head, *m; int i, j, error, nsegs, maxsegs; int first, last = 0; u16 vtag = 0; u32 cmd, off; bus_dmamap_t map; bus_dma_tag_t tag; bus_dma_segment_t segs[IXL_MAX_TSO_SEGS]; cmd = off = 0; m_head = *m_headp; /* * Important to capture the first descriptor * used because it will contain the index of * the one we tell the hardware to report back */ first = txr->next_avail; buf = &txr->buffers[first]; map = buf->map; tag = txr->tx_tag; maxsegs = IXL_MAX_TX_SEGS; if (m_head->m_pkthdr.csum_flags & CSUM_TSO) { /* Use larger mapping for TSO */ tag = txr->tso_tag; maxsegs = IXL_MAX_TSO_SEGS; if (ixl_tso_detect_sparse(m_head)) { m = m_defrag(m_head, M_NOWAIT); *m_headp = m; } } /* * Map the packet for DMA. */ error = bus_dmamap_load_mbuf_sg(tag, map, *m_headp, segs, &nsegs, BUS_DMA_NOWAIT); if (error == EFBIG) { struct mbuf *m; m = m_collapse(*m_headp, M_NOWAIT, maxsegs); if (m == NULL) { que->mbuf_defrag_failed++; m_freem(*m_headp); *m_headp = NULL; return (ENOBUFS); } *m_headp = m; /* Try it again */ error = bus_dmamap_load_mbuf_sg(tag, map, *m_headp, segs, &nsegs, BUS_DMA_NOWAIT); if (error == ENOMEM) { que->tx_dma_setup++; return (error); } else if (error != 0) { que->tx_dma_setup++; m_freem(*m_headp); *m_headp = NULL; return (error); } } else if (error == ENOMEM) { que->tx_dma_setup++; return (error); } else if (error != 0) { que->tx_dma_setup++; m_freem(*m_headp); *m_headp = NULL; return (error); } /* Make certain there are enough descriptors */ if (nsegs > txr->avail - 2) { txr->no_desc++; error = ENOBUFS; goto xmit_fail; } m_head = *m_headp; /* Set up the TSO/CSUM offload */ if (m_head->m_pkthdr.csum_flags & CSUM_OFFLOAD) { error = ixl_tx_setup_offload(que, m_head, &cmd, &off); if (error) goto xmit_fail; } cmd |= I40E_TX_DESC_CMD_ICRC; /* Grab the VLAN tag */ if (m_head->m_flags & M_VLANTAG) { cmd |= I40E_TX_DESC_CMD_IL2TAG1; vtag = htole16(m_head->m_pkthdr.ether_vtag); } i = txr->next_avail; for (j = 0; j < nsegs; j++) { bus_size_t seglen; buf = &txr->buffers[i]; buf->tag = tag; /* Keep track of the type tag */ txd = &txr->base[i]; seglen = segs[j].ds_len; txd->buffer_addr = htole64(segs[j].ds_addr); txd->cmd_type_offset_bsz = htole64(I40E_TX_DESC_DTYPE_DATA | ((u64)cmd << I40E_TXD_QW1_CMD_SHIFT) | ((u64)off << I40E_TXD_QW1_OFFSET_SHIFT) | ((u64)seglen << I40E_TXD_QW1_TX_BUF_SZ_SHIFT) | ((u64)vtag << I40E_TXD_QW1_L2TAG1_SHIFT)); last = i; /* descriptor that will get completion IRQ */ if (++i == que->num_desc) i = 0; buf->m_head = NULL; buf->eop_index = -1; } /* Set the last descriptor for report */ txd->cmd_type_offset_bsz |= htole64(((u64)IXL_TXD_CMD << I40E_TXD_QW1_CMD_SHIFT)); txr->avail -= nsegs; txr->next_avail = i; buf->m_head = m_head; /* Swap the dma map between the first and last descriptor */ txr->buffers[first].map = buf->map; buf->map = map; bus_dmamap_sync(tag, map, BUS_DMASYNC_PREWRITE); /* Set the index of the descriptor that will be marked done */ buf = &txr->buffers[first]; buf->eop_index = last; bus_dmamap_sync(txr->dma.tag, txr->dma.map, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE); /* * Advance the Transmit Descriptor Tail (Tdt), this tells the * hardware that this frame is available to transmit. */ ++txr->total_packets; wr32(hw, txr->tail, i); ixl_flush(hw); /* Mark outstanding work */ if (que->busy == 0) que->busy = 1; return (0); xmit_fail: bus_dmamap_unload(tag, buf->map); return (error); }
// make Local File Header chunk with extra fields ngx_chain_t* ngx_http_zip_file_header_chain_link(ngx_http_request_t *r, ngx_http_zip_ctx_t *ctx, ngx_http_zip_piece_t *piece, ngx_http_zip_range_t *range) { ngx_chain_t *link; ngx_buf_t *b; ngx_http_zip_file_t *file = piece->file; ngx_zip_extra_field_local_t extra_field_local; ngx_zip_extra_field_zip64_sizes_only_t extra_field_zip64; ngx_zip_local_file_header_t local_file_header; ngx_zip_extra_field_unicode_path_t extra_field_unicode_path; size_t len = sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t) + (file->need_zip64? sizeof(ngx_zip_extra_field_zip64_sizes_only_t):0 + (ctx->unicode_path && file->filename_utf8.len ? (sizeof(ngx_zip_extra_field_unicode_path_t) + file->filename_utf8.len): 0)); if ((link = ngx_alloc_chain_link(r->pool)) == NULL || (b = ngx_calloc_buf(r->pool)) == NULL || (b->pos = ngx_pcalloc(r->pool, len)) == NULL) return NULL; b->memory = 1; b->last = b->pos + len; /* A note about the ZIP format: in order to appease all ZIP software I * could find, the local file header contains the file sizes but not the * CRC-32, even though setting the third bit of the general purpose bit * flag would indicate that all three fields should be zeroed out. */ local_file_header = ngx_zip_local_file_header_template; local_file_header.signature = htole32(local_file_header.signature); local_file_header.version = htole16(local_file_header.version); local_file_header.flags = htole16(local_file_header.flags); local_file_header.mtime = htole32(file->dos_time); local_file_header.filename_len = htole16(file->filename.len); if (ctx->native_charset) { local_file_header.flags &= htole16(~zip_utf8_flag); } extra_field_zip64 = ngx_zip_extra_field_zip64_sizes_only_template; extra_field_zip64.tag = htole16(extra_field_zip64.tag); extra_field_zip64.size = htole16(extra_field_zip64.size); if (file->need_zip64) { local_file_header.version = htole16(zip_version_zip64); local_file_header.extra_field_len = sizeof(ngx_zip_extra_field_zip64_sizes_only_t) + sizeof(ngx_zip_extra_field_local_t); extra_field_zip64.uncompressed_size = extra_field_zip64.compressed_size = htole64(file->size); } else { local_file_header.compressed_size = htole32(file->size); local_file_header.uncompressed_size = htole32(file->size); } extra_field_unicode_path = ngx_zip_extra_field_unicode_path_template; extra_field_unicode_path.tag = htole16(extra_field_unicode_path.tag); if (ctx->unicode_path && file->filename_utf8.len) { extra_field_unicode_path.crc32 = htole32(file->filename_utf8_crc32); extra_field_unicode_path.size = htole16(sizeof(ngx_zip_extra_field_unicode_path_t) + file->filename_utf8.len); local_file_header.extra_field_len += sizeof(ngx_zip_extra_field_unicode_path_t) + file->filename_utf8.len; } local_file_header.extra_field_len = htole16(local_file_header.extra_field_len); if (!file->missing_crc32) { local_file_header.flags &= htole16(~zip_missing_crc32_flag); local_file_header.crc32 = htole32(file->crc32); } extra_field_local = ngx_zip_extra_field_local_template; extra_field_local.tag = htole16(extra_field_local.tag); extra_field_local.size = htole16(extra_field_local.size); extra_field_local.mtime = htole32(file->unix_time); extra_field_local.atime = htole32(file->unix_time); ngx_memcpy(b->pos, &local_file_header, sizeof(ngx_zip_local_file_header_t)); ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t), file->filename.data, file->filename.len); ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len, &extra_field_local, sizeof(ngx_zip_extra_field_local_t)); if (file->need_zip64) { ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t), &extra_field_zip64, sizeof(ngx_zip_extra_field_zip64_sizes_only_t)); if (ctx->unicode_path && file->filename_utf8.len) { ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t) + sizeof(ngx_zip_extra_field_zip64_sizes_only_t), &extra_field_unicode_path, sizeof(ngx_zip_extra_field_unicode_path_t)); ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t) + sizeof(ngx_zip_extra_field_zip64_sizes_only_t) + sizeof(ngx_zip_extra_field_unicode_path_t), file->filename_utf8.data, file->filename_utf8.len); } } else if (ctx->unicode_path && file->filename_utf8.len) { ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t), &extra_field_unicode_path, sizeof(ngx_zip_extra_field_unicode_path_t)); ngx_memcpy(b->pos + sizeof(ngx_zip_local_file_header_t) + file->filename.len + sizeof(ngx_zip_extra_field_local_t) + sizeof(ngx_zip_extra_field_unicode_path_t), file->filename_utf8.data, file->filename_utf8.len); } ngx_http_zip_truncate_buffer(b, &piece->range, range); link->buf = b; link->next = NULL; return link; }
/* * Allocate and setup an initial beacon frame. */ int ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ath_vap *avp = ATH_VAP(vap); struct ath_buf *bf; struct mbuf *m; int error; bf = avp->av_bcbuf; DPRINTF(sc, ATH_DEBUG_NODE, "%s: bf_m=%p, bf_node=%p\n", __func__, bf->bf_m, bf->bf_node); if (bf->bf_m != NULL) { bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap); m_freem(bf->bf_m); bf->bf_m = NULL; } if (bf->bf_node != NULL) { ieee80211_free_node(bf->bf_node); bf->bf_node = NULL; } /* * NB: the beacon data buffer must be 32-bit aligned; * we assume the mbuf routines will return us something * with this alignment (perhaps should assert). */ m = ieee80211_beacon_alloc(ni, &avp->av_boff); if (m == NULL) { device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__); sc->sc_stats.ast_be_nombuf++; return ENOMEM; } error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m, bf->bf_segs, &bf->bf_nseg, BUS_DMA_NOWAIT); if (error != 0) { device_printf(sc->sc_dev, "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n", __func__, error); m_freem(m); return error; } /* * Calculate a TSF adjustment factor required for staggered * beacons. Note that we assume the format of the beacon * frame leaves the tstamp field immediately following the * header. */ if (sc->sc_stagbeacons && avp->av_bslot > 0) { uint64_t tsfadjust; struct ieee80211_frame *wh; /* * The beacon interval is in TU's; the TSF is in usecs. * We figure out how many TU's to add to align the timestamp * then convert to TSF units and handle byte swapping before * inserting it in the frame. The hardware will then add this * each time a beacon frame is sent. Note that we align vap's * 1..N and leave vap 0 untouched. This means vap 0 has a * timestamp in one beacon interval while the others get a * timstamp aligned to the next interval. */ tsfadjust = ni->ni_intval * (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF; tsfadjust = htole64(tsfadjust << 10); /* TU -> TSF */ DPRINTF(sc, ATH_DEBUG_BEACON, "%s: %s beacons bslot %d intval %u tsfadjust %llu\n", __func__, sc->sc_stagbeacons ? "stagger" : "burst", avp->av_bslot, ni->ni_intval, (long long unsigned) le64toh(tsfadjust)); wh = mtod(m, struct ieee80211_frame *); memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust)); }
u_char * ngx_http_zip_write_central_directory_entry(u_char *p, ngx_http_zip_file_t *file, ngx_http_zip_ctx_t *ctx) { ngx_zip_extra_field_central_t extra_field_central; ngx_zip_central_directory_file_header_t central_directory_file_header; ngx_zip_extra_field_zip64_offset_only_t extra_zip64_offset; ngx_zip_extra_field_zip64_sizes_offset_t extra_zip64_offset_size; ngx_zip_extra_field_zip64_sizes_only_t extra_zip64_size; ngx_zip_extra_field_unicode_path_t extra_field_unicode_path; void* extra_zip64_ptr = NULL; //!! size_t extra_zip64_ptr_size = 0; central_directory_file_header = ngx_zip_central_directory_file_header_template; central_directory_file_header.signature = htole32(central_directory_file_header.signature); central_directory_file_header.version_made_by = htole16(central_directory_file_header.version_made_by); central_directory_file_header.version_needed = htole16(central_directory_file_header.version_needed); central_directory_file_header.flags = htole16(central_directory_file_header.flags); central_directory_file_header.attr_external = htole32(central_directory_file_header.attr_external); central_directory_file_header.mtime = htole32(file->dos_time); central_directory_file_header.crc32 = htole32(file->crc32); if (ctx->native_charset) { central_directory_file_header.flags &= htole16(~zip_utf8_flag); } if (!file->need_zip64) { central_directory_file_header.compressed_size = htole32(file->size); central_directory_file_header.uncompressed_size = htole32(file->size); } central_directory_file_header.filename_len = htole16(file->filename.len); if (!file->need_zip64_offset) central_directory_file_header.offset = htole32(file->offset); if (!file->missing_crc32) central_directory_file_header.flags &= htole16(~zip_missing_crc32_flag); if (file->need_zip64) { central_directory_file_header.version_needed = zip_version_zip64; if (file->need_zip64_offset){ extra_zip64_offset_size = ngx_zip_extra_field_zip64_sizes_offset_template; extra_zip64_offset_size.tag = htole16(extra_zip64_offset_size.tag); extra_zip64_offset_size.size = htole16(extra_zip64_offset_size.size); extra_zip64_offset_size.relative_header_offset = htole64(file->offset); extra_zip64_offset_size.compressed_size = extra_zip64_offset_size.uncompressed_size = htole64(file->size); extra_zip64_ptr = &extra_zip64_offset_size; extra_zip64_ptr_size = sizeof(extra_zip64_offset_size); } else { //zip64 only extra_zip64_size = ngx_zip_extra_field_zip64_sizes_only_template; extra_zip64_size.tag = htole16(extra_zip64_size.tag); extra_zip64_size.size = htole16(extra_zip64_size.size); extra_zip64_size.compressed_size = extra_zip64_size.uncompressed_size = htole64(file->size); extra_zip64_ptr = &extra_zip64_size; extra_zip64_ptr_size = sizeof(extra_zip64_size); } } else { if (file->need_zip64_offset){ extra_zip64_offset = ngx_zip_extra_field_zip64_offset_only_template; extra_zip64_offset.tag = htole16(extra_zip64_offset.tag); extra_zip64_offset.size = htole16(extra_zip64_offset.size); extra_zip64_offset.relative_header_offset = htole64(file->offset); extra_zip64_ptr = &extra_zip64_offset; extra_zip64_ptr_size = sizeof(extra_zip64_offset); } } central_directory_file_header.extra_field_len=sizeof(ngx_zip_extra_field_central_t)+extra_zip64_ptr_size; extra_field_central = ngx_zip_extra_field_central_template; extra_field_central.tag = htole16(extra_field_central.tag); extra_field_central.size = htole16(extra_field_central.size); extra_field_central.mtime = htole32(file->unix_time); extra_field_unicode_path = ngx_zip_extra_field_unicode_path_template; extra_field_unicode_path.tag = htole16(extra_field_unicode_path.tag); if (ctx->unicode_path && file->filename_utf8.len) { extra_field_unicode_path.crc32 = htole32(file->filename_utf8_crc32); extra_field_unicode_path.size = htole16(sizeof(ngx_zip_extra_field_unicode_path_t) + file->filename_utf8.len); central_directory_file_header.extra_field_len += sizeof(ngx_zip_extra_field_unicode_path_t) + file->filename_utf8.len; } central_directory_file_header.extra_field_len = htole16(central_directory_file_header.extra_field_len); ngx_memcpy(p, ¢ral_directory_file_header, sizeof(ngx_zip_central_directory_file_header_t)); p += sizeof(ngx_zip_central_directory_file_header_t); ngx_memcpy(p, file->filename.data, file->filename.len); p += file->filename.len; ngx_memcpy(p, &extra_field_central, sizeof(ngx_zip_extra_field_central_t)); p += sizeof(ngx_zip_extra_field_central_t); if (extra_zip64_ptr) { ngx_memcpy(p, extra_zip64_ptr, extra_zip64_ptr_size); p += extra_zip64_ptr_size; } if (ctx->unicode_path && file->filename_utf8.len) { ngx_memcpy(p, &extra_field_unicode_path, sizeof(ngx_zip_extra_field_unicode_path_t)); p += sizeof(ngx_zip_extra_field_unicode_path_t); ngx_memcpy(p, file->filename_utf8.data, file->filename_utf8.len); p += file->filename_utf8.len; } return p; }
int mb_put_int64le(struct mbchain *mbp, int64_t x) { x = htole64(x); return (mb_put_mem(mbp, (caddr_t)&x, sizeof(x), MB_MSYSTEM)); }
/** * Write up to size bytes to buf. Return negative on error, and number of * bytes written otherwise. The last case is a kind of an error too. */ static ssize_t write_entry(char *buf, size_t size, Uploader *u) { int r; size_t pos = 0; assert(size <= SSIZE_MAX); while (true) { switch(u->entry_state) { case ENTRY_CURSOR: { free(u->current_cursor); u->current_cursor = NULL; r = sd_journal_get_cursor(u->journal, &u->current_cursor); if (r < 0) return log_error_errno(r, "Failed to get cursor: %m"); r = snprintf(buf + pos, size - pos, "__CURSOR=%s\n", u->current_cursor); if (pos + r > size) /* not enough space */ return pos; u->entry_state ++; if (pos + r == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } /* fall through */ case ENTRY_REALTIME: { usec_t realtime; r = sd_journal_get_realtime_usec(u->journal, &realtime); if (r < 0) return log_error_errno(r, "Failed to get realtime timestamp: %m"); r = snprintf(buf + pos, size - pos, "__REALTIME_TIMESTAMP="USEC_FMT"\n", realtime); if (r + pos > size) /* not enough space */ return pos; u->entry_state ++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } /* fall through */ case ENTRY_MONOTONIC: { usec_t monotonic; sd_id128_t boot_id; r = sd_journal_get_monotonic_usec(u->journal, &monotonic, &boot_id); if (r < 0) return log_error_errno(r, "Failed to get monotonic timestamp: %m"); r = snprintf(buf + pos, size - pos, "__MONOTONIC_TIMESTAMP="USEC_FMT"\n", monotonic); if (r + pos > size) /* not enough space */ return pos; u->entry_state ++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } /* fall through */ case ENTRY_BOOT_ID: { sd_id128_t boot_id; char sid[33]; r = sd_journal_get_monotonic_usec(u->journal, NULL, &boot_id); if (r < 0) return log_error_errno(r, "Failed to get monotonic timestamp: %m"); r = snprintf(buf + pos, size - pos, "_BOOT_ID=%s\n", sd_id128_to_string(boot_id, sid)); if (r + pos > size) /* not enough space */ return pos; u->entry_state ++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } /* fall through */ case ENTRY_NEW_FIELD: { u->field_pos = 0; r = sd_journal_enumerate_data(u->journal, &u->field_data, &u->field_length); if (r < 0) return log_error_errno(r, "Failed to move to next field in entry: %m"); else if (r == 0) { u->entry_state = ENTRY_OUTRO; continue; } if (!utf8_is_printable_newline(u->field_data, u->field_length, false)) { u->entry_state = ENTRY_BINARY_FIELD_START; continue; } u->entry_state ++; } /* fall through */ case ENTRY_TEXT_FIELD: case ENTRY_BINARY_FIELD: { bool done; size_t tocopy; done = size - pos > u->field_length - u->field_pos; if (done) tocopy = u->field_length - u->field_pos; else tocopy = size - pos; memcpy(buf + pos, (char*) u->field_data + u->field_pos, tocopy); if (done) { buf[pos + tocopy] = '\n'; pos += tocopy + 1; u->entry_state = ENTRY_NEW_FIELD; continue; } else { u->field_pos += tocopy; return size; } } case ENTRY_BINARY_FIELD_START: { const char *c; size_t len; c = memchr(u->field_data, '=', u->field_length); if (!c || c == u->field_data) { log_error("Invalid field."); return -EINVAL; } len = c - (const char*)u->field_data; /* need space for label + '\n' */ if (size - pos < len + 1) return pos; memcpy(buf + pos, u->field_data, len); buf[pos + len] = '\n'; pos += len + 1; u->field_pos = len + 1; u->entry_state ++; } /* fall through */ case ENTRY_BINARY_FIELD_SIZE: { uint64_t le64; /* need space for uint64_t */ if (size - pos < 8) return pos; le64 = htole64(u->field_length - u->field_pos); memcpy(buf + pos, &le64, 8); pos += 8; u->entry_state ++; continue; } case ENTRY_OUTRO: /* need space for '\n' */ if (size - pos < 1) return pos; buf[pos++] = '\n'; u->entry_state ++; u->entries_sent ++; return pos; default: assert_not_reached("WTF?"); } } assert_not_reached("WTF?"); }
template <> inline uint64_t host_to <uint64_t, little_endian>(uint64_t value) { return htole64(value); }
static void test_message_handler(void) { _cleanup_(sd_dhcp_server_unrefp) sd_dhcp_server *server = NULL; struct { DHCPMessage message; struct { uint8_t code; uint8_t length; uint8_t type; } _packed_ option_type; struct { uint8_t code; uint8_t length; be32_t address; } _packed_ option_requested_ip; struct { uint8_t code; uint8_t length; be32_t address; } _packed_ option_server_id; struct { uint8_t code; uint8_t length; uint8_t id[7]; } _packed_ option_client_id; uint8_t end; } _packed_ test = { .message.op = BOOTREQUEST, .message.htype = ARPHRD_ETHER, .message.hlen = ETHER_ADDR_LEN, .message.xid = htobe32(0x12345678), .message.chaddr = { 'A', 'B', 'C', 'D', 'E', 'F' }, .option_type.code = SD_DHCP_OPTION_MESSAGE_TYPE, .option_type.length = 1, .option_type.type = DHCP_DISCOVER, .end = SD_DHCP_OPTION_END, }; struct in_addr address_lo = { .s_addr = htonl(INADDR_LOOPBACK), }; assert_se(sd_dhcp_server_new(&server, 1) >= 0); assert_se(sd_dhcp_server_configure_pool(server, &address_lo, 8, 0, 0) >= 0); assert_se(sd_dhcp_server_attach_event(server, NULL, 0) >= 0); assert_se(sd_dhcp_server_start(server) >= 0); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.end = 0; /* TODO, shouldn't this fail? */ assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.end = SD_DHCP_OPTION_END; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.option_type.code = 0; test.option_type.length = 0; test.option_type.type = 0; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.option_type.code = SD_DHCP_OPTION_MESSAGE_TYPE; test.option_type.length = 1; test.option_type.type = DHCP_DISCOVER; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.message.op = 0; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.message.op = BOOTREQUEST; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.message.htype = 0; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.message.htype = ARPHRD_ETHER; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.message.hlen = 0; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.message.hlen = ETHER_ADDR_LEN; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_OFFER); test.option_type.type = DHCP_REQUEST; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.option_requested_ip.code = SD_DHCP_OPTION_REQUESTED_IP_ADDRESS; test.option_requested_ip.length = 4; test.option_requested_ip.address = htobe32(0x12345678); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_NAK); test.option_server_id.code = SD_DHCP_OPTION_SERVER_IDENTIFIER; test.option_server_id.length = 4; test.option_server_id.address = htobe32(INADDR_LOOPBACK); test.option_requested_ip.address = htobe32(INADDR_LOOPBACK + 3); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_ACK); test.option_server_id.address = htobe32(0x12345678); test.option_requested_ip.address = htobe32(INADDR_LOOPBACK + 3); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.option_server_id.address = htobe32(INADDR_LOOPBACK); test.option_requested_ip.address = htobe32(INADDR_LOOPBACK + 4); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); test.option_requested_ip.address = htobe32(INADDR_LOOPBACK + 3); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_ACK); test.option_client_id.code = SD_DHCP_OPTION_CLIENT_IDENTIFIER; test.option_client_id.length = 7; test.option_client_id.id[0] = 0x01; test.option_client_id.id[1] = 'A'; test.option_client_id.id[2] = 'B'; test.option_client_id.id[3] = 'C'; test.option_client_id.id[4] = 'D'; test.option_client_id.id[5] = 'E'; test.option_client_id.id[6] = 'F'; assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == DHCP_ACK); test.option_requested_ip.address = htobe32(INADDR_LOOPBACK + 30); assert_se(dhcp_server_handle_message(server, (DHCPMessage*)&test, sizeof(test)) == 0); } static uint64_t client_id_hash_helper(DHCPClientId *id, uint8_t key[HASH_KEY_SIZE]) { struct siphash state; siphash24_init(&state, key); client_id_hash_func(id, &state); return htole64(siphash24_finalize(&state)); } static void test_client_id_hash(void) { DHCPClientId a = { .length = 4, }, b = {
template <> inline int64_t host_to <int64_t, little_endian>(int64_t value) { return (int64_t)htole64((uint64_t)value); }
static int statsdWrite(struct timespec* ts, struct iovec* vec, size_t nr) { ssize_t ret; int sock; static const unsigned headerLength = 1; struct iovec newVec[nr + headerLength]; android_log_header_t header; size_t i, payloadSize; sock = atomic_load(&statsdLoggerWrite.sock); if (sock < 0) switch (sock) { case -ENOTCONN: case -ECONNREFUSED: case -ENOENT: break; default: return -EBADF; } /* * struct { * // what we provide to socket * android_log_header_t header; * // caller provides * union { * struct { * char prio; * char payload[]; * } string; * struct { * uint32_t tag * char payload[]; * } binary; * }; * }; */ header.tid = gettid(); header.realtime.tv_sec = ts->tv_sec; header.realtime.tv_nsec = ts->tv_nsec; newVec[0].iov_base = (unsigned char*)&header; newVec[0].iov_len = sizeof(header); // If we dropped events before, try to tell statsd. if (sock >= 0) { int32_t snapshot = atomic_exchange_explicit(&dropped, 0, memory_order_relaxed); if (snapshot) { android_log_event_long_t buffer; header.id = LOG_ID_STATS; // store the last log error in the tag field. This tag field is not used by statsd. buffer.header.tag = htole32(atomic_load(&log_error)); buffer.payload.type = EVENT_TYPE_LONG; // format: // |atom_tag|dropped_count| int64_t composed_long = atomic_load(&atom_tag); // Send 2 int32's via an int64. composed_long = ((composed_long << 32) | ((int64_t)snapshot)); buffer.payload.data = htole64(composed_long); newVec[headerLength].iov_base = &buffer; newVec[headerLength].iov_len = sizeof(buffer); ret = TEMP_FAILURE_RETRY(writev(sock, newVec, 2)); if (ret != (ssize_t)(sizeof(header) + sizeof(buffer))) { atomic_fetch_add_explicit(&dropped, snapshot, memory_order_relaxed); } } } header.id = LOG_ID_STATS; for (payloadSize = 0, i = headerLength; i < nr + headerLength; i++) { newVec[i].iov_base = vec[i - headerLength].iov_base; payloadSize += newVec[i].iov_len = vec[i - headerLength].iov_len; if (payloadSize > LOGGER_ENTRY_MAX_PAYLOAD) { newVec[i].iov_len -= payloadSize - LOGGER_ENTRY_MAX_PAYLOAD; if (newVec[i].iov_len) { ++i; } break; } } /* * The write below could be lost, but will never block. * * ENOTCONN occurs if statsd has died. * ENOENT occurs if statsd is not running and socket is missing. * ECONNREFUSED occurs if we can not reconnect to statsd. * EAGAIN occurs if statsd is overloaded. */ if (sock < 0) { ret = sock; } else { ret = TEMP_FAILURE_RETRY(writev(sock, newVec, i)); if (ret < 0) { ret = -errno; } } switch (ret) { case -ENOTCONN: case -ECONNREFUSED: case -ENOENT: if (statd_writer_trylock()) { return ret; /* in a signal handler? try again when less stressed */ } __statsdClose(ret); ret = statsdOpen(); statsd_writer_init_unlock(); if (ret < 0) { return ret; } ret = TEMP_FAILURE_RETRY(writev(atomic_load(&statsdLoggerWrite.sock), newVec, i)); if (ret < 0) { ret = -errno; } /* FALLTHRU */ default: break; } if (ret > (ssize_t)sizeof(header)) { ret -= sizeof(header); } return ret; }
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; }
static int64_t trie_store_nodes(struct trie_f *trie, struct trie_node *node) { uint64_t i; struct trie_node_f n = { .prefix_off = htole64(trie->strings_off + node->prefix_off), .children_count = node->children_count, .values_count = htole64(node->values_count), }; struct trie_child_entry_f *children = NULL; int64_t node_off; if (node->children_count) { children = new0(struct trie_child_entry_f, node->children_count); if (!children) return -ENOMEM; } /* post-order recursion */ for (i = 0; i < node->children_count; i++) { int64_t child_off; child_off = trie_store_nodes(trie, node->children[i].child); if (child_off < 0) return child_off; children[i].c = node->children[i].c; children[i].child_off = htole64(child_off); } /* write node */ node_off = ftello(trie->f); fwrite(&n, sizeof(struct trie_node_f), 1, trie->f); trie->nodes_count++; /* append children array */ if (node->children_count) { fwrite(children, sizeof(struct trie_child_entry_f), node->children_count, trie->f); trie->children_count += node->children_count; free(children); } /* append values array */ for (i = 0; i < node->values_count; i++) { struct trie_value_entry_f v = { .key_off = htole64(trie->strings_off + node->values[i].key_off), .value_off = htole64(trie->strings_off + node->values[i].value_off), }; fwrite(&v, sizeof(struct trie_value_entry_f), 1, trie->f); trie->values_count++; } return node_off; } static int trie_store(struct trie *trie, const char *filename) { struct trie_f t = { .trie = trie, }; char *filename_tmp; int64_t pos; int64_t root_off; int64_t size; struct trie_header_f h = { .signature = HWDB_SIG, .tool_version = htole64(atoi(VERSION)), .header_size = htole64(sizeof(struct trie_header_f)), .node_size = htole64(sizeof(struct trie_node_f)), .child_entry_size = htole64(sizeof(struct trie_child_entry_f)), .value_entry_size = htole64(sizeof(struct trie_value_entry_f)), }; int err; /* calculate size of header, nodes, children entries, value entries */ t.strings_off = sizeof(struct trie_header_f); trie_store_nodes_size(&t, trie->root); err = fopen_temporary(filename , &t.f, &filename_tmp); if (err < 0) return err; fchmod(fileno(t.f), 0444); /* write nodes */ fseeko(t.f, sizeof(struct trie_header_f), SEEK_SET); root_off = trie_store_nodes(&t, trie->root); h.nodes_root_off = htole64(root_off); pos = ftello(t.f); h.nodes_len = htole64(pos - sizeof(struct trie_header_f)); /* write string buffer */ fwrite(trie->strings->buf, trie->strings->len, 1, t.f); h.strings_len = htole64(trie->strings->len); /* write header */ size = ftello(t.f); h.file_size = htole64(size); fseeko(t.f, 0, SEEK_SET); fwrite(&h, sizeof(struct trie_header_f), 1, t.f); err = ferror(t.f); if (err) err = -errno; fclose(t.f); if (err < 0 || rename(filename_tmp, filename) < 0) { unlink(filename_tmp); goto out; } log_debug("=== trie on-disk ===\n"); log_debug("size: %8llu bytes\n", (unsigned long long)size); log_debug("header: %8zu bytes\n", sizeof(struct trie_header_f)); log_debug("nodes: %8llu bytes (%8llu)\n", (unsigned long long)t.nodes_count * sizeof(struct trie_node_f), (unsigned long long)t.nodes_count); log_debug("child pointers: %8llu bytes (%8llu)\n", (unsigned long long)t.children_count * sizeof(struct trie_child_entry_f), (unsigned long long)t.children_count); log_debug("value pointers: %8llu bytes (%8llu)\n", (unsigned long long)t.values_count * sizeof(struct trie_value_entry_f), (unsigned long long)t.values_count); log_debug("string store: %8llu bytes\n", (unsigned long long)trie->strings->len); log_debug("strings start: %8llu\n", (unsigned long long) t.strings_off); out: free(filename_tmp); return err; } static int import_file(struct trie *trie, const char *filename) { FILE *f; char line[LINE_MAX]; char match[LINE_MAX]; char cond[LINE_MAX]; f = fopen(filename, "re"); if (f == NULL) return -errno; match[0] = '\0'; cond[0] = '\0'; while (fgets(line, sizeof(line), f)) { size_t len; if (line[0] == '#') continue; /* new line, new record */ if (line[0] == '\n') { match[0] = '\0'; cond[0] = '\0'; continue; } /* remove newline */ len = strlen(line); if (len < 2) continue; line[len-1] = '\0'; /* start of new record */ if (match[0] == '\0') { strcpy(match, line); cond[0] = '\0'; continue; } if (line[0] == '+') { strcpy(cond, line); continue; } /* TODO: support +; skip the entire record until we support it */ if (cond[0] != '\0') continue; /* value lines */ if (line[0] == ' ') { char *value; value = strchr(line, '='); if (!value) continue; value[0] = '\0'; value++; trie_insert(trie, trie->root, match, line, value); } } fclose(f); return 0; } static void help(void) { printf("Usage: udevadm hwdb OPTIONS\n" " --update update the hardware database\n" " --test=<modalias> query database and print result\n" " --root=<path> alternative root path in the filesystem\n" " --help\n\n"); }
static int migrate(gpt_t gpt, u_int parts, int force, int slice, int active) { off_t last = gpt_last(gpt); map_t map; struct gpt_ent *ent; struct mbr *mbr; uint32_t start, size; unsigned int i; gpt_type_t type = GPT_TYPE_INVALID; map = map_find(gpt, MAP_TYPE_MBR); if (map == NULL || map->map_start != 0) { gpt_warnx(gpt, "No MBR in disk to convert"); return -1; } mbr = map->map_data; if (gpt_create(gpt, last, parts, 0) == -1) return -1; ent = gpt->tbl->map_data; /* Mirror partitions. */ for (i = 0; i < 4; i++) { start = le16toh(mbr->mbr_part[i].part_start_hi); start = (start << 16) + le16toh(mbr->mbr_part[i].part_start_lo); size = le16toh(mbr->mbr_part[i].part_size_hi); size = (size << 16) + le16toh(mbr->mbr_part[i].part_size_lo); if (gpt->verbose > 1) gpt_msg(gpt, "MBR partition %u type %s", i, mbrptypename(mbr->mbr_part[i].part_typ)); switch (mbr->mbr_part[i].part_typ) { case MBR_PTYPE_UNUSED: continue; case MBR_PTYPE_386BSD: /* FreeBSD */ if (slice) { type = GPT_TYPE_FREEBSD; break; } else { ent = migrate_disklabel(gpt, start, ent, freebsd_fstype_to_gpt_type); continue; } case MBR_PTYPE_NETBSD: /* NetBSD */ ent = migrate_disklabel(gpt, start, ent, netbsd_fstype_to_gpt_type); continue; case MBR_PTYPE_EFI: type = GPT_TYPE_EFI; break; default: if (!force) { gpt_warnx(gpt, "unknown partition type (%d)", mbr->mbr_part[i].part_typ); return -1; } continue; } gpt_uuid_create(type, ent->ent_type, ent->ent_name, sizeof(ent->ent_name)); ent->ent_lba_start = htole64((uint64_t)start); ent->ent_lba_end = htole64((uint64_t)(start + size - 1LL)); ent++; } if (gpt_write_primary(gpt) == -1) return -1; if (gpt_write_backup(gpt) == -1) return -1; /* * Turn the MBR into a Protective MBR. */ memset(mbr->mbr_part, 0, sizeof(mbr->mbr_part)); gpt_create_pmbr_part(mbr->mbr_part, last, active); if (gpt_write(gpt, map) == -1) { gpt_warn(gpt, "Cant write PMBR"); return -1; } return 0; }