repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
criu
|
criu-master/test/zdtm/static/netns-dev.c
|
#include <unistd.h>
#include <stdlib.h>
#include <linux/limits.h>
#include "zdtmtst.h"
#define LO_CONF_DIR_PATH "/proc/sys/net/ipv4/conf/lo"
#define DEF_CONF_DIR_PATH "/proc/sys/net/ipv4/conf/default"
#define ALL_CONF_DIR_PATH "/proc/sys/net/ipv4/conf/all"
#define LO_CONF6_DIR_PATH "/proc/sys/net/ipv6/conf/lo"
#define DEF_CONF6_DIR_PATH "/proc/sys/net/ipv6/conf/default"
#define ALL_CONF6_DIR_PATH "/proc/sys/net/ipv6/conf/all"
#define INT_MAX ((int)(~0U >> 1))
#define INT_MIN (-INT_MAX - 1)
char *devconfs4[] = {
"accept_local",
"accept_source_route",
"arp_accept",
"arp_announce",
"arp_filter",
"arp_ignore",
"arp_notify",
"bootp_relay",
"disable_policy",
"disable_xfrm",
"drop_gratuitous_arp",
"drop_unicast_in_l2_multicast",
"force_igmp_version",
"forwarding",
"accept_redirects",
"igmpv2_unsolicited_report_interval",
"igmpv3_unsolicited_report_interval",
"ignore_routes_with_linkdown",
"log_martians",
"mc_forwarding",
"medium_id",
"promote_secondaries",
"proxy_arp",
"proxy_arp_pvlan",
"route_localnet",
"rp_filter",
"secure_redirects",
"send_redirects",
"shared_media",
"src_valid_mark",
"tag",
NULL,
};
struct range {
int min;
int max;
};
struct range rand_range4[] = {
{ 0, 1 }, /* accept_local */
{ -1, 0 }, /* accept_source_route */
{ 0, 1 }, /* arp_accept */
{ 0, 2 }, /* arp_announce */
{ 0, 1 }, /* arp_filter */
{ 0, 8 }, /* arp_ignore */
{ 0, 1 }, /* arp_notify */
{ 0, 1 }, /* bootp_relay */
{ 0, 1 }, /* disable_policy */
{ 0, 1 }, /* disable_xfrm */
{ 0, 1 }, /* drop_gratuitous_arp */
{ 0, 1 }, /* drop_unicast_in_l2_multicast */
{ 0, INT_MAX }, /* force_igmp_version */
{ 0, 1 }, /* forwarding */
{ 0, 1 }, /* accept_redirects */
{ 0, INT_MAX }, /* igmpv2_unsolicited_report_interval */
{ 0, INT_MAX }, /* igmpv3_unsolicited_report_interval */
{ 0, 1 }, /* ignore_routes_with_linkdown */
{ 0, 1 }, /* log_martians */
{ 0, 1 }, /* mc_forwarding */
{ -1, INT_MAX }, /* medium_id */
{ 0, 1 }, /* promote_secondaries */
{ 0, 1 }, /* proxy_arp */
{ 0, 1 }, /* proxy_arp_pvlan */
{ 0, 1 }, /* route_localnet */
{ 0, 2 }, /* rp_filter */
{ 0, 1 }, /* secure_redirects */
{ 0, 1 }, /* send_redirects */
{ 0, 1 }, /* shared_media */
{ 0, 1 }, /* src_valid_mark */
{ INT_MIN, INT_MAX }, /* tag */
};
char *devconfs6[] = {
"accept_dad",
"accept_ra",
"accept_ra_defrtr",
"accept_ra_from_local",
"accept_ra_min_hop_limit",
"accept_ra_mtu",
"accept_ra_pinfo",
"accept_ra_rt_info_max_plen",
"accept_ra_rtr_pref",
"accept_source_route",
"autoconf",
"dad_transmits",
"disable_ipv6",
"drop_unicast_in_l2_multicast",
"drop_unsolicited_na",
"force_mld_version",
"force_tllao",
"forwarding",
"accept_redirects",
"hop_limit",
"ignore_routes_with_linkdown",
"keep_addr_on_down",
"max_addresses",
"max_desync_factor",
"mldv1_unsolicited_report_interval",
"mldv2_unsolicited_report_interval",
"mtu",
"ndisc_notify",
"optimistic_dad",
"proxy_ndp",
"regen_max_retry",
"router_probe_interval",
"router_solicitation_delay",
"router_solicitation_interval",
"router_solicitations",
"suppress_frag_ndisc",
"temp_prefered_lft",
"temp_valid_lft",
"use_oif_addrs_only",
"use_optimistic",
"use_tempaddr",
NULL,
};
#define IPV6_MIN_MTU 1280
#define ROUTER_MAX 60
/* According to kernel docs do not make max_addresses too large */
#define MAX_ADDRESSES 128
struct range rand_range6[] = {
{ 0, 2 }, /* accept_dad */
{ 0, 2 }, /* accept_ra */
{ 0, 1 }, /* accept_ra_defrtr */
{ 0, 1 }, /* accept_ra_from_local */
{ 0, INT_MAX }, /* accept_ra_min_hop_limit */
{ 0, 1 }, /* accept_ra_mtu */
{ 0, 1 }, /* accept_ra_pinfo */
{ 0, INT_MAX }, /* accept_ra_rt_info_max_plen */
{ 0, 1 }, /* accept_ra_rtr_pref */
{ -1, 0 }, /* accept_source_route */
{ 0, 1 }, /* autoconf */
{ 0, INT_MAX }, /* dad_transmits */
{ 0, 1 }, /* disable_ipv6 */
{ 0, 1 }, /* drop_unicast_in_l2_multicast */
{ 0, 1 }, /* drop_unsolicited_na */
{ 0, 2 }, /* force_mld_version */
{ 0, 1 }, /* force_tllao */
{ 0, 1 }, /* forwarding */
{ 0, 1 }, /* accept_redirects */
{ 1, 255 }, /* hop_limit */
{ 0, 1 }, /* ignore_routes_with_linkdown */
{ -1, 1 }, /* keep_addr_on_down */
{ 0, MAX_ADDRESSES }, /* max_addresses */
{ 0, INT_MAX }, /* max_desync_factor */
{ 0, INT_MAX }, /* mldv1_unsolicited_report_interval */
{ 0, INT_MAX }, /* mldv2_unsolicited_report_interval */
{ IPV6_MIN_MTU, IPV6_MIN_MTU }, /* mtu */
{ 0, 1 }, /* ndisc_notify */
{ 0, 1 }, /* optimistic_dad */
{ 0, 1 }, /* proxy_ndp */
{ 0, INT_MAX }, /* regen_max_retry */
{ 0, ROUTER_MAX }, /* router_probe_interval */
{ 0, ROUTER_MAX }, /* router_solicitation_delay */
{ 0, ROUTER_MAX }, /* router_solicitation_interval */
{ 0, ROUTER_MAX }, /* router_solicitations */
{ 0, 1 }, /* suppress_frag_ndisc */
{ 0, INT_MAX }, /* temp_prefered_lft */
{ 0, INT_MAX }, /* temp_valid_lft */
{ 0, 1 }, /* use_oif_addrs_only */
{ 0, 1 }, /* use_optimistic */
{ 0, 2 }, /* use_tempaddr */
};
struct test_conf {
int ipv4_conf[ARRAY_SIZE(devconfs4)];
int ipv4_conf_rand[ARRAY_SIZE(devconfs4)];
int ipv6_conf[ARRAY_SIZE(devconfs6)];
int ipv6_conf_rand[ARRAY_SIZE(devconfs6)];
char *dir4;
char *dir6;
} lo, def, all;
static int save_conf(FILE *fp, int *conf, int *conf_rand, struct range *range, char *path)
{
int ret;
/*
* Save
*/
ret = fscanf(fp, "%d", conf);
if (ret != 1) {
pr_perror("fscanf");
return -1;
}
return 0;
}
static int rand_in_small_range(struct range *r)
{
return lrand48() % (r->max - r->min + 1) + r->min;
}
static int rand_in_range(struct range *r)
{
struct range small;
int mid = r->max / 2 + r->min / 2;
int half = r->max / 2 - r->min / 2;
if (half < INT_MAX / 2)
return rand_in_small_range(r);
if (lrand48() % 2) {
small.min = r->min;
small.max = mid;
} else {
small.min = mid + 1;
small.max = r->max;
}
return rand_in_small_range(&small);
}
static int gen_conf(FILE *fp, int *conf, int *conf_rand, struct range *range, char *path)
{
int ret;
/*
* Set random value
*/
*conf_rand = rand_in_range(range);
ret = fprintf(fp, "%d", *conf_rand);
if (ret < 0) {
pr_perror("fprintf");
return -1;
}
return 0;
}
#define MAX_MSEC_GRANULARITY 10
static int check_conf(FILE *fp, int *conf, int *conf_rand, struct range *range, char *path)
{
int ret;
int val;
/*
* Check opt
*/
ret = fscanf(fp, "%d", &val);
if (ret != 1) {
pr_perror("fscanf");
return -1;
}
if (val != *conf_rand) {
fail("Option \"%s\" changed from %d to %d", path, *conf_rand, val);
if ((strstr(path, "mldv1_unsolicited_report_interval") ||
strstr(path, "mldv2_unsolicited_report_interval")) &&
val - *conf_rand < MAX_MSEC_GRANULARITY)
return 0;
return -1;
}
return 0;
}
static int restore_conf(FILE *fp, int *conf, int *conf_rand, struct range *range, char *path)
{
int ret;
/*
* Restore opt
*/
ret = fprintf(fp, "%d", *conf);
if (ret < 0) {
pr_perror("fprintf");
return -1;
}
return 0;
}
static int for_each_option_do(int (*f)(FILE *fp, int *conf, int *conf_rand, struct range *range, char *path),
struct test_conf *tc)
{
int ret;
int i;
for (i = 0; devconfs4[i]; i++) {
FILE *fp;
char path[PATH_MAX];
ret = snprintf(path, sizeof(path), "%s/%s", tc->dir4, devconfs4[i]);
if (ret < 0) {
pr_perror("snprintf");
return -1;
}
ret = access(path, W_OK);
if (ret < 0)
continue;
fp = fopen(path, "r+");
if (fp == NULL) {
pr_perror("fopen");
return -1;
}
ret = (*f)(fp, &tc->ipv4_conf[i], &tc->ipv4_conf_rand[i], &rand_range4[i], path);
if (ret < 0)
return -1;
fclose(fp);
}
for (i = 0; devconfs6[i]; i++) {
FILE *fp;
char path[PATH_MAX];
ret = snprintf(path, sizeof(path), "%s/%s", tc->dir6, devconfs6[i]);
if (ret < 0) {
pr_perror("snprintf");
return -1;
}
ret = access(path, W_OK);
if (ret < 0)
continue;
fp = fopen(path, "r+");
if (fp == NULL) {
pr_perror("fopen");
return -1;
}
ret = (*f)(fp, &tc->ipv6_conf[i], &tc->ipv6_conf_rand[i], &rand_range6[i], path);
if (ret < 0)
return -1;
fclose(fp);
}
return 0;
}
#define IPV6ADDR_EXAMPLE "2607:f0d0:1002:0051:0000:0000:0000:0004"
#define MAX_STR_CONF_LEN 200
static int set_stable_secret(struct test_conf *tc)
{
int ret;
FILE *fp;
char path[PATH_MAX];
ret = snprintf(path, sizeof(path), "%s/%s", tc->dir6, "stable_secret");
if (ret < 0) {
pr_perror("snprintf");
return -1;
}
ret = access(path, W_OK);
if (ret < 0)
return 0;
fp = fopen(path, "r+");
if (fp == NULL) {
pr_perror("fopen");
return -1;
}
ret = fprintf(fp, IPV6ADDR_EXAMPLE);
if (ret < 0) {
pr_perror("fprintf");
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
static int check_stable_secret(struct test_conf *tc)
{
int ret;
FILE *fp;
char path[PATH_MAX];
char val[MAX_STR_CONF_LEN + 1];
ret = snprintf(path, sizeof(path), "%s/%s", tc->dir6, "stable_secret");
if (ret < 0) {
pr_perror("snprintf");
return -1;
}
ret = access(path, W_OK);
if (ret < 0)
return 0;
fp = fopen(path, "r+");
if (fp == NULL) {
pr_perror("fopen");
return -1;
}
ret = fscanf(fp, "%s", val);
if (ret != 1) {
pr_perror("fscanf");
fclose(fp);
return -1;
}
if (strcmp(val, IPV6ADDR_EXAMPLE)) {
fail("Option \"%s\" changed from %s to %s", path, IPV6ADDR_EXAMPLE, val);
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
int main(int argc, char **argv)
{
int ret;
lo.dir4 = LO_CONF_DIR_PATH;
def.dir4 = DEF_CONF_DIR_PATH;
all.dir4 = ALL_CONF_DIR_PATH;
lo.dir6 = LO_CONF6_DIR_PATH;
def.dir6 = DEF_CONF6_DIR_PATH;
all.dir6 = ALL_CONF6_DIR_PATH;
test_init(argc, argv);
ret = for_each_option_do(save_conf, &all);
if (ret < 0)
return -1;
ret = for_each_option_do(save_conf, &def);
if (ret < 0)
return -1;
ret = for_each_option_do(save_conf, &lo);
if (ret < 0)
return -1;
ret = for_each_option_do(gen_conf, &all);
if (ret < 0)
return -1;
ret = for_each_option_do(gen_conf, &def);
if (ret < 0)
return -1;
ret = for_each_option_do(gen_conf, &lo);
if (ret < 0)
return -1;
ret = set_stable_secret(&def);
if (ret < 0)
return -1;
ret = set_stable_secret(&lo);
if (ret < 0)
return -1;
test_daemon();
test_waitsig();
ret = for_each_option_do(check_conf, &all);
if (ret < 0)
return -1;
ret = for_each_option_do(check_conf, &def);
if (ret < 0)
return -1;
ret = for_each_option_do(check_conf, &lo);
if (ret < 0)
return -1;
ret = for_each_option_do(restore_conf, &all);
if (ret < 0)
return -1;
ret = for_each_option_do(restore_conf, &def);
if (ret < 0)
return -1;
ret = for_each_option_do(restore_conf, &lo);
if (ret < 0)
return -1;
ret = check_stable_secret(&def);
if (ret < 0)
return -1;
ret = check_stable_secret(&lo);
if (ret < 0)
return -1;
pass();
return 0;
}
| 11,032 | 20.761341 | 109 |
c
|
criu
|
criu-master/test/zdtm/static/netns-nft-ipt.c
|
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "zdtmtst.h"
const char *test_doc = "Check that both nftables & iptables rules (some) are C/R properly";
const char *test_author = "Alexander Mikhalitsyn <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
int main(int argc, char **argv)
{
char cmd[128];
test_init(argc, argv);
/* create nft table */
if (system("nft add table inet netns-nft-zdtm-test")) {
pr_perror("Can't create nft table");
return -1;
}
/* create input chain in table */
if (system("nft add chain inet netns-nft-zdtm-test input { type filter hook input priority 0 \\; }")) {
pr_perror("Can't create input chain in nft table");
return -1;
}
/* block ICMPv4 traffic */
if (system("nft add rule inet netns-nft-zdtm-test input meta nfproto ipv4 icmp type { echo-request } reject")) {
pr_perror("Can't set input rule");
return -1;
}
/* save resulting nft table */
sprintf(cmd, "nft list table inet netns-nft-zdtm-test > pre-%s", filename);
if (system(cmd)) {
pr_perror("Can't get nft table");
return -1;
}
if (system("iptables -A INPUT -t filter --protocol icmp -j DROP")) {
pr_perror("Can't set input rule");
return -1;
}
sprintf(cmd, "iptables -L >> pre-%s", filename);
if (system(cmd)) {
pr_perror("Can't save iptables");
return -1;
}
test_daemon();
test_waitsig();
/* get nft table */
sprintf(cmd, "nft list table inet netns-nft-zdtm-test > post-%s", filename);
if (system(cmd)) {
fail("Can't get nft table");
return -1;
}
sprintf(cmd, "iptables -L >> post-%s", filename);
if (system(cmd)) {
fail("Can't get iptables");
return -1;
}
/* compare nft table before/after c/r */
sprintf(cmd, "diff pre-%s post-%s", filename, filename);
if (system(cmd)) {
fail("nft table differ");
return -1;
}
pass();
return 0;
}
| 1,891 | 22.073171 | 113 |
c
|
criu
|
criu-master/test/zdtm/static/netns-nft.c
|
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include "zdtmtst.h"
const char *test_doc = "Check that nft rules (some) are kept";
const char *test_author = "Alexander Mikhalitsyn <[email protected]>";
char *filename;
TEST_OPTION(filename, string, "file name", 1);
int main(int argc, char **argv)
{
char cmd[128];
test_init(argc, argv);
/* create nft table */
if (system("nft add table inet netns-nft-zdtm-test")) {
pr_perror("Can't create nft table");
return -1;
}
/* create input chain in table */
if (system("nft add chain inet netns-nft-zdtm-test input { type filter hook input priority 0 \\; }")) {
pr_perror("Can't create input chain in nft table");
return -1;
}
/* block ICMPv4 traffic */
if (system("nft add rule inet netns-nft-zdtm-test input meta nfproto ipv4 icmp type { echo-request } reject")) {
pr_perror("Can't set input rule");
return -1;
}
/* save resulting nft table */
sprintf(cmd, "nft list table inet netns-nft-zdtm-test > pre-%s", filename);
if (system(cmd)) {
pr_perror("Can't get nft table");
return -1;
}
test_daemon();
test_waitsig();
/* get nft table */
sprintf(cmd, "nft list table inet netns-nft-zdtm-test > post-%s", filename);
if (system(cmd)) {
fail("Can't get nft table");
return -1;
}
/* compare nft table before/after c/r */
sprintf(cmd, "diff pre-%s post-%s", filename, filename);
if (system(cmd)) {
fail("nft table differ");
return -1;
}
pass();
return 0;
}
| 1,497 | 22.046154 | 113 |
c
|
criu
|
criu-master/test/zdtm/static/netns.c
|
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include "zdtmtst.h"
const char *test_doc = "Check that network environment (links, addresses and routes) are preserved";
const char *test_author = "Pavel Emelianov <[email protected]>";
int main(int argc, char **argv)
{
test_init(argc, argv);
if (system("ip link set lo up")) {
fail("Can't set lo up");
return -1;
}
if (system("ip addr add 1.2.3.4 dev lo")) {
fail("Can't add addr on lo");
return -1;
}
if (system("ip route add 1.2.3.5 dev lo")) {
fail("Can't add route via lo");
return -1;
}
if (system("ip route add 1.2.3.6 via 1.2.3.5")) {
fail("Can't add route via lo (2)");
return -1;
}
if (system("ip link > netns.dump.test && ip addr >> netns.dump.test && ip route >> netns.dump.test")) {
sleep(1000);
fail("Can't save net config");
return -1;
}
test_daemon();
test_waitsig();
if (system("ip link > netns.rst.test && ip addr >> netns.rst.test && ip route >> netns.rst.test")) {
fail("Can't get net config");
return -1;
}
if (system("diff netns.rst.test netns.dump.test")) {
fail("Net config differs after restore");
return -1;
}
pass();
return 0;
}
| 1,180 | 20.089286 | 104 |
c
|
criu
|
criu-master/test/zdtm/static/netns_lock_iptables.c
|
#include "zdtmtst.h"
const char *test_doc = "Check network namespace is locked between dump and restore\n";
const char *test_author = "Zeyad Yasser <[email protected]>";
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#define NS_PATH "/var/run/netns/criu-net-lock-test"
#define SYNCFILE_PATH "net_lock.sync"
#define MAX_RETRY 3
int main(int argc, char **argv)
{
int i, ns_fd;
test_init(argc, argv);
/*
* We try to enter the netns created by post-start hook so that
* criu locks the network namespace between dump and restore.
*
* A TCP server is started in post-start hook inside the netns
* and runs in the background detached from its parent so that
* it stays alive for the duration of the test.
*
* Other hooks (pre-dump, pre-restore, post-restore) try to
* connect to the server.
*
* Pre-dump and post-restore hooks should be able to connect
* successfully.
*
* Pre-restore hook client with SOCCR_MARK should also connect
* successfully.
*
* Pre-restore hook client without SOCCR_MARK should not be able
* to connect but also should not get connection refused as all
* packets are dropped in the namespace so the kernel shouldn't
* send an RST packet as a result. Instead we check that the
* connect operation causes a timeout.
*/
for (i = 0; i < MAX_RETRY; i++) {
if (access(SYNCFILE_PATH, F_OK)) {
/* Netns not created yet by post-start hook */
sleep(1);
continue;
}
break;
}
ns_fd = open(NS_PATH, O_RDONLY);
if (ns_fd < 0) {
pr_perror("can't open network ns");
return 1;
}
if (setns(ns_fd, CLONE_NEWNET)) {
pr_perror("setns %d", ns_fd);
return 1;
}
close(ns_fd);
test_daemon();
test_waitsig();
pass();
return 0;
}
| 1,737 | 22.808219 | 86 |
c
|
criu
|
criu-master/test/zdtm/static/ofd_file_locks.h
|
#ifndef ZDTM_OFD_FILE_LOCKS_H_
#define ZDTM_OFD_FILE_LOCKS_H_
#include <sys/file.h>
#ifndef F_OFD_GETLK
#define F_OFD_GETLK 36
#define F_OFD_SETLK 37
#define F_OFD_SETLKW 38
#endif
/*
* Functions for parsing of OFD locks
* from procfs and checking them after restoring.
*/
extern int check_lock_exists(const char *filename, struct flock *lck);
extern int check_file_lock_restored(int pid, int fd, struct flock *lck);
extern int zdtm_fcntl(int fd, int cmd, struct flock *f);
#endif /* ZDTM_OFD_FILE_LOCKS_H_ */
| 520 | 22.681818 | 72 |
h
|
criu
|
criu-master/test/zdtm/static/packet_sock.c
|
#include "zdtmtst.h"
const char *test_doc = "static test for packet sockets";
const char *test_author = "Pavel Emelyanov <[email protected]>";
/*
* Description:
* Create and bind several packet sockets, check thet getname
* reports same result before and after c/r cycle. This is enough
* for _basic_ packet functionality only, but still.
*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <linux/version.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#define SK_RESERVE 8
#define DEF_FANOUT 13
#ifndef PACKET_FANOUT
#define PACKET_FANOUT 18
#endif
static int test_sockaddr(int n, struct sockaddr_ll *have, struct sockaddr_ll *want)
{
if (have->sll_family != want->sll_family) {
fail("%d Family mismatch %d/%d", n, (int)have->sll_family, (int)want->sll_family);
return 1;
}
if (have->sll_protocol != want->sll_protocol) {
fail("%d Proto mismatch %d/%d", n, (int)have->sll_protocol, (int)want->sll_protocol);
return 1;
}
if (have->sll_ifindex != want->sll_ifindex) {
fail("%d Index mismatch %d/%d", n, have->sll_ifindex, want->sll_ifindex);
return 1;
}
/* all the others are derivatives from dev */
return 0;
}
#ifndef MAX_ADDR_LEN
#define MAX_ADDR_LEN 32
#endif
struct packet_mreq_max {
int mr_ifindex;
unsigned short mr_type;
unsigned short mr_alen;
unsigned char mr_address[MAX_ADDR_LEN];
};
#define LO_ADDR_LEN 6
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 2, 0)
struct tpacket_req3 {
unsigned int tp_block_size;
unsigned int tp_block_nr;
unsigned int tp_frame_size;
unsigned int tp_frame_nr;
unsigned int tp_retire_blk_tov;
unsigned int tp_sizeof_priv;
unsigned int tp_feature_req_word;
};
#endif
int main(int argc, char **argv)
{
int sk1, sk2;
struct sockaddr_ll addr, addr1, addr2;
socklen_t alen;
int ver, rsv, yes;
struct packet_mreq_max mreq;
struct tpacket_req3 ring;
test_init(argc, argv);
sk1 = socket(PF_PACKET, SOCK_RAW, 0);
if (sk1 < 0) {
pr_perror("Can't create socket 1");
return 1;
}
sk2 = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
if (sk2 < 0) {
pr_perror("Can't create socket 2");
return 1;
}
memset(&addr, 0, sizeof(addr));
addr.sll_family = AF_PACKET;
addr.sll_ifindex = 1; /* loopback should be 1 in all namespaces */
if (bind(sk2, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
pr_perror("Can't bind socket");
return 1;
}
alen = sizeof(addr1);
if (getsockname(sk1, (struct sockaddr *)&addr1, &alen) < 0) {
pr_perror("Can't get sockname 1");
return 1;
}
alen = sizeof(addr2);
if (getsockname(sk2, (struct sockaddr *)&addr2, &alen) < 0) {
pr_perror("Can't get sockname 2");
return 1;
}
ver = TPACKET_V2;
if (setsockopt(sk1, SOL_PACKET, PACKET_VERSION, &ver, sizeof(ver)) < 0) {
pr_perror("Can't set version");
return 1;
}
yes = 1;
if (setsockopt(sk1, SOL_PACKET, PACKET_AUXDATA, &yes, sizeof(yes)) < 0) {
pr_perror("Can't set auxdata");
return 1;
}
memset(&ring, 0, sizeof(ring));
ring.tp_block_size = PAGE_SIZE;
ring.tp_block_nr = 1;
ring.tp_frame_size = 1024;
ring.tp_frame_nr = (ring.tp_block_size / ring.tp_frame_size) * ring.tp_block_nr;
if (setsockopt(sk1, SOL_PACKET, PACKET_RX_RING, &ring, sizeof(ring)) < 0) {
pr_perror("Can't set rx ring");
return 1;
}
rsv = SK_RESERVE;
if (setsockopt(sk2, SOL_PACKET, PACKET_RESERVE, &rsv, sizeof(rsv)) < 0) {
pr_perror("Can't set reserve");
return 1;
}
yes = 1;
if (setsockopt(sk2, SOL_PACKET, PACKET_ORIGDEV, &yes, sizeof(yes)) < 0) {
pr_perror("Can't set origdev");
return 1;
}
yes = DEF_FANOUT;
if (setsockopt(sk2, SOL_PACKET, PACKET_FANOUT, &yes, sizeof(yes)) < 0) {
pr_perror("Can't configure fanout");
return 1;
}
memset(&mreq, 0, sizeof(mreq));
mreq.mr_ifindex = 1;
mreq.mr_type = PACKET_MR_PROMISC;
if (setsockopt(sk1, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
pr_perror("Can't add promisc member");
return 1;
}
memset(&mreq, 0, sizeof(mreq));
mreq.mr_ifindex = 1;
mreq.mr_type = PACKET_MR_UNICAST;
mreq.mr_alen = LO_ADDR_LEN;
if (setsockopt(sk2, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
pr_perror("Can't add ucast member");
return 1;
}
memset(&ring, 0, sizeof(ring));
ring.tp_block_size = PAGE_SIZE;
ring.tp_block_nr = 1;
ring.tp_frame_size = 1024;
ring.tp_frame_nr = (ring.tp_block_size / ring.tp_frame_size) * ring.tp_block_nr;
if (setsockopt(sk2, SOL_PACKET, PACKET_TX_RING, &ring, sizeof(ring)) < 0) {
pr_perror("Can't set tx ring");
return 1;
}
test_daemon();
test_waitsig();
alen = sizeof(addr);
if (getsockname(sk1, (struct sockaddr *)&addr, &alen) < 0) {
fail("Can't get sockname 1 rst");
return 1;
}
if (test_sockaddr(1, &addr, &addr1))
return 1;
alen = sizeof(ver);
if (getsockopt(sk1, SOL_PACKET, PACKET_VERSION, &ver, &alen) < 0) {
fail("Can't get sockopt ver");
return 1;
}
if (ver != TPACKET_V2) {
fail("Version mismatch have %d, want %d", ver, TPACKET_V2);
return 1;
}
alen = sizeof(yes);
if (getsockopt(sk1, SOL_PACKET, PACKET_AUXDATA, &yes, &alen) < 0) {
fail("Can't get sockopt auxdata");
return 1;
}
if (yes != 1) {
fail("Auxdata not ON");
return 1;
}
memset(&mreq, 0, sizeof(mreq));
mreq.mr_ifindex = 1;
mreq.mr_type = PACKET_MR_PROMISC;
if (setsockopt(sk1, SOL_PACKET, PACKET_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
fail("Promisc member not kept");
return 1;
}
alen = sizeof(yes);
if (getsockopt(sk1, SOL_PACKET, PACKET_FANOUT, &yes, &alen) < 0) {
fail("Can't read fanout back");
return 1;
}
if (yes != 0) {
fail("Fanout screwed up to %x", yes);
return 1;
}
alen = sizeof(addr);
if (getsockname(sk2, (struct sockaddr *)&addr, &alen) < 0) {
fail("Can't get sockname 2 rst");
return 1;
}
if (test_sockaddr(2, &addr, &addr2))
return 1;
alen = sizeof(rsv);
if (getsockopt(sk2, SOL_PACKET, PACKET_RESERVE, &rsv, &alen) < 0) {
fail("Can't get sockopt rsv");
return 1;
}
alen = sizeof(yes);
if (getsockopt(sk2, SOL_PACKET, PACKET_ORIGDEV, &yes, &alen) < 0) {
fail("Can't get sockopt origdev");
return 1;
}
if (yes != 1) {
fail("OrigDev not ON");
return 1;
}
if (rsv != SK_RESERVE) {
fail("Reserve mismatch have %d, want %d", rsv, SK_RESERVE);
return 1;
}
memset(&mreq, 0, sizeof(mreq));
mreq.mr_ifindex = 1;
mreq.mr_type = PACKET_MR_UNICAST;
mreq.mr_alen = LO_ADDR_LEN;
if (setsockopt(sk2, SOL_PACKET, PACKET_DROP_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
fail("Ucast member not kept");
return 1;
}
alen = sizeof(yes);
if (getsockopt(sk2, SOL_PACKET, PACKET_FANOUT, &yes, &alen) < 0) {
fail("Can't read fanout2 back");
return 1;
}
if (yes != DEF_FANOUT) {
fail("Fanout2 screwed up to %x", yes);
return 1;
}
pass();
return 0;
}
| 6,883 | 22.023411 | 87 |
c
|
criu
|
criu-master/test/zdtm/static/packet_sock_mmap.c
|
#include "zdtmtst.h"
const char *test_doc = "static test for packet sockets mmaps";
const char *test_author = "Pavel Emelyanov <[email protected]>";
#include <stdio.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <linux/version.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <sys/mman.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 2, 0)
struct tpacket_req3 {
unsigned int tp_block_size;
unsigned int tp_block_nr;
unsigned int tp_frame_size;
unsigned int tp_frame_nr;
unsigned int tp_retire_blk_tov;
unsigned int tp_sizeof_priv;
unsigned int tp_feature_req_word;
};
#endif
static void check_map_is_there(unsigned long addr, int sk)
{
FILE *f;
char line[4096];
struct stat ss;
fstat(sk, &ss);
f = fopen("/proc/self/maps", "r");
while (fgets(line, sizeof(line), f) != NULL) {
unsigned long long ino;
unsigned long start;
int maj, min;
sscanf(line, "%lx-%*x %*s %*s %x:%x %llu %*s", &start, &maj, &min, &ino);
if ((start == addr) && ss.st_dev == makedev(maj, min) && ss.st_ino == ino) {
pass();
fclose(f);
return;
}
}
fail("No socket mapping found");
}
int main(int argc, char **argv)
{
int sk;
struct tpacket_req3 ring;
void *mem;
test_init(argc, argv);
sk = socket(PF_PACKET, SOCK_RAW, 0);
if (sk < 0) {
pr_perror("Can't create socket 1");
return 1;
}
memset(&ring, 0, sizeof(ring));
ring.tp_block_size = PAGE_SIZE;
ring.tp_block_nr = 1;
ring.tp_frame_size = 1024;
ring.tp_frame_nr = (ring.tp_block_size / ring.tp_frame_size) * ring.tp_block_nr;
if (setsockopt(sk, SOL_PACKET, PACKET_RX_RING, &ring, sizeof(ring)) < 0) {
pr_perror("Can't set rx ring");
return 1;
}
memset(&ring, 0, sizeof(ring));
ring.tp_block_size = PAGE_SIZE;
ring.tp_block_nr = 1;
ring.tp_frame_size = 1024;
ring.tp_frame_nr = (ring.tp_block_size / ring.tp_frame_size) * ring.tp_block_nr;
if (setsockopt(sk, SOL_PACKET, PACKET_TX_RING, &ring, sizeof(ring)) < 0) {
pr_perror("Can't set tx ring");
return 1;
}
mem = mmap(NULL, 2 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FILE, sk, 0);
if (mem == MAP_FAILED) {
pr_perror("Can't mmap socket");
return 1;
}
test_daemon();
test_waitsig();
check_map_is_there((unsigned long)mem, sk);
return 0;
}
| 2,398 | 21.632075 | 88 |
c
|
criu
|
criu-master/test/zdtm/static/posix_timers.c
|
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <limits.h>
#include <string.h>
#include "zdtmtst.h"
const char *test_doc = "Posix timers migration check";
const char *test_author = "Kinsbursky Stanislav <[email protected]>";
sigset_t mask;
#define WRONG_SIGNAL 1
#define WRONG_SI_PTR 2
#define FAIL_OVERRUN 4
#define MAX_TIMER_DISPLACEMENT 10
#define NO_PERIODIC
#ifndef CLOCK_MONOTONIC_COARSE
#define CLOCK_MONOTONIC_COARSE 6
#endif
#ifndef CLOCK_BOOTTIME
#define CLOCK_BOOTTIME 7
#endif
#ifndef NO_PERIODIC
static void realtime_periodic_handler(int sig, siginfo_t *si, void *uc);
static void monotonic_periodic_handler(int sig, siginfo_t *si, void *uc);
static void boottime_periodic_handler(int sig, siginfo_t *si, void *uc);
#endif
static void realtime_oneshot_handler(int sig, siginfo_t *si, void *uc);
static void monotonic_oneshot_handler(int sig, siginfo_t *si, void *uc);
static void boottime_oneshot_handler(int sig, siginfo_t *si, void *uc);
enum {
#ifndef NO_PERIODIC
REALTIME_PERIODIC_INFO,
MONOTONIC_PERIODIC_INFO,
BOOTTIME_PERIODIC_INFO,
#endif
REALTIME_ONESHOT_INFO,
MONOTONIC_ONESHOT_INFO,
BOOTTIME_ONESHOT_INFO,
};
static struct posix_timers_info {
char clock;
char *name;
void (*handler)(int sig, siginfo_t *si, void *uc);
int sig;
int oneshot;
int ms_int;
struct sigaction sa;
int handler_status;
int handler_cnt;
timer_t timerid;
int overrun;
struct timespec start, end;
} posix_timers[] = {
#ifndef NO_PERIODIC
[REALTIME_PERIODIC_INFO] = {
.clock = CLOCK_REALTIME,
.name = "REALTIME (periodic)",
.handler = realtime_periodic_handler,
.sig = SIGALRM,
.oneshot = 0,
.ms_int = 1,
},
[MONOTONIC_PERIODIC_INFO] = {
.clock = CLOCK_MONOTONIC,
.name = "MONOTONIC (periodic)",
.handler = monotonic_periodic_handler,
.sig = SIGINT,
.oneshot = 0,
.ms_int = 3,
},
[BOOTTIME_PERIODIC_INFO] = {
.clock = CLOCK_BOOTTIME,
.name = "BOOTTIME (periodic)",
.handler = boottime_periodic_handler,
.sig = SIGWINCH,
.oneshot = 0,
.ms_int = 3,
},
#endif
[REALTIME_ONESHOT_INFO] = {
.clock = CLOCK_REALTIME,
.name = "REALTIME (oneshot)",
.handler = realtime_oneshot_handler,
.sig = SIGUSR1,
.oneshot = 1,
.ms_int = INT_MAX,
},
[MONOTONIC_ONESHOT_INFO] = {
.clock = CLOCK_MONOTONIC,
.name = "MONOTONIC (oneshot)",
.handler = monotonic_oneshot_handler,
.sig = SIGUSR2,
.oneshot = 1,
.ms_int = INT_MAX,
},
[BOOTTIME_ONESHOT_INFO] = {
.clock = CLOCK_BOOTTIME,
.name = "BOOTTIME (oneshot)",
.handler = boottime_oneshot_handler,
.sig = SIGPROF,
.oneshot = 1,
.ms_int = INT_MAX,
},
{ }
};
static int check_handler_status(struct posix_timers_info *info, struct itimerspec *its, int ms_passed, int delta)
{
int displacement;
int timer_ms;
if (!info->handler_cnt && !info->oneshot) {
fail("%s: Signal handler wasn't called", info->name);
return -EINVAL;
}
if (info->handler_status) {
if (info->handler_status & WRONG_SIGNAL)
fail("%s: Handler: wrong signal received", info->name);
if (info->handler_status & WRONG_SI_PTR)
fail("%s: Handler: wrong timer address", info->name);
if (info->handler_status & FAIL_OVERRUN)
fail("%s: Handler: failed to get overrun count", info->name);
return -1;
}
if (!info->oneshot && !its->it_value.tv_sec && !its->it_value.tv_nsec) {
fail("%s: timer became unset", info->name);
return -EFAULT;
}
if (info->oneshot && (its->it_interval.tv_sec || its->it_interval.tv_nsec)) {
fail("%s: timer became periodic", info->name);
return -EFAULT;
}
if (!info->oneshot && !its->it_interval.tv_sec && !its->it_interval.tv_nsec) {
fail("%s: timer became oneshot", info->name);
return -EFAULT;
}
if (info->oneshot) {
int val = its->it_value.tv_sec * 1000 + its->it_value.tv_nsec / 1000 / 1000;
if (info->handler_cnt) {
if (val != 0) {
fail("%s: timer continues ticking after expiration", info->name);
return -EFAULT;
}
if (info->handler_cnt > 1) {
fail("%s: timer expired %d times", info->name, info->handler_cnt);
return -EFAULT;
}
if (info->ms_int > ms_passed) {
fail("%s: timer expired too early", info->name);
return -EFAULT;
}
return 0;
}
timer_ms = info->ms_int - val;
} else
timer_ms = (info->overrun + info->handler_cnt) * info->ms_int;
displacement = (abs(ms_passed - timer_ms) - delta) * 100 / ms_passed;
test_msg("%20s: cpt/rst : %-8d msec\n", info->name, delta);
test_msg("%20s: Time passed (ms) : %-8d msec\n", info->name, ms_passed);
test_msg("%20s: Timer results : %-8d msec\n", info->name, timer_ms);
test_msg("%20s: Handler count : %d\n", info->name, info->handler_cnt);
if (displacement > MAX_TIMER_DISPLACEMENT) {
fail("%32s: Time displacement: %d%% (max alloved: %d%%)", info->name, displacement,
MAX_TIMER_DISPLACEMENT);
return -EFAULT;
}
return 0;
}
static int check_timers(int delta, struct timespec *sleep_start, struct timespec *sleep_end)
{
struct posix_timers_info *info = posix_timers;
int ms_passed;
int status = 0;
struct itimerspec val, oldval;
if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == -1) {
fail("Failed to unlock signal");
return -errno;
}
while (info->handler) {
memset(&val, 0, sizeof(val));
if (timer_settime(info->timerid, 0, &val, &oldval) == -1) {
fail("%s: failed to reset timer", info->name);
return -errno;
}
if (clock_gettime(info->clock, &info->end) == -1) {
fail("Can't get %s end time", info->name);
return -errno;
}
/*
* Adjust with @total_sleep_time if needed.
*/
if (info->clock == CLOCK_BOOTTIME) {
info->start.tv_sec -= sleep_start->tv_sec;
info->start.tv_nsec -= sleep_start->tv_nsec;
info->end.tv_sec -= sleep_end->tv_sec;
info->end.tv_nsec -= sleep_end->tv_nsec;
}
ms_passed = (info->end.tv_sec - info->start.tv_sec) * 1000 +
(info->end.tv_nsec - info->start.tv_nsec) / (1000 * 1000);
if (check_handler_status(info, &oldval, ms_passed, delta))
status--;
info++;
}
return status;
}
static void generic_handler(struct posix_timers_info *info, struct posix_timers_info *real, int sig)
{
int overrun;
if (info == NULL)
info = &posix_timers[MONOTONIC_ONESHOT_INFO];
if (info != real) {
real->handler_status |= WRONG_SI_PTR;
return;
}
if (sig != info->sig)
info->handler_status |= WRONG_SIGNAL;
overrun = timer_getoverrun(info->timerid);
if (overrun == -1)
info->handler_status |= FAIL_OVERRUN;
else
info->overrun += overrun;
info->handler_cnt++;
}
#ifndef NO_PERIODIC
static void monotonic_periodic_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[MONOTONIC_PERIODIC_INFO], sig);
}
static void boottime_periodic_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[BOOTTIME_PERIODIC_INFO], sig);
}
#endif
static void monotonic_oneshot_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[MONOTONIC_ONESHOT_INFO], sig);
}
static void boottime_oneshot_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[BOOTTIME_ONESHOT_INFO], sig);
}
#ifndef NO_PERIODIC
static void realtime_periodic_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[REALTIME_PERIODIC_INFO], sig);
}
#endif
static void realtime_oneshot_handler(int sig, siginfo_t *si, void *uc)
{
generic_handler(si->si_value.sival_ptr, &posix_timers[REALTIME_ONESHOT_INFO], sig);
}
static int setup_timers(void)
{
int i;
int ret;
struct posix_timers_info *info = posix_timers;
struct sigevent sev;
struct itimerspec its;
sigemptyset(&mask);
while (info->handler) {
sigaddset(&mask, info->sig);
info++;
}
if (sigprocmask(SIG_SETMASK, &mask, NULL) == -1) {
pr_perror("Failed to unlock signal");
return -errno;
}
info = posix_timers;
while (info->handler) {
/* Add and delete fake timers to test restoring 'with holes' */
timer_t timeridt;
for (i = 0; i < 10; i++) {
ret = timer_create(CLOCK_REALTIME, NULL, &timeridt);
if (ret < 0) {
pr_perror("Can't create temporary posix timer %lx", (long)timeridt);
return -errno;
}
ret = timer_delete(timeridt);
if (ret < 0) {
pr_perror("Can't remove temporaty posix timer %lx", (long)timeridt);
return -errno;
}
}
info->sa.sa_flags = SA_SIGINFO;
info->sa.sa_sigaction = info->handler;
sigemptyset(&info->sa.sa_mask);
if (sigaction(info->sig, &info->sa, NULL) == -1) {
pr_perror("Failed to set SIGALRM handler");
return -errno;
}
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = info->sig;
if (&posix_timers[MONOTONIC_ONESHOT_INFO] == info)
sev.sigev_value.sival_ptr = NULL;
else
sev.sigev_value.sival_ptr = info;
if (timer_create(info->clock, &sev, &info->timerid) == -1) {
pr_perror("Can't create timer");
return -errno;
}
its.it_value.tv_sec = info->ms_int / 1000;
its.it_value.tv_nsec = info->ms_int % 1000 * 1000 * 1000;
if (!info->oneshot) {
its.it_interval.tv_sec = its.it_value.tv_sec;
its.it_interval.tv_nsec = its.it_value.tv_nsec;
} else
its.it_interval.tv_sec = its.it_interval.tv_nsec = 0;
if (clock_gettime(info->clock, &info->start) == -1) {
pr_perror("Can't get %s start time", info->name);
return -errno;
}
if (timer_settime(info->timerid, 0, &its, NULL) == -1) {
pr_perror("Can't set timer");
return -errno;
}
info++;
}
return 0;
}
/*
* Figure out @total_sleep_time, ie time the system was in hardware
* suspend mode, will need this value to exclude from boottime clock
* testing.
*/
static int get_total_sleep_time(struct timespec *tv, char *type)
{
struct timespec boottime_coarse;
struct timespec boottime;
if (clock_gettime(CLOCK_BOOTTIME, &boottime) == -1) {
pr_perror("Can't get CLOCK_BOOTTIME %s time", type);
return -errno;
}
if (clock_gettime(CLOCK_MONOTONIC_COARSE, &boottime_coarse) == -1) {
pr_perror("Can't get CLOCK_MONOTONIC_COARSE %s time", type);
return -errno;
}
tv->tv_sec = boottime.tv_sec - boottime_coarse.tv_sec;
tv->tv_nsec = boottime.tv_nsec - boottime_coarse.tv_nsec;
test_msg("(%6s) boottime %lu "
"boottime-coarse %lu "
"total_sleep_time %lu\n",
type, (long)boottime.tv_sec, (long)boottime_coarse.tv_sec, (long)tv->tv_sec);
return 0;
}
int main(int argc, char **argv)
{
struct timespec sleep_start, sleep_end;
struct timespec start, end;
int err;
test_init(argc, argv);
err = setup_timers();
if (err)
return err;
usleep(500 * 1000);
clock_gettime(CLOCK_REALTIME, &start);
err = get_total_sleep_time(&sleep_start, "start");
if (err)
return err;
test_daemon();
test_waitsig();
clock_gettime(CLOCK_REALTIME, &end);
err = get_total_sleep_time(&sleep_end, "end");
if (err)
return err;
err = check_timers((end.tv_sec - start.tv_sec) * 1000 + (end.tv_nsec - start.tv_nsec) / 1000000, &sleep_start,
&sleep_end);
if (err)
return err;
pass();
return 0;
}
| 11,072 | 24.572748 | 113 |
c
|
criu
|
criu-master/test/zdtm/static/pthread01.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include "zdtmtst.h"
#define gettid() pthread_self()
const char *test_doc = "Create a few pthreads and test TLS + blocked signals\n";
const char *test_author = "Cyrill Gorcunov <[email protected]";
static __thread struct tls_data_s {
char *rand_string[10];
sigset_t blk_sigset;
} tls_data;
static task_waiter_t t1;
static task_waiter_t t2;
#ifdef CONFIG_MIPS
#ifndef SIGSTKFLT
#define SIGSTKFLT 16
#endif
#endif
static char *decode_signal(const sigset_t *s, char *buf)
{
buf[0] = '\0';
#define COLLECT(sig) \
do { \
if (sigismember(s, sig)) \
strcat(buf, #sig " "); \
} while (0)
COLLECT(SIGHUP);
COLLECT(SIGINT);
COLLECT(SIGQUIT);
COLLECT(SIGILL);
COLLECT(SIGTRAP);
COLLECT(SIGABRT);
COLLECT(SIGIOT);
COLLECT(SIGBUS);
COLLECT(SIGFPE);
COLLECT(SIGKILL);
COLLECT(SIGUSR1);
COLLECT(SIGSEGV);
COLLECT(SIGUSR2);
COLLECT(SIGPIPE);
COLLECT(SIGALRM);
COLLECT(SIGTERM);
COLLECT(SIGSTKFLT);
COLLECT(SIGCHLD);
COLLECT(SIGCONT);
COLLECT(SIGSTOP);
COLLECT(SIGTSTP);
COLLECT(SIGTTIN);
COLLECT(SIGTTOU);
COLLECT(SIGURG);
COLLECT(SIGXCPU);
COLLECT(SIGXFSZ);
COLLECT(SIGVTALRM);
COLLECT(SIGPROF);
COLLECT(SIGWINCH);
COLLECT(SIGIO);
COLLECT(SIGPOLL);
COLLECT(SIGPWR);
COLLECT(SIGSYS);
#undef COLLECT
return buf;
}
static void __show_sigset(int line, const sigset_t *s)
{
char buf[sizeof(sigset_t) * 2 + 1] = {};
decode_signal(s, buf);
test_msg("sigset at %4d: %s\n", line, buf);
}
#define show_sigset(set) __show_sigset(__LINE__, set)
static void *ch_thread_2(void *arg)
{
char __tls_data[sizeof(tls_data.rand_string)] = "XM5o:?B*[a";
int *results_map = arg;
sigset_t blk_sigset = {};
sigset_t new = {};
memcpy(tls_data.rand_string, __tls_data, sizeof(tls_data.rand_string));
sigemptyset(&blk_sigset);
pthread_sigmask(SIG_SETMASK, NULL, &blk_sigset);
sigaddset(&blk_sigset, SIGFPE);
pthread_sigmask(SIG_SETMASK, &blk_sigset, NULL);
memcpy(&tls_data.blk_sigset, &blk_sigset, sizeof(tls_data.blk_sigset));
show_sigset(&blk_sigset);
show_sigset(&tls_data.blk_sigset);
task_waiter_complete(&t2, 1);
task_waiter_wait4(&t2, 2);
if (memcmp(tls_data.rand_string, __tls_data, sizeof(tls_data.rand_string))) {
pr_perror("Failed to restore tls_data.rand_string in thread 2");
results_map[2] = -1;
} else
results_map[2] = 1;
if (memcmp(&tls_data.blk_sigset, &blk_sigset, sizeof(tls_data.blk_sigset))) {
pr_perror("Failed to restore tls_data.blk_sigset in thread 2");
results_map[4] = -1;
} else
results_map[4] = 1;
pthread_sigmask(SIG_SETMASK, NULL, &new);
if (memcmp(&tls_data.blk_sigset, &new, sizeof(tls_data.blk_sigset))) {
pr_perror("Failed to restore blk_sigset in thread 2");
results_map[6] = -1;
show_sigset(&tls_data.blk_sigset);
show_sigset(&new);
} else
results_map[6] = 1;
return NULL;
}
static void *ch_thread_1(void *arg)
{
char __tls_data[sizeof(tls_data.rand_string)] = "pffYQSBo?6";
int *results_map = arg;
sigset_t blk_sigset = {};
sigset_t new = {};
memcpy(tls_data.rand_string, __tls_data, sizeof(tls_data.rand_string));
sigemptyset(&blk_sigset);
pthread_sigmask(SIG_SETMASK, NULL, &blk_sigset);
sigaddset(&blk_sigset, SIGWINCH);
sigaddset(&blk_sigset, SIGALRM);
pthread_sigmask(SIG_SETMASK, &blk_sigset, NULL);
memcpy(&tls_data.blk_sigset, &blk_sigset, sizeof(tls_data.blk_sigset));
show_sigset(&blk_sigset);
show_sigset(&tls_data.blk_sigset);
task_waiter_complete(&t1, 1);
task_waiter_wait4(&t1, 2);
if (memcmp(tls_data.rand_string, __tls_data, sizeof(tls_data.rand_string))) {
pr_perror("Failed to restore tls_data.rand_string in thread 1");
results_map[1] = -1;
} else
results_map[1] = 1;
if (memcmp(&tls_data.blk_sigset, &blk_sigset, sizeof(tls_data.blk_sigset))) {
pr_perror("Failed to restore tls_data.blk_sigset in thread 1");
results_map[3] = -1;
} else
results_map[3] = 1;
sigemptyset(&new);
pthread_sigmask(SIG_SETMASK, NULL, &new);
if (memcmp(&tls_data.blk_sigset, &new, sizeof(tls_data.blk_sigset))) {
pr_perror("Failed to restore blk_sigset in thread 1");
results_map[5] = -1;
show_sigset(&tls_data.blk_sigset);
show_sigset(&new);
} else
results_map[5] = 1;
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread_1, thread_2;
int *results_map;
int rc1, rc2;
test_init(argc, argv);
task_waiter_init(&t1);
task_waiter_init(&t2);
test_msg("%s pid %d\n", argv[0], getpid());
results_map = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if ((void *)results_map == MAP_FAILED) {
fail("Can't map");
exit(1);
}
rc1 = pthread_create(&thread_1, NULL, &ch_thread_1, results_map);
rc2 = pthread_create(&thread_2, NULL, &ch_thread_2, results_map);
if (rc1 | rc2) {
fail("Can't pthread_create");
exit(1);
}
test_msg("Waiting until all threads are created\n");
task_waiter_wait4(&t1, 1);
task_waiter_wait4(&t2, 1);
test_daemon();
test_waitsig();
task_waiter_complete(&t1, 2);
task_waiter_complete(&t2, 2);
test_msg("Waiting while all threads are joined\n");
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
if (results_map[1] == 1 && results_map[2] == 1 && results_map[3] == 1 && results_map[4] == 1 &&
results_map[5] == 1 && results_map[6] == 1)
pass();
else
fail();
return 0;
}
| 5,567 | 22.493671 | 96 |
c
|
criu
|
criu-master/test/zdtm/static/s390x_gs_threads.c
|
#include <linux/types.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
#include "zdtmtst.h"
#include "lock.h"
#define NR_THREADS 4
#define GS_ENABLE 0
#define GS_SET_BC_CB 2
#define GS_BROADCAST 4
#ifndef __NR_guarded_storage
#define __NR_guarded_storage 378
#endif
const char *test_doc = "Check the guarded storage broadcast";
/* Original test provided by Martin Schwidefsky <[email protected]> */
const char *test_author = "Alice Frosi <[email protected]>";
static unsigned long main_thread_tid;
/*
* This test case executes the following procedure:
*
* 1) The parent thread creates NR_THREADS child threads
*
* 2) For each thread (including the parent thread):
* - Enable guarded-storage
* - Set the guarded-storage broadcast control block and
* specify gs_handler as Guarded-Storage-Event Parameter-List
* address
*
* 3) Dump and restore
*
* 4) Guarded-storage broadcast event
* - Child threads: Wait until main thread does GS broadcast
* - Parent thread: Trigger GS broadcast
*
* 5) Verify that all GS works as expected and all threads have been
* executed the gs_handler
*/
struct gs_cb {
__u64 reserved;
__u64 gsd;
__u64 gssm;
__u64 gs_epl_a;
};
static futex_t futex;
static futex_t futex2;
/*
* Load guarded-storage
*/
void load_guarded(unsigned long *mem);
asm(".global load_guarded\n"
"load_guarded:\n"
" .insn rxy,0xe3000000004c,%r2,0(%r2)\n"
" br %r14\n"
" .size load_guarded,.-load_guarded\n");
/*
* Inline assembly to deal with interrupted context to the call of
* the GS handler. Load guarded can be turned into a branch to this
* function.
*/
void gs_handler_asm(void);
asm(".globl gs_handler_asm\n"
"gs_handler_asm:\n"
" lgr %r14,%r15\n"
" aghi %r15,-320\n"
" stmg %r0,%r14,192(%r15)\n"
" stg %r14,312(%r14)\n"
" la %r2,160(%r15)\n"
" .insn rxy,0xe30000000049,0,160(%r15)\n"
" lg %r14,24(%r2)\n"
" lg %r14,40(%r14)\n"
" la %r14,6(%r14)\n"
" stg %r14,304(%r15)\n"
" brasl %r14,gs_handler\n"
" lmg %r0,%r15,192(%r15)\n"
" br %r14\n"
" .size gs_handler_asm,.-gs_handler_asm\n");
/*
* GS handler called when GS event occurs
*/
void gs_handler(struct gs_cb *this_cb)
{
unsigned long tid = syscall(SYS_gettid);
test_msg("gs_handler for thread %016lx\n", tid);
futex_dec_and_wake(&futex2);
}
/*
* Entry point for threads
*/
static void *thread_run(void *param)
{
unsigned long test = 0x1234000000;
unsigned long *gs_epl;
struct gs_cb *gs_cb;
/* Enable guarded-storage */
if (syscall(__NR_guarded_storage, GS_ENABLE) != 0) {
fail("Unable to enable guarded storage");
exit(1);
}
gs_epl = malloc(sizeof(unsigned long) * 6);
gs_cb = malloc(sizeof(*gs_cb));
if (gs_epl == NULL || gs_cb == NULL) {
fail("Error allocating memory");
exit(1);
}
gs_cb->gsd = 0x1234000000UL | 26;
gs_cb->gssm = -1UL;
gs_cb->gs_epl_a = (unsigned long)gs_epl;
gs_epl[1] = (unsigned long)gs_handler_asm;
/* Set the GS broadcast control block */
syscall(__NR_guarded_storage, GS_SET_BC_CB, gs_cb);
futex_dec_and_wake(&futex);
/* Wait for all threads to set the GS broadcast control block */
futex_wait_until(&futex, 0);
test_msg("Thread %016lx staring loop\n", syscall(SYS_gettid));
/*
* Designate a guarded-storage section until the main task
* performs the GS_BROADCAST action and the following load_guarded
* will provoke the switch to the gs handler
*/
while (1)
load_guarded(&test);
}
int main(int argc, char *argv[])
{
pthread_t tids[NR_THREADS];
int i;
main_thread_tid = syscall(SYS_gettid);
test_init(argc, argv);
/* Enable guarded-storage */
if (syscall(__NR_guarded_storage, GS_ENABLE) != 0) {
if (errno == ENOSYS || errno == EOPNOTSUPP) {
test_daemon();
test_waitsig();
skip("No guarded storage support");
pass();
return 0;
}
fail("Unable to enable guarded storage");
return 1;
}
futex_set(&futex, NR_THREADS);
for (i = 0; i < NR_THREADS; i++)
pthread_create(tids + i, NULL, thread_run, NULL);
test_msg("Waiting for thread startup\n");
/* Wait for all threads to set the GS broadcast control block */
futex_wait_until(&futex, 0);
test_daemon();
test_waitsig();
test_msg("Doing broadcast\n");
futex_set(&futex2, NR_THREADS);
/*
* Triggers a GS event and force all the threads to execute
* the gs handler
*/
syscall(__NR_guarded_storage, GS_BROADCAST);
test_msg("Waiting for thread completion\n");
futex_wait_until(&futex2, 0);
pass();
return 0;
}
| 4,607 | 23.774194 | 75 |
c
|
criu
|
criu-master/test/zdtm/static/s390x_mmap_high.c
|
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include "zdtmtst.h"
#define TASK_SIZE_LEVEL_4 0x20000000000000UL /* 8 PB */
#define MAP_SIZE 0x1000
#define VAL 0x77
const char *test_doc = "Verify that tasks > 4TB can be checkpointed";
const char *test_author = "Michael Holzheu <[email protected]>";
/*
* Map memory at the very end of the 8 PB address space
*/
int main(int argc, char **argv)
{
void *addr = (void *)TASK_SIZE_LEVEL_4 - MAP_SIZE;
char *buf;
int i;
test_init(argc, argv);
/*
* Skip test if kernel does not have the following fix:
*
* ee71d16d22 ("s390/mm: make TASK_SIZE independent from the number
* of page table levels")
*/
if (munmap(addr, MAP_SIZE) == -1) {
test_daemon();
test_waitsig();
skip("Detected kernel without 4 level TASK_SIZE fix");
pass();
return 0;
}
/* Map memory at the very end of the 8 PB address space */
buf = mmap(addr, MAP_SIZE, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED, -1, 0);
if (buf == MAP_FAILED) {
pr_perror("Could not create mapping");
exit(1);
}
/* Initialize buffer with data */
memset(buf, VAL, MAP_SIZE);
test_daemon();
test_waitsig();
/* Verify that we restored the data correctly */
for (i = 0; i < MAP_SIZE; i++) {
if (buf[i] == VAL)
continue;
fail("%d: %d != %d", i, buf[i], VAL);
goto out;
}
pass();
out:
return 0;
}
| 1,423 | 21.603175 | 100 |
c
|
criu
|
criu-master/test/zdtm/static/s390x_regs_check.c
|
#include <linux/elf.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
#include "zdtmtst.h"
const char *test_doc = "Check that FP and VX registers do not change";
const char *test_author = "Michael Holzheu <[email protected]>";
/*
* This test case executes the following procedure:
*
* 1) Set registers to defined values
* The main process creates one child process and within that process
* NR_THREADS threads. Then the main process uses ptrace(SETREGS) to
* set the registers in the child process and in all threads.
*
* 2) Detach from child and threads
* Do this in order to allow criu to use ptrace for dumping.
*
* 3) Issue criu commands
* Useful tests are: dump, dump --check-only, dump --leave-running
*
* 4) Check registers
* Use ptrace(GETREGS) and compare with original values from step 1.
*
* This test can be used for two purposes:
*
* - Verify that "criu restore" sets the correct register sets
* from "criu dump":
* $ zdtm.py run -t zdtm/static/s390x_regs_check
*
* - Verify that dumpee continues running with correct registers after
* parasite injection:
* $ zdtm.py run --norst -t zdtm/static/s390x_regs_check
* $ zdtm.py run --norst --pre 2 -t zdtm/static/s390x_regs_check
* $ zdtm.py run --check-only -t zdtm/static/s390x_regs_check
*/
#define NR_THREADS 2
#define NR_THREADS_ALL (NR_THREADS + 1)
static pid_t thread_pids[NR_THREADS_ALL];
static int pipefd[2];
/*
* Generic structure to define a register set and test data
*/
struct reg_set {
const char *name; /* Name of regset */
int nr; /* Number of regset */
void *data; /* Test data */
int len; /* Number of bytes of test data */
bool optional; /* Not all kernels/machines have this reg set */
bool available; /* Current kernel/machine has this reg set */
};
/*
* s390 floating point registers
*/
struct prfpreg {
uint32_t fpc;
uint64_t fprs[16];
};
struct prfpreg prfpreg_data = { .fpc = 0,
.fprs = {
0x0000000000000000,
0x1111111111111110,
0x2222222222222220,
0x3333333333333330,
0x4444444444444440,
0x5555555555555550,
0x6666666666666660,
0x7777777777777770,
0x8888888888888880,
0x9999999999999990,
0xaaaaaaaaaaaaaaa0,
0xbbbbbbbbbbbbbbb0,
0xccccccccccccccc0,
0xddddddddddddddd0,
0xeeeeeeeeeeeeeee0,
0xfffffffffffffff0,
} };
struct reg_set reg_set_prfpreg = {
.name = "PRFPREG",
.nr = NT_PRFPREG,
.data = &prfpreg_data,
.len = sizeof(prfpreg_data),
.optional = false,
};
/*
* s390 vector VXRS_LOW registers
*/
#define NT_S390_VXRS_LOW 0x309
struct vxrs_low {
uint64_t regs[16];
};
struct vxrs_low vxrs_low_data = { .regs = {
0x0000000000000001,
0x1111111111111111,
0x2222222222222221,
0x3333333333333331,
0x4444444444444441,
0x5555555555555551,
0x6666666666666661,
0x7777777777777771,
0x8888888888888881,
0x9999999999999991,
0xaaaaaaaaaaaaaaa1,
0xbbbbbbbbbbbbbbb1,
0xccccccccccccccc1,
0xddddddddddddddd1,
0xeeeeeeeeeeeeeee1,
0xfffffffffffffff1,
} };
struct reg_set reg_set_vxrs_low = {
.name = "VXRS_LOW",
.nr = NT_S390_VXRS_LOW,
.data = &vxrs_low_data,
.len = sizeof(vxrs_low_data),
.optional = true,
};
/*
* s390 vector VXRS_HIGH registers
*/
#define NT_S390_VXRS_HIGH 0x30a
struct vxrs_high {
uint64_t regs[32];
};
struct vxrs_high vxrs_high_data = { .regs = {
0x0000000000000002, 0x0000000000000002, 0x1111111111111112,
0x1111111111111112, 0x2222222222222222, 0x2222222222222222,
0x3333333333333332, 0x3333333333333332, 0x4444444444444442,
0x4444444444444442, 0x5555555555555552, 0x5555555555555552,
0x6666666666666662, 0x6666666666666662, 0x7777777777777772,
0x7777777777777772, 0x8888888888888882, 0x8888888888888882,
0x9999999999999992, 0x9999999999999992, 0xaaaaaaaaaaaaaaa2,
0xaaaaaaaaaaaaaaa2, 0xbbbbbbbbbbbbbbb2, 0xbbbbbbbbbbbbbbb2,
0xccccccccccccccc2, 0xccccccccccccccc2, 0xddddddddddddddd2,
0xddddddddddddddd2, 0xeeeeeeeeeeeeeee2, 0xeeeeeeeeeeeeeee2,
0xfffffffffffffff2, 0xfffffffffffffff2,
} };
struct reg_set reg_set_vxrs_high = {
.name = "VXRS_HIGH",
.nr = NT_S390_VXRS_HIGH,
.data = &vxrs_high_data,
.len = sizeof(vxrs_high_data),
.optional = true,
};
/*
* s390 guarded-storage registers
*/
#define NT_S390_GS_CB 0x30b
#define NT_S390_GS_BC 0x30c
struct gs_cb {
uint64_t regs[4];
};
struct gs_cb gs_cb_data = { .regs = {
0x0000000000000000,
0x000000123400001a,
0x5555555555555555,
0x000000014b58a010,
} };
struct reg_set reg_set_gs_cb = {
.name = "GS_CB",
.nr = NT_S390_GS_CB,
.data = &gs_cb_data,
.len = sizeof(gs_cb_data),
.optional = true,
};
struct gs_cb gs_bc_data = { .regs = {
0x0000000000000000,
0x000000123400001a,
0xffffffffffffffff,
0x0000000aaaaaaaaa,
} };
struct reg_set reg_set_gs_bc = {
.name = "GS_BC_CB",
.nr = NT_S390_GS_BC,
.data = &gs_bc_data,
.len = sizeof(gs_bc_data),
.optional = true,
};
/*
* s390 runtime-instrumentation control block
*/
#define NT_S390_RI_CB 0x30d
struct ri_cb {
uint64_t regs[8];
};
struct ri_cb ri_cb_data = { .regs = {
0x000002aa13aae000,
0x000002aa13aad000,
0x000002aa13aadfff,
0xe0a1000400000000,
0x0000000000000000,
0x0000000000004e20,
0x0000000000003479,
0x0000000000000000,
} };
struct reg_set reg_set_ri_cb = {
.name = "RI_CB",
.nr = NT_S390_RI_CB,
.data = &ri_cb_data,
.len = sizeof(ri_cb_data),
.optional = true,
};
/*
* Vector with all regsets
*/
struct reg_set *reg_set_vec[] = {
®_set_prfpreg, ®_set_vxrs_low, ®_set_vxrs_high, ®_set_gs_cb, ®_set_gs_bc, ®_set_ri_cb, NULL,
};
/*
* Print hexdump for buffer with variable group parameter
*/
void util_hexdump_grp(const char *tag, const void *data, int grp, int count, int indent)
{
char str[1024], *ptr = str;
const char *buf = data;
int i, first = 1;
for (i = 0; i < count; i++) {
if (first) {
ptr = str;
ptr += sprintf(ptr, "%*s", indent, " ");
if (tag)
ptr += sprintf(ptr, "%s: ", tag);
ptr += sprintf(ptr, "%08x: ", i);
first = 0;
}
ptr += sprintf(ptr, "%02x", buf[i]);
if (i % 16 == 15 || i + 1 == count) {
test_msg("%s\n", str);
first = 1;
} else if (i % grp == grp - 1) {
ptr += sprintf(ptr, " ");
}
}
}
/*
* Print hexdump for buffer with fix grp parameter
*/
void util_hexdump(const char *tag, const void *data, int count)
{
util_hexdump_grp(tag, data, sizeof(long), count, 0);
}
/*
* Set regset for pid
*/
static int set_regset(pid_t pid, struct reg_set *reg_set)
{
struct iovec iov;
iov.iov_base = reg_set->data;
iov.iov_len = reg_set->len;
if (ptrace(PTRACE_SETREGSET, pid, reg_set->nr, iov) == 0) {
test_msg(" REGSET: %12s -> DONE\n", reg_set->name);
reg_set->available = true;
return 0;
}
if (reg_set->optional) {
switch (errno) {
case EOPNOTSUPP:
case ENODEV:
test_msg(" REGSET: %12s -> not supported by machine\n", reg_set->name);
return 0;
case EINVAL:
test_msg(" REGSET: %12s -> not supported by kernel\n", reg_set->name);
return 0;
default:
break;
}
}
pr_perror("PTRACE_SETREGSET for %s failed for pid %d", reg_set->name, pid);
return -1;
}
/*
* Apply all regsets
*/
static int set_regset_all(pid_t pid)
{
int i;
for (i = 0; reg_set_vec[i] != NULL; i++) {
if (set_regset(pid, reg_set_vec[i]))
return -1;
}
return 0;
}
/*
* Check if regset for pid has changed
*/
static int check_regset(pid_t pid, struct reg_set *reg_set)
{
struct iovec iov;
char *data;
if (!reg_set->available)
return 0;
data = calloc(reg_set->len, 1);
if (!data)
return -1;
iov.iov_base = data;
iov.iov_len = reg_set->len;
if (ptrace(PTRACE_GETREGSET, pid, reg_set->nr, iov) != 0) {
pr_perror("PTRACE_SETREGSET for %s failed for pid %d", reg_set->name, pid);
free(data);
return -1;
}
if (memcmp(data, reg_set->data, reg_set->len) != 0) {
test_msg("RegSet %s changed for pid=%d\n", reg_set->name, pid);
test_msg("Original values:\n");
util_hexdump(reg_set->name, reg_set->data, reg_set->len);
test_msg("New values:\n");
util_hexdump(reg_set->name, data, reg_set->len);
free(data);
return -1;
}
free(data);
return 0;
}
/*
* Check all regsets
*/
static int check_regset_all(pid_t pid)
{
int i;
for (i = 0; reg_set_vec[i] != NULL; i++) {
if (check_regset(pid, reg_set_vec[i]))
return -1;
}
return 0;
}
/*
* Send error to father
*/
static void send_error(void)
{
int val = 0;
if (write(pipefd[1], &val, sizeof(val)) == -1)
pr_perror("write failed");
}
/*
* Write tid to pipe and then loop without changing registers
*/
static inline void send_tid_and_loop(int fd)
{
int tid = syscall(__NR_gettid);
asm volatile("lgr 2,%0\n" /* Arg 1: fd */
"la 3,%1\n" /* Arg 2: &tid */
"lghi 4,4\n" /* Arg 3: sizeof(int) */
"svc 4\n" /* __NR_write SVC: */
/* After SVC no more registers are changed */
"0: j 0b\n" /* Loop here */
:
: "d"(fd), "Q"(tid)
: "2", "3", "4");
}
/*
* Function for threads
*/
static void *thread_func(void *fd)
{
send_tid_and_loop(pipefd[1]);
return NULL;
}
/*
* Function executed by the child
*/
static void child_func(void)
{
pthread_t thread;
int i;
/* Close read end of pipe */
close(pipefd[0]);
/* Create threads and send TID */
for (i = 0; i < NR_THREADS; i++) {
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
pr_perror("Error create thread: %d", i);
send_error();
}
}
/* Send tid and wait until get killed */
send_tid_and_loop(pipefd[1]);
}
/*
* Attach to a thread
*/
static int ptrace_attach(pid_t pid)
{
if (ptrace(PTRACE_ATTACH, pid, 0, 0) == 0) {
if (waitpid(pid, NULL, __WALL) < 0) {
pr_perror("Waiting for thread %d failed", pid);
return -1;
}
return 0;
}
pr_perror("Attach to thread %d failed", pid);
return -1;
}
/*
* Detach from a thread
*/
static int ptrace_detach(pid_t pid)
{
if (ptrace(PTRACE_DETACH, pid, 0, 0) == 0)
return 0;
pr_perror("Detach from thread %d failed", pid);
return -1;
}
/*
* Create child with threads and verify that registers are not corrupted
*/
int main(int argc, char *argv[])
{
bool failed = false;
pid_t child, pid;
int i;
test_init(argc, argv);
test_msg("------------- START 1 PROCESS + %d THREADS ---------------\n", NR_THREADS);
if (pipe(pipefd) == -1) {
perror("pipe failed");
exit(EXIT_FAILURE);
}
child = fork();
if (child == 0)
child_func();
/* Parent */
for (i = 0; i < NR_THREADS_ALL; i++) {
if (read(pipefd[0], &pid, sizeof(pid_t)) == -1) {
perror("Read from pipe failed");
failed = true;
goto kill_all_threads;
}
if (pid == 0) {
pr_err("Not all threads are started\n");
failed = true;
goto kill_all_threads;
}
test_msg("STARTED: pid = %d\n", pid);
thread_pids[i] = pid;
}
/* Close write end */
close(pipefd[1]);
test_msg("---------------------- SET REGISTERS --------------------\n");
for (i = 0; i < NR_THREADS_ALL; i++) {
pid = thread_pids[i];
test_msg("SET: pid = %d\n", pid);
ptrace_attach(pid);
set_regset_all(pid);
ptrace_detach(pid);
}
test_daemon();
test_waitsig();
test_msg("-------------------- CHECK REGISTERS --------------------\n");
for (i = 0; i < NR_THREADS_ALL; i++) {
pid = thread_pids[i];
test_msg("CHECK: pid = %d:\n", pid);
ptrace_attach(pid);
if (check_regset_all(pid) == 0) {
test_msg(" -> OK\n");
} else {
test_msg(" -> FAIL\n");
failed = true;
}
ptrace_detach(pid);
}
test_msg("----------------------- CLEANUP ------------------------\n");
kill_all_threads:
for (i = 0; i < NR_THREADS_ALL; i++) {
pid = thread_pids[i];
if (pid == 0)
continue;
test_msg("KILL: pid = %d\n", pid);
kill(pid, SIGTERM);
}
if (failed) {
fail("Registers changed");
return 1;
}
pass();
return 0;
}
| 12,257 | 21.368613 | 111 |
c
|
criu
|
criu-master/test/zdtm/static/s390x_runtime_instr.c
|
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <errno.h>
#include <sys/ptrace.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <asm/ptrace.h>
#include <linux/elf.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <ucontext.h>
#include <signal.h>
#include <string.h>
#include "zdtmtst.h"
#ifndef __NR_s390_runtime_instr
#define __NR_s390_runtime_instr 342
#endif
#define NT_S390_RI_CB 0x30d
#define BUF_SIZE (1024 * 1024)
const char *test_doc = "Check runtime-instrumentation";
/* Original test provided by Martin Schwidefsky <[email protected]> */
const char *test_author = "Alice Frosi <[email protected]>";
struct runtime_instr_cb {
unsigned long rca;
unsigned long roa;
unsigned long rla;
unsigned int v : 1;
unsigned int s : 1;
unsigned int k : 1;
unsigned int h : 1;
unsigned int a : 1;
unsigned int reserved1 : 3;
unsigned int ps : 1;
unsigned int qs : 1;
unsigned int pc : 1;
unsigned int qc : 1;
unsigned int reserved2 : 1;
unsigned int g : 1;
unsigned int u : 1;
unsigned int l : 1;
unsigned int key : 4;
unsigned int reserved3 : 8;
unsigned int t : 1;
unsigned int rgs : 3;
unsigned int m : 4;
unsigned int n : 1;
unsigned int mae : 1;
unsigned int reserved4 : 2;
unsigned int c : 1;
unsigned int r : 1;
unsigned int b : 1;
unsigned int j : 1;
unsigned int e : 1;
unsigned int x : 1;
unsigned int reserved5 : 2;
unsigned int bpxn : 1;
unsigned int bpxt : 1;
unsigned int bpti : 1;
unsigned int bpni : 1;
unsigned int reserved6 : 2;
unsigned int d : 1;
unsigned int f : 1;
unsigned int ic : 4;
unsigned int dc : 4;
unsigned long reserved7;
unsigned long sf;
unsigned long rsic;
unsigned long reserved8;
};
/*
* Return PSW mask
*/
static inline unsigned long extract_psw(void)
{
unsigned int reg1, reg2;
asm volatile("epsw %0,%1" : "=d"(reg1), "=a"(reg2));
return (((unsigned long)reg1) << 32) | ((unsigned long)reg2);
}
/*
* Enable runtime-instrumentation
*/
static inline void rion(void)
{
asm volatile(".word 0xaa01, 0x0000");
}
/*
* Disable runtime-instrumentation
*/
static inline void rioff(void)
{
asm volatile(".word 0xaa03, 0x0000");
}
/*
* Modify the current runtime-instrumentation control block
*/
static inline void mric(struct runtime_instr_cb *cb)
{
asm volatile(".insn rsy,0xeb0000000062,0,0,%0" : : "Q"(*cb));
}
/*
* Store the current runtime-instrumentation control block
*/
static inline void stric(struct runtime_instr_cb *cb)
{
asm volatile(".insn rsy,0xeb0000000061,0,0,%0" : "=Q"(*cb) : : "cc");
}
/*
* Ensure that runtime-intstrumentation is still working after C/R
*/
int main(int argc, char **argv)
{
struct runtime_instr_cb ricb, ricb_check;
unsigned long *ricb_check_ptr = (unsigned long *)&ricb_check;
unsigned long *ricb_ptr = (unsigned long *)&ricb;
unsigned long psw_mask;
void *buf;
int i;
test_init(argc, argv);
buf = malloc(BUF_SIZE);
memset(buf, 0, BUF_SIZE);
memset(&ricb, 0, sizeof(ricb));
/* Initialize the default RI control block in the kernel */
if (syscall(__NR_s390_runtime_instr, 1, NULL) < 0) {
if (errno == EOPNOTSUPP) {
test_daemon();
test_waitsig();
skip("RI not supported");
pass();
free(buf);
return 0;
}
fail("syscall(s390_runtime_instr) failed");
free(buf);
return -1;
}
/* Set buffer for RI */
ricb.rca = ricb.roa = (unsigned long)buf;
ricb.rla = (unsigned long)buf + BUF_SIZE;
mric(&ricb);
/* Enable RI - afterwards the PSW will have RI bit set */
rion();
psw_mask = extract_psw();
/* Verify that the RI bit is set in the PSW */
if (!(psw_mask & PSW_MASK_RI)) {
fail("Failed to enable RI");
return -1;
}
/* Collect RI records until we hit buffer-full condition */
while (ricb.rca < ricb.rla + 1) {
for (i = 0; i < 10000; i++)
asm volatile("" : : : "memory");
rioff();
stric(&ricb);
rion();
}
/* Disable RI */
rioff();
/* Save the current RI control block */
stric(&ricb);
ricb_check = ricb;
/* Re-enable RI for checkpoint */
rion();
/* Do C/R now */
test_daemon();
test_waitsig();
/* Verify that the RI bit is set in the PSW */
psw_mask = extract_psw();
if (!(psw_mask & PSW_MASK_RI)) {
fail("RI bit in PSW not set");
return -1;
}
/*
* Verify that the RI block has been restored correctly
* and the buffer is unchanged
*/
rioff();
stric(&ricb);
for (i = 0; i < 8; i++) {
if (ricb_ptr[i] == ricb_check_ptr[i])
continue;
/* Skip sf field because its value may change */
if (i == 6)
continue;
fail("%d:Got %016lx expected %016lx", i, ricb_ptr[i], ricb_check_ptr[i]);
return -1;
}
pass();
return 0;
}
| 4,668 | 20.817757 | 75 |
c
|
criu
|
criu-master/test/zdtm/static/seccomp_filter_threads.c
|
#include <unistd.h>
#include <stdbool.h>
#include <signal.h>
#include <stddef.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#ifdef __NR_seccomp
#include <linux/seccomp.h>
#include <linux/filter.h>
#include <linux/limits.h>
#include <pthread.h>
#endif
#include "zdtmtst.h"
#include "lock.h"
#ifndef SECCOMP_SET_MODE_FILTER
#define SECCOMP_SET_MODE_FILTER 1
#endif
#ifndef SECCOMP_FILTER_FLAG_TSYNC
#define SECCOMP_FILTER_FLAG_TSYNC 1
#endif
const char *test_doc = "Check threads to carry different seccomps";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
#ifdef __NR_seccomp
static long sys_gettid(void)
{
return syscall(__NR_gettid);
}
static futex_t *wait_rdy;
static futex_t *wait_run;
static int magic = 1234;
int get_seccomp_mode(pid_t pid)
{
FILE *f;
char buf[PATH_MAX];
sprintf(buf, "/proc/%d/status", pid);
f = fopen(buf, "r");
if (!f) {
pr_perror("fopen failed");
return -1;
}
while (NULL != fgets(buf, sizeof(buf), f)) {
int mode;
if (sscanf(buf, "Seccomp:\t%d", &mode) != 1)
continue;
fclose(f);
return mode;
}
fclose(f);
return -1;
}
int filter_syscall(int syscall_nr, unsigned int flags)
{
struct sock_filter filter[] = {
BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct seccomp_data, nr)),
BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, syscall_nr, 0, 1),
BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | (SECCOMP_RET_DATA & magic)),
BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW),
};
struct sock_fprog bpf_prog = {
.len = (unsigned short)(sizeof(filter) / sizeof(filter[0])),
.filter = filter,
};
if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, flags, &bpf_prog) < 0) {
pr_perror("seccomp failed");
return -1;
}
return 0;
}
int tigger_ptrace(void)
{
return ptrace(PTRACE_TRACEME);
}
int trigger_prctl(void)
{
return prctl(PR_SET_PDEATHSIG, 9, 0, 0, 0);
}
int trigger_mincore(void)
{
return mincore(NULL, 0, NULL);
}
#define gen_param(__syscall_nr, __trigger) \
{ \
.syscall_name = #__syscall_nr, .syscall_nr = __syscall_nr, .trigger = __trigger, \
}
struct {
char *syscall_name;
unsigned int syscall_nr;
int (*trigger)(void);
} pthread_seccomp_params[] = {
gen_param(__NR_ptrace, tigger_ptrace),
gen_param(__NR_prctl, trigger_prctl),
gen_param(__NR_mincore, trigger_mincore),
};
#define WAITER_VALS_OFFSET (ARRAY_SIZE(pthread_seccomp_params) * 2)
void *thread_main(void *arg)
{
int ret;
size_t nr = (long)arg;
if (filter_syscall(pthread_seccomp_params[nr].syscall_nr, 0) < 0)
pthread_exit((void *)1);
test_msg("%s filtered inside a sole thread %lu\n", pthread_seccomp_params[nr].syscall_name, sys_gettid());
futex_inc_and_wake(wait_rdy);
futex_wait_while_lt(wait_run, 1);
test_msg("Triggering %zu %s thread %lu\n", nr, pthread_seccomp_params[nr].syscall_name, sys_gettid());
ret = pthread_seccomp_params[nr].trigger();
if (ret == -1 && errno == magic)
return (void *)0;
test_msg("Abnormal exit %zu thread %lu\n", nr, sys_gettid());
return (void *)1;
}
int main(int argc, char **argv)
{
int ret, mode, status;
size_t i;
pid_t pid;
test_init(argc, argv);
wait_rdy = mmap(NULL, sizeof(*wait_rdy), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
wait_run = mmap(NULL, sizeof(*wait_rdy), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (wait_rdy == MAP_FAILED || wait_run == MAP_FAILED) {
pr_perror("mmap failed");
exit(1);
}
futex_init(wait_rdy);
futex_init(wait_run);
futex_set(wait_rdy, 0);
futex_set(wait_run, 0);
pid = fork();
if (pid < 0) {
pr_perror("fork");
return -1;
}
if (pid == 0) {
pthread_t thread[ARRAY_SIZE(pthread_seccomp_params)];
void *ret;
zdtm_seccomp = 1;
for (i = 0; i < ARRAY_SIZE(pthread_seccomp_params); i++) {
if (pthread_create(&thread[i], NULL, thread_main, (void *)i)) {
pr_perror("pthread_create");
exit(1);
}
}
for (i = 0; i < ARRAY_SIZE(pthread_seccomp_params); i++) {
test_msg("Waiting thread %zu\n", i);
if (pthread_join(thread[i], &ret) != 0) {
pr_perror("pthread_join");
exit(1);
}
if (ret != 0)
syscall(__NR_exit, 1);
}
syscall(__NR_exit, 0);
}
futex_wait_until(wait_rdy, ARRAY_SIZE(pthread_seccomp_params));
test_daemon();
test_waitsig();
futex_inc_and_wake(wait_run);
mode = get_seccomp_mode(pid);
if (mode != SECCOMP_MODE_DISABLED) {
fail("seccomp mode mismatch %d", mode);
return 1;
}
ret = waitpid(pid, &status, 0);
if (ret != pid) {
fail("waitpid: %d != %d", ret, pid);
exit(1);
}
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
fail("expected 0 exit, got %d", WEXITSTATUS(status));
exit(1);
}
pass();
return 0;
}
#else /* __NR_seccomp */
#define TEST_SKIP_REASON "incompatible kernel (no seccomp)"
#include "skip-me.c"
#endif /* __NR_seccomp */
| 5,058 | 20.345992 | 107 |
c
|
criu
|
criu-master/test/zdtm/static/session01.c
|
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include "zdtmtst.h"
#include "lock.h"
const char *test_doc = "Test that sid, pgid are restored";
const char *test_author = "Andrey Vagin <[email protected]>";
struct master {
pid_t pid;
pid_t ppid;
pid_t sid;
pid_t pgid;
};
struct testcase {
pid_t pid;
pid_t ppid;
pid_t sid;
pid_t born_sid;
pid_t pgid;
int alive;
struct master master;
futex_t futex;
};
enum {
TEST_FORK,
TEST_PGID,
TEST_WAIT,
TEST_MASTER,
TEST_CHECK,
TEST_EXIT,
};
static struct testcase *testcases;
static futex_t *fstate;
static struct testcase __testcases[] = {
{ 2, 1, 2, 1, 2, 1 }, /* session00 */
{ 4, 2, 4, 2, 4, 1 }, /* |\_session00 */
{ 15, 4, 4, 4, 15, 1 }, /* | |\_session00 */
{ 16, 4, 4, 4, 15, 1 }, /* | \_session00 */
{ 17, 4, 4, 4, 17, 0 }, /* | |\_session00 */
{ 18, 4, 4, 4, 17, 1 }, /* | \_session00 */
{ 5, 2, 2, 2, 2, 1 }, /* |\_session00 */
{ 8, 2, 8, 2, 8, 1 }, /* |\_session00 */
{ 9, 8, 2, 2, 2, 1 }, /* | \_session00 */
{ 10, 2, 10, 2, 10, 1 }, /* |\_session00 */
{ 11, 10, 11, 2, 11, 1 }, /* | \_session00 */
{ 12, 11, 2, 2, 2, 1 }, /* | \_session00 */
{ 13, 2, 2, 2, 2, 0 }, /* \_session00 */
{ 3, 13, 2, 2, 2, 1 }, /* session00 */
{ 6, 2, 6, 2, 6, 0 }, /* \_session00 */
{ 14, 6, 6, 6, 6, 1 }, /* session00 */
};
#define TESTS (sizeof(__testcases) / sizeof(struct testcase))
#define check(n, a, b) \
do { \
if ((a) != (b)) { \
pr_perror("%s mismatch %d != %d", n, a, b); \
goto err; \
} \
} while (0)
static int child(const int c);
static int fork_children(struct testcase *t, int leader)
{
int i;
pid_t cid;
for (i = 0; i < TESTS; i++) {
if (t->pid != testcases[i].ppid)
continue;
if (leader ^ (t->pid == testcases[i].born_sid))
continue;
cid = test_fork_id(i);
if (cid < 0)
goto err;
if (cid == 0) {
test_msg("I'm %d with pid %d\n", i, getpid());
child(i);
exit(0);
}
testcases[i].master.pid = cid;
}
return 0;
err:
return -1;
}
static int child(const int c)
{
int i;
struct testcase *t = &testcases[c];
t->master.pid = getpid();
if (fork_children(t, 0))
goto err;
if (t->pid == t->sid) {
if (getpid() != getsid(0))
if (setsid() < 0)
goto err;
if (fork_children(t, 1))
goto err;
}
if (t->pid == t->pgid) {
if (getpid() != getpgid(0))
if (setpgid(getpid(), getpid()) < 0) {
pr_perror("setpgid() failed");
goto err;
}
t->master.pgid = t->master.pid;
}
futex_set_and_wake(&t->futex, c);
if (c == 0)
goto out;
futex_wait_until(fstate, TEST_PGID);
for (i = 0; i < TESTS; i++) {
if (c == 0)
break;
if (t->pgid != testcases[i].pid)
continue;
if (getpgid(0) != testcases[i].master.pid)
if (setpgid(getpid(), testcases[i].master.pid) < 0) {
pr_perror("setpgid() failed (%d) (%d)", c, i);
goto err;
}
t->master.pgid = testcases[i].master.pid;
break;
}
futex_set_and_wake(&t->futex, c);
futex_wait_until(fstate, TEST_WAIT);
for (i = 0; i < TESTS; i++) {
if (t->pid != testcases[i].ppid)
continue;
if (testcases[i].alive)
continue;
test_msg("Wait process %d (pid %d)\n", i, testcases[i].master.pid);
waitpid(testcases[i].master.pid, NULL, 0);
}
if (!t->alive)
goto out;
futex_set_and_wake(&t->futex, c);
futex_wait_until(fstate, TEST_MASTER);
/* Save the master copy */
t->master.ppid = getppid();
t->master.sid = getsid(0);
futex_set_and_wake(&t->futex, c);
futex_wait_until(fstate, TEST_CHECK);
check("pid", t->master.pid, getpid());
check("ppid", t->master.ppid, getppid());
check("sid", t->master.sid, getsid(0));
check("pgid", t->master.pgid, getpgid(0));
futex_set_and_wake(&t->futex, c);
/* Wait while all test cases check results */
futex_wait_until(fstate, TEST_EXIT);
out:
return 0;
err:
futex_set_and_wake(&t->futex, -1);
return 1;
}
int main(int argc, char **argv)
{
int i, err, ret;
void *ptr;
BUG_ON(sizeof(*fstate) + sizeof(__testcases) > 4096);
ptr = mmap(NULL, 4096, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (ptr == MAP_FAILED)
return 1;
fstate = ptr;
futex_set(fstate, TEST_FORK);
testcases = ptr + sizeof(*fstate);
memcpy(testcases, &__testcases, sizeof(__testcases));
test_init(argc, argv);
testcases[0].master.pid = getpid();
if (child(0))
goto err;
for (i = 1; i < TESTS; i++) {
ret = futex_wait_while(&testcases[i].futex, 0);
if (ret < 0)
return 1;
futex_set(&testcases[i].futex, 0);
}
test_msg("TEST_PGID\n");
futex_set_and_wake(fstate, TEST_PGID);
for (i = 1; i < TESTS; i++) {
ret = futex_wait_while(&testcases[i].futex, 0);
if (ret < 0)
goto err;
futex_set(&testcases[i].futex, 0);
}
test_msg("TEST_WAIT\n");
futex_set_and_wake(fstate, TEST_WAIT);
for (i = 1; i < TESTS; i++) {
if (!testcases[i].alive)
continue;
ret = futex_wait_while(&testcases[i].futex, 0);
if (ret < 0)
goto err;
futex_set(&testcases[i].futex, 0);
}
for (i = 0; i < TESTS; i++) {
if (testcases[0].pid != testcases[i].ppid)
continue;
if (testcases[i].alive)
continue;
test_msg("Wait process %d (pid %d)\n", i, testcases[i].master.pid);
waitpid(testcases[i].master.pid, NULL, 0);
}
test_msg("TEST_MASTER\n");
futex_set_and_wake(fstate, TEST_MASTER);
for (i = 1; i < TESTS; i++) {
if (!testcases[i].alive)
continue;
ret = futex_wait_while(&testcases[i].futex, 0);
if (ret < 0)
goto err;
futex_set(&testcases[i].futex, 0);
test_msg("The process %d initialized\n", ret);
}
test_daemon();
test_waitsig();
err = 0;
for (i = 1; i < TESTS; i++) {
int j;
struct testcase *t = testcases + i;
pid_t sid, pgid;
if (!t->alive)
continue;
for (j = 0; j < TESTS; j++) {
struct testcase *p = testcases + j;
/* sanity check */
if (p->pid == t->sid && t->master.sid != p->master.pid) {
pr_perror("session mismatch (%d) %d != (%d) %d", i, t->master.sid, j, p->master.pid);
err++;
}
if (p->pid == t->pgid && t->master.pgid != p->master.pid) {
pr_perror("pgid mismatch (%d) %d != (%d) %d", i, t->master.pgid, j, p->master.pid);
err++;
}
}
sid = getsid(t->master.pid);
if (t->master.sid != sid) {
pr_perror("%d: session mismatch %d (expected %d)", i, sid, t->master.sid);
err++;
}
pgid = getpgid(t->master.pid);
if (t->master.pgid != pgid) {
pr_perror("%d: pgid mismatch %d (expected %d)", i, t->master.pgid, pgid);
err++;
}
}
test_msg("TEST_CHECK\n");
futex_set_and_wake(fstate, TEST_CHECK);
for (i = 1; i < TESTS; i++) {
if (!testcases[i].alive)
continue;
ret = futex_wait_while(&testcases[i].futex, 0);
if (ret < 0)
goto err;
futex_set(&testcases[i].futex, 0);
if (ret < 0) {
fail("Someone failed");
err++;
continue;
}
test_msg("The process %u is restored correctly\n", (unsigned)ret);
}
test_msg("TEST_EXIT\n");
futex_set_and_wake(fstate, TEST_EXIT);
if (!err)
pass();
return 0;
err:
for (i = 1; i < TESTS; i++) {
pid_t pid = testcases[i].master.pid;
if (pid > 0) {
ret = kill(pid, SIGKILL);
test_msg("kill %d %s\n", pid, strerror(ret == -1 ? errno : 0));
}
}
return 1;
}
| 7,450 | 20.979351 | 89 |
c
|
criu
|
criu-master/test/zdtm/static/shared_mount_propagation.c
|
#include <fcntl.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include "zdtmtst.h"
const char *test_doc = "Check mounts are propagated to shared mounts";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
int main(int argc, char **argv)
{
char dir_a[PATH_MAX], dir_b[PATH_MAX], dir_c[PATH_MAX];
char dir_d[PATH_MAX], dir_e[PATH_MAX], dir_f[PATH_MAX];
char test_file[PATH_MAX];
char test_bind_file1[PATH_MAX];
char test_bind_file2[PATH_MAX];
char test_bind_file3[PATH_MAX];
int fd;
test_init(argc, argv);
mkdir(dirname, 0700);
if (mount(dirname, dirname, NULL, MS_BIND, NULL)) {
pr_perror("Unable to self bind mount %s", dirname);
return 1;
}
if (mount(NULL, dirname, NULL, MS_SHARED, NULL)) {
pr_perror("Unable to make shared mount %s", dirname);
return 1;
}
ssprintf(dir_a, "%s/a", dirname);
ssprintf(dir_d, "%s/d", dirname);
ssprintf(dir_e, "%s/e", dirname);
ssprintf(dir_f, "%s/f", dirname);
mkdir(dir_a, 0700);
mkdir(dir_d, 0700);
mkdir(dir_e, 0700);
mkdir(dir_f, 0700);
ssprintf(dir_b, "%s/b", dir_a);
ssprintf(dir_c, "%s/c", dir_b);
mkdir(dir_b, 0700);
mkdir(dir_c, 0700);
if (mount(dir_a, dir_d, NULL, MS_BIND, NULL)) {
pr_perror("Unable to bind mount %s to %s", dir_a, dir_d);
return 1;
}
if (mount(dir_b, dir_e, NULL, MS_BIND, NULL)) {
pr_perror("Unable to bind mount %s to %s", dir_b, dir_e);
return 1;
}
if (mount(dir_f, dir_c, NULL, MS_BIND, NULL)) {
pr_perror("Unable to bind mount %s to %s", dir_f, dir_c);
return 1;
}
ssprintf(test_file, "%s/file", dir_f);
fd = open(test_file, O_CREAT | O_WRONLY | O_EXCL, 0600);
if (fd < 0) {
pr_perror("Unable to open %s", test_file);
return 1;
}
close(fd);
test_daemon();
test_waitsig();
ssprintf(test_bind_file1, "%s/file", dir_c);
ssprintf(test_bind_file2, "%s/b/c/file", dir_d);
ssprintf(test_bind_file3, "%s/c/file", dir_e);
if (access(test_file, F_OK)) {
pr_perror("%s doesn't exist", test_file);
return 1;
}
if (access(test_bind_file1, F_OK)) {
pr_perror("%s doesn't exist", test_bind_file1);
return 1;
}
if (access(test_bind_file2, F_OK)) {
pr_perror("%s doesn't exist", test_bind_file2);
return 1;
}
if (access(test_bind_file3, F_OK)) {
pr_perror("%s doesn't exist", test_bind_file3);
return 1;
}
if (umount(dir_c)) {
pr_perror("Unable to umount %s", dir_c);
return 1;
}
if (umount(dir_e)) {
pr_perror("Unable to umount %s", dir_e);
return 1;
}
if (umount(dir_d)) {
pr_perror("Unable to umount %s", dir_d);
return 1;
}
pass();
return 0;
}
| 2,649 | 21.083333 | 73 |
c
|
criu
|
criu-master/test/zdtm/static/shmemfd-priv.c
|
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/vfs.h>
#include <fcntl.h>
#include "zdtmtst.h"
const char *test_doc = "Test C/R of shared memory file descriptors";
const char *test_author = "Andrei Vagin <[email protected]>";
#define err(exitcode, msg, ...) \
({ \
pr_perror(msg, ##__VA_ARGS__); \
exit(exitcode); \
})
int main(int argc, char *argv[])
{
void *addr, *priv_addr, *addr2;
char path[4096];
int fd;
test_init(argc, argv);
addr = mmap(NULL, 5 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (addr == MAP_FAILED) {
pr_perror("mmap");
return 1;
}
*(int *)addr = 1;
*(int *)(addr + PAGE_SIZE) = 11;
*(int *)(addr + 2 * PAGE_SIZE) = 111;
snprintf(path, sizeof(path), "/proc/self/map_files/%lx-%lx", (long)addr, (long)addr + 5 * PAGE_SIZE);
fd = open(path, O_RDWR | O_LARGEFILE);
if (fd < 0)
err(1, "Can't open %s", path);
priv_addr = mmap(NULL, 5 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_PRIVATE, fd, PAGE_SIZE);
if (priv_addr == MAP_FAILED) {
pr_perror("mmap");
return 1;
}
addr2 = mmap(NULL, 5 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 2 * PAGE_SIZE);
if (addr2 == MAP_FAILED) {
pr_perror("mmap");
return 1;
}
*(int *)(priv_addr + PAGE_SIZE) = 22;
test_daemon();
test_waitsig();
if (*(int *)(priv_addr + PAGE_SIZE) != 22) {
fail("the second page of the private mapping is corrupted");
return 1;
}
if (*(int *)(priv_addr) != 11) {
fail("the first page of the private mapping is corrupted");
return 1;
}
if (*(int *)(addr2) != 111) {
fail("the first page of the second shared mapping is corrupted");
return 1;
}
*(int *)(addr2) = 333;
if (*(int *)(addr + 2 * PAGE_SIZE) != 333) {
fail("the first page of the second shared mapping isn't shared");
return 1;
}
*(int *)(addr + 3 * PAGE_SIZE) = 444;
if (*(int *)(priv_addr + 2 * PAGE_SIZE) != 444) {
fail("the third page of the private mapping is corrupted");
return 1;
}
pass();
return 0;
}
| 2,135 | 23.272727 | 102 |
c
|
criu
|
criu-master/test/zdtm/static/sigaltstack.c
|
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "zdtmtst.h"
const char *test_doc = "Check for alternate signal stack";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
#define TESTSIGSTKSZ 16384
static char stack_thread[TESTSIGSTKSZ + TEST_MSG_BUFFER_SIZE] __stack_aligned__;
static char stack_main[TESTSIGSTKSZ + TEST_MSG_BUFFER_SIZE] __stack_aligned__;
enum {
SAS_MAIN_OLD,
SAS_MAIN_NEW,
SAS_THRD_OLD,
SAS_THRD_NEW,
SAS_MAX
};
static stack_t sas_state[SAS_MAX];
static task_waiter_t t;
#define exit_group(code) syscall(__NR_exit_group, code)
#define gettid() syscall(__NR_gettid)
static int sascmp(stack_t *old, stack_t *new)
{
return old->ss_size != new->ss_size || old->ss_sp != new->ss_sp || old->ss_flags != new->ss_flags;
}
static void show_ss(char *prefix, stack_t *s)
{
test_msg("%20s: at %p (size %8zu flags %#2x)\n", prefix, s->ss_sp, s->ss_size, s->ss_flags);
}
void thread_sigaction(int signo, siginfo_t *info, void *context)
{
if (sigaltstack(NULL, &sas_state[SAS_THRD_NEW]))
pr_perror("thread sigaltstack");
show_ss("thread in sas", &sas_state[SAS_THRD_NEW]);
task_waiter_complete(&t, 2);
test_msg("Waiting in thread SAS\n");
task_waiter_wait4(&t, 3);
test_msg("Leaving thread SAS\n");
}
static void *thread_func(void *arg)
{
struct sigaction sa = {
.sa_sigaction = thread_sigaction,
.sa_flags = SA_RESTART | SA_ONSTACK,
};
sas_state[SAS_THRD_OLD] = (stack_t){
.ss_size = sizeof(stack_thread) - 8,
.ss_sp = stack_thread,
.ss_flags = 0,
};
sigemptyset(&sa.sa_mask);
if (sigaction(SIGUSR2, &sa, NULL)) {
pr_perror("Can't set SIGUSR2 handler");
exit_group(-1);
}
task_waiter_wait4(&t, 1);
if (sigaltstack(&sas_state[SAS_THRD_OLD], NULL)) {
pr_perror("thread sigaltstack");
exit_group(-1);
}
syscall(__NR_tkill, gettid(), SIGUSR2);
return NULL;
}
void leader_sigaction(int signo, siginfo_t *info, void *context)
{
if (sigaltstack(NULL, &sas_state[SAS_MAIN_NEW]))
pr_perror("leader sigaltstack");
show_ss("leader in sas", &sas_state[SAS_MAIN_NEW]);
}
int main(int argc, char *argv[])
{
pthread_t thread;
struct sigaction sa = {
.sa_sigaction = leader_sigaction,
.sa_flags = SA_RESTART | SA_ONSTACK,
};
sas_state[SAS_MAIN_OLD] = (stack_t){
.ss_size = sizeof(stack_main) - 8,
.ss_sp = stack_main,
.ss_flags = 0,
};
sigemptyset(&sa.sa_mask);
test_init(argc, argv);
task_waiter_init(&t);
if (sigaction(SIGUSR1, &sa, NULL)) {
pr_perror("Can't set SIGUSR1 handler");
exit(-1);
}
if (pthread_create(&thread, NULL, &thread_func, NULL)) {
pr_perror("Can't create thread");
exit(-1);
}
if (sigaltstack(&sas_state[SAS_MAIN_OLD], NULL)) {
pr_perror("sigaltstack");
exit(-1);
}
task_waiter_complete(&t, 1);
task_waiter_wait4(&t, 2);
test_daemon();
test_waitsig();
test_msg("Thread may leave SAS\n");
task_waiter_complete(&t, 3);
syscall(__NR_tkill, gettid(), SIGUSR1);
if (pthread_join(thread, NULL)) {
fail("Error joining thread");
exit(-1);
}
task_waiter_fini(&t);
sas_state[SAS_THRD_OLD].ss_flags = SS_ONSTACK;
sas_state[SAS_MAIN_OLD].ss_flags = SS_ONSTACK;
show_ss("main old", &sas_state[SAS_MAIN_OLD]);
show_ss("main new", &sas_state[SAS_MAIN_NEW]);
show_ss("thrd old", &sas_state[SAS_THRD_OLD]);
show_ss("thrd new", &sas_state[SAS_THRD_NEW]);
if (sascmp(&sas_state[SAS_MAIN_OLD], &sas_state[SAS_MAIN_NEW]) ||
sascmp(&sas_state[SAS_THRD_OLD], &sas_state[SAS_THRD_NEW])) {
fail("sas not restored");
} else
pass();
return 0;
}
| 3,652 | 20.615385 | 99 |
c
|
criu
|
criu-master/test/zdtm/static/sigpending.c
|
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>
#include <string.h>
#include <limits.h>
#include <sys/wait.h>
#include "zdtmtst.h"
const char *test_doc = "Check pending signals";
const char *test_author = "Andrew Vagin <[email protected]>";
static pid_t child;
static int numsig;
#define TESTSIG (SIGRTMAX)
#define THREADSIG (SIGRTMIN)
static siginfo_t share_infos[2];
static siginfo_t self_infos[64]; /* self */
static siginfo_t thread_infos[3]; /* thread */
static int share_nr;
static int self_nr;
static int thread_nr;
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t) & ((TYPE *)0)->MEMBER)
#endif
/* cr_siginfo is declared to get an offset of _sifields */
union cr_siginfo {
struct {
int si_signo;
int si_errno;
int si_code;
union {
int _pad[10];
/* ... */
} _sifields;
} _info;
siginfo_t info;
};
typedef union cr_siginfo cr_siginfo_t;
#define siginf_body(s) (&((cr_siginfo_t *)(s))->_info._sifields)
/*
* The kernel puts only relevant union member when signal arrives,
* leaving _si_fields to be filled with junk from stack. Check only
* first 12 bytes:
* // POSIX.1b signals.
* struct
* {
* __pid_t si_pid; // Sending process ID.
* __uid_t si_uid; // Real user ID of sending process.
* sigval_t si_sigval; // Signal value.
* } _rt;
* Look at __copy_siginfo_to_user32() for more information.
*/
#define _si_fields_sz 12
#define siginfo_filled (offsetof(cr_siginfo_t, _info._sifields) + _si_fields_sz)
static pthread_mutex_t exit_lock;
static pthread_mutex_t init_lock;
static void sig_handler(int signal, siginfo_t *info, void *data)
{
uint32_t crc;
test_msg("signo=%d si_code=%x\n", signal, info->si_code);
if (test_go()) {
pr_perror("The signal is received before unlocking");
return;
}
switch (signal) {
case SIGCHLD:
if ((info->si_code & CLD_EXITED) && (info->si_pid == child) && (info->si_status == 5))
numsig++;
else {
fail("Wrong siginfo");
exit(1);
}
return;
}
if (TESTSIG == signal || THREADSIG == signal) {
siginfo_t *src;
if (signal == TESTSIG) {
src = &share_infos[share_nr];
share_nr++;
} else if (getpid() == syscall(SYS_gettid)) {
src = &self_infos[self_nr];
self_nr++;
} else {
src = &thread_infos[thread_nr];
thread_nr++;
}
crc = ~0;
if (datachk((uint8_t *)siginf_body(info), _si_fields_sz, &crc)) {
fail("CRC mismatch");
return;
}
if (memcmp(info, src, siginfo_filled)) {
fail("Source and received info are differ");
return;
}
numsig++;
return;
}
pr_perror("Unexpected signal");
exit(1);
}
static int thread_id;
static void *thread_fn(void *args)
{
sigset_t blockmask, oldset, newset;
struct sigaction act;
memset(&oldset, 0, sizeof(oldset));
memset(&newset, 0, sizeof(oldset));
sigfillset(&blockmask);
sigdelset(&blockmask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &blockmask, NULL) == -1) {
pr_perror("sigprocmask");
return NULL;
}
if (sigprocmask(SIG_SETMASK, NULL, &oldset) == -1) {
pr_perror("sigprocmask");
return NULL;
}
thread_id = syscall(SYS_gettid);
act.sa_flags = SA_SIGINFO | SA_RESTART;
act.sa_sigaction = sig_handler;
sigemptyset(&act.sa_mask);
sigaddset(&act.sa_mask, TESTSIG);
sigaddset(&act.sa_mask, THREADSIG);
if (sigaction(TESTSIG, &act, NULL)) {
pr_perror("sigaction() failed");
return NULL;
}
pthread_mutex_unlock(&init_lock);
pthread_mutex_lock(&exit_lock);
if (sigprocmask(SIG_UNBLOCK, &blockmask, &newset) == -1) {
pr_perror("sigprocmask");
return NULL;
}
sigdelset(&oldset, SIGTRAP);
sigdelset(&newset, SIGTRAP);
if (memcmp(&newset, &oldset, sizeof(newset))) {
fail("The signal blocking mask was changed");
numsig = INT_MAX;
}
return NULL;
}
static int sent_sigs;
int send_siginfo(int signo, pid_t pid, pid_t tid, int group, siginfo_t *info)
{
static int si_code = -10;
uint32_t crc = ~0;
info->si_code = si_code;
si_code--;
info->si_signo = signo;
datagen((uint8_t *)siginf_body(info), _si_fields_sz, &crc);
sent_sigs++;
if (group)
return syscall(SYS_rt_sigqueueinfo, pid, signo, info);
else
return syscall(SYS_rt_tgsigqueueinfo, pid, tid, signo, info);
}
int main(int argc, char **argv)
{
sigset_t blockmask, oldset, newset;
struct sigaction act;
pthread_t pthrd;
siginfo_t infop;
int i;
memset(&oldset, 0, sizeof(oldset));
memset(&newset, 0, sizeof(oldset));
test_init(argc, argv);
pthread_mutex_init(&exit_lock, NULL);
pthread_mutex_lock(&exit_lock);
pthread_mutex_init(&init_lock, NULL);
pthread_mutex_lock(&init_lock);
if (pthread_create(&pthrd, NULL, thread_fn, NULL)) {
pr_perror("Can't create a thread");
return 1;
}
pthread_mutex_lock(&init_lock);
sigfillset(&blockmask);
sigdelset(&blockmask, SIGTERM);
if (sigprocmask(SIG_BLOCK, &blockmask, NULL) == -1) {
pr_perror("sigprocmask");
return -1;
}
if (sigprocmask(SIG_BLOCK, NULL, &oldset) == -1) {
pr_perror("sigprocmask");
return -1;
}
child = fork();
if (child == -1) {
pr_perror("fork");
return -1;
}
if (child == 0)
return 5; /* SIGCHLD */
if (waitid(P_PID, child, &infop, WNOWAIT | WEXITED)) {
pr_perror("waitid");
return 1;
}
sent_sigs++;
for (i = 0; i < sizeof(share_infos) / sizeof(siginfo_t); i++) {
send_siginfo(TESTSIG, getpid(), -1, 1, share_infos + i);
}
for (i = 0; i < sizeof(self_infos) / sizeof(siginfo_t); i++) {
send_siginfo(THREADSIG, getpid(), getpid(), 0, self_infos + i);
}
for (i = 0; i < sizeof(thread_infos) / sizeof(siginfo_t); i++) {
send_siginfo(THREADSIG, getpid(), thread_id, 0, thread_infos + i);
}
act.sa_flags = SA_SIGINFO | SA_RESTART;
act.sa_sigaction = sig_handler;
sigemptyset(&act.sa_mask);
if (sigaction(SIGCHLD, &act, NULL)) {
pr_perror("sigaction() failed");
return -1;
}
sigaddset(&act.sa_mask, TESTSIG);
sigaddset(&act.sa_mask, THREADSIG);
if (sigaction(TESTSIG, &act, NULL)) {
pr_perror("sigaction() failed");
return -1;
}
if (sigaction(THREADSIG, &act, NULL)) {
pr_perror("sigaction() failed");
return -1;
}
test_daemon();
test_waitsig();
if (sigprocmask(SIG_UNBLOCK, &blockmask, &newset) == -1) {
pr_perror("sigprocmask");
return -1;
}
pthread_mutex_unlock(&exit_lock);
pthread_join(pthrd, NULL);
sigdelset(&oldset, SIGTRAP);
sigdelset(&newset, SIGTRAP);
if (memcmp(&newset, &oldset, sizeof(newset))) {
fail("The signal blocking mask was changed");
return 1;
}
if (numsig == sent_sigs)
pass();
return 0;
}
| 6,497 | 20.304918 | 88 |
c
|
criu
|
criu-master/test/zdtm/static/sk-unix01.c
|
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include "zdtmtst.h"
const char *test_doc = "Check that deleted unix sockets with dirs are restored correctly";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
#ifdef ZDTM_UNIX_SEQPACKET
#define SOCK_TYPE SOCK_SEQPACKET
#else
#define SOCK_TYPE SOCK_STREAM
#endif
static int sk_alloc_bind(int type, struct sockaddr_un *addr)
{
int sk;
sk = socket(PF_UNIX, type, 0);
if (sk < 0) {
pr_perror("socket");
return -1;
}
if (addr && bind(sk, (const struct sockaddr *)addr, sizeof(*addr))) {
pr_perror("bind %s", addr->sun_path);
close(sk);
return -1;
}
return sk;
}
static int sk_alloc_connect(int type, struct sockaddr_un *addr)
{
int sk;
sk = socket(PF_UNIX, type, 0);
if (sk < 0) {
pr_perror("socket");
return -1;
}
if (connect(sk, (const struct sockaddr *)addr, sizeof(*addr))) {
pr_perror("connect %s", addr->sun_path);
close(sk);
return -1;
}
return sk;
}
#define write_int(__f, __p) \
({ \
ssize_t __r = write(__f, __p, sizeof(*(__p))); \
(__r == sizeof(*(__p))) ? 0 : -1; \
})
#define read_int(__f, __p) \
({ \
ssize_t __r = read(__f, __p, sizeof(*(__p))); \
(__r == sizeof(*(__p))) ? 0 : -1; \
})
int main(int argc, char **argv)
{
int c1 = 1, c2 = 0, c3 = 3, c4 = 0;
int c5 = 5, c6 = 0, c7 = 7, c8 = 0;
int c9 = 8, c10 = 0;
char filename[PATH_MAX];
char subdir_dg[PATH_MAX];
char subdir_st[PATH_MAX];
struct sockaddr_un addr_from;
struct sockaddr_un addr;
int sk_dgram_pair[2];
int sk_dgram[9];
socklen_t len;
int sk_st[5];
DIR *dir;
test_init(argc, argv);
/*
* All sockets are under dir to not clash
* with other tests.
*/
if (mkdir(dirname, 0755) < 0) {
if (errno != EEXIST) {
pr_perror("Can't create %s", dirname);
return 1;
}
}
/*
* Subdir for dgram sockets.
*/
ssprintf(subdir_dg, "%s/%s", dirname, "dg");
if (mkdir(subdir_dg, 0755) < 0) {
if (errno != EEXIST) {
pr_perror("Can't create %s", subdir_dg);
return 1;
}
}
/*
* Subdir for stream sockets.
*/
ssprintf(subdir_st, "%s/%s", dirname, "st");
if (mkdir(subdir_st, 0755) < 0) {
if (errno != EEXIST) {
pr_perror("Can't create %s", subdir_st);
return 1;
}
}
/*
* DGRAM sockets
*
* - create 2 sockets
* - bind first to subdired
* - connect second to it
* - delete socket on fs
* - do the same for second pair with same name
* - delete socket on fs
* - create 3 more sockets
* - bind /connect to same name, where one is deleted
*/
ssprintf(filename, "%s/%s", subdir_dg, "sk-dt");
if (unix_fill_sock_name(&addr, filename))
return 1;
unlink(addr.sun_path);
sk_dgram[0] = sk_alloc_bind(SOCK_DGRAM, &addr);
if (sk_dgram[0] < 0)
return 1;
test_msg("sk-dt: alloc/bind %d %s\n", sk_dgram[0], addr.sun_path);
sk_dgram[1] = sk_alloc_connect(SOCK_DGRAM, &addr);
if (sk_dgram[1] < 0)
return 1;
unlink(addr.sun_path);
test_msg("sk-dt: alloc/connect/unlink %d %s\n", sk_dgram[1], addr.sun_path);
sk_dgram[2] = sk_alloc_bind(SOCK_DGRAM, &addr);
if (sk_dgram[2] < 0)
return 1;
test_msg("sk-dt: alloc/bind %d %s\n", sk_dgram[2], addr.sun_path);
sk_dgram[3] = sk_alloc_connect(SOCK_DGRAM, &addr);
if (sk_dgram[3] < 0)
return 1;
unlink(addr.sun_path);
test_msg("sk-dt: alloc/connect/unlink %d %s\n", sk_dgram[3], addr.sun_path);
ssprintf(filename, "%s/%s", dirname, "sole");
if (unix_fill_sock_name(&addr, filename))
return 1;
unlink(addr.sun_path);
sk_dgram[4] = sk_alloc_bind(SOCK_DGRAM, &addr);
if (sk_dgram[4] < 0)
return 1;
test_msg("sk-dt: alloc/bind %d %s\n", sk_dgram[4], addr.sun_path);
sk_dgram[5] = sk_alloc_connect(SOCK_DGRAM, &addr);
if (sk_dgram[5] < 0)
return 1;
unlink(addr.sun_path);
test_msg("sk-dt: alloc/connect/unlink %d %s\n", sk_dgram[5], addr.sun_path);
sk_dgram[6] = sk_alloc_bind(SOCK_DGRAM, &addr);
if (sk_dgram[6] < 0)
return 1;
test_msg("sk-dt: alloc/bind %d %s\n", sk_dgram[6], addr.sun_path);
sk_dgram[7] = sk_alloc_connect(SOCK_DGRAM, &addr);
if (sk_dgram[7] < 0)
return 1;
unlink(addr.sun_path);
test_msg("sk-dt: alloc/connect/unlink %d %s\n", sk_dgram[7], addr.sun_path);
sk_dgram[8] = sk_alloc_bind(SOCK_DGRAM, &addr);
if (sk_dgram[8] < 0)
return 1;
test_msg("sk-dt: alloc/bind %d %s\n", sk_dgram[8], addr.sun_path);
if (dup2(sk_dgram[4], 110) < 0 || dup2(sk_dgram[6], 100) < 0) {
pr_perror("Can't move socket");
return 1;
}
close(sk_dgram[4]);
sk_dgram[4] = 110;
close(sk_dgram[6]);
sk_dgram[6] = 100;
/*
* DGRAM paired sockets. Just bind both to the same name.
*/
if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sk_dgram_pair)) {
pr_perror("Can't create dgram pair");
return 1;
}
test_msg("sk-dgp: sockpair %d %d\n", sk_dgram_pair[0], sk_dgram_pair[1]);
ssprintf(filename, "%s/%s", subdir_dg, "sk-dtp");
if (unix_fill_sock_name(&addr, filename)) {
pr_err("%s is too long for socket\n", filename);
return 1;
}
if (bind(sk_dgram_pair[0], (const struct sockaddr *)&addr, sizeof(addr))) {
pr_perror("bind %d to %s", sk_dgram_pair[0], addr.sun_path);
return -1;
}
unlink(addr.sun_path);
if (bind(sk_dgram_pair[1], (const struct sockaddr *)&addr, sizeof(addr))) {
pr_perror("bind %d to %s", sk_dgram_pair[1], addr.sun_path);
return -1;
}
unlink(addr.sun_path);
/*
* Drop subdirectory.
*/
rmdir(subdir_dg);
/*
* STREAM sockets
*
* - create server, bind to subdired
* - create client
* - connect to server
* - delete socket on fs
* - bind again to subdired
* - connect to server
* - delete socket on fs
*/
ssprintf(filename, "%s/%s", subdir_st, "sk-st");
if (unix_fill_sock_name(&addr, filename))
return 1;
unlink(addr.sun_path);
sk_st[0] = sk_alloc_bind(SOCK_TYPE, &addr);
if (sk_st[0] < 0)
return 1;
test_msg("sk-st: alloc/bind/listen %d\n", sk_st[0]);
if (listen(sk_st[0], 16)) {
pr_perror("Can't listen on socket");
return 1;
}
sk_st[1] = sk_alloc_connect(SOCK_TYPE, &addr);
if (sk_st[1] < 0)
return 1;
test_msg("sk-st: alloc/connect %d\n", sk_st[1]);
len = sizeof(addr_from);
sk_st[2] = accept(sk_st[0], (struct sockaddr *)&addr_from, &len);
if (sk_st[2] < 0) {
pr_perror("Can't accept on socket");
return 1;
}
test_msg("sk-st: accept %d\n", sk_st[2]);
sk_st[3] = sk_alloc_connect(SOCK_TYPE, &addr);
if (sk_st[3] < 0)
return 1;
test_msg("sk-st: alloc/connect %d\n", sk_st[3]);
len = sizeof(addr_from);
sk_st[4] = accept(sk_st[0], (struct sockaddr *)&addr_from, &len);
if (sk_st[4] < 0) {
pr_perror("Can't accept on socket");
return 1;
}
test_msg("sk-st: accept %d\n", sk_st[4]);
unlink(addr.sun_path);
/*
* Drop subdirectory.
*/
rmdir(subdir_st);
test_daemon();
test_waitsig();
if (write_int(sk_dgram[1], &c1) || read_int(sk_dgram[0], &c2) || write_int(sk_dgram[3], &c3) ||
read_int(sk_dgram[2], &c4)) {
fail("Unable to send/receive a message on dgram");
return 1;
}
if (c1 != c2 || c3 != c4) {
fail("Vals mismatch on dgram: c1 %d c2 %d c3 %d c4 %d", c1, c2, c3, c4);
return 1;
}
if (write_int(sk_dgram_pair[1], &c9) || read_int(sk_dgram_pair[0], &c10)) {
fail("Unable to send/receive a message on paired dgram");
return 1;
}
if (c9 != c10) {
fail("Vals mismatch on dgram: c9 %d c10 %d", c9, c10);
return 1;
}
if (write_int(sk_st[2], &c5) || read_int(sk_st[1], &c6) || write_int(sk_st[4], &c7) ||
read_int(sk_st[3], &c8)) {
fail("Unable to send/receive a message on stream");
return 1;
}
if (c5 != c6 || c7 != c8) {
fail("Vals mismatch on stream: c5 %d c6 %d c7 %d c8 %d", c5, c6, c7, c8);
return 1;
}
dir = opendir(subdir_dg);
if (dir != NULL || errno != ENOENT) {
fail("Directory %s is not deteled", subdir_dg);
return 1;
}
dir = opendir(subdir_st);
if (dir != NULL || errno != ENOENT) {
fail("Directory %s is not deteled", subdir_st);
return 1;
}
pass();
return 0;
}
| 8,368 | 22.377095 | 96 |
c
|
criu
|
criu-master/test/zdtm/static/sock_ip_opts00.c
|
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <linux/in.h>
#include <linux/in6.h>
#include "zdtmtst.h"
const char *test_doc = "Check that different ip socket options are restored";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
#ifdef ZDTM_VAL_ZERO
#define IP_OPT_VAL 0
#else
#define IP_OPT_VAL 1
#endif
struct sk_opt {
int level;
int opt;
};
struct sk_opt sk_opts_v4[] = {
{ SOL_IP, IP_FREEBIND },
{ SOL_IP, IP_PKTINFO },
};
#ifndef IPV6_FREEBIND
#define IPV6_FREEBIND 78
#endif
struct sk_opt sk_opts_v6[] = {
{ SOL_IPV6, IPV6_FREEBIND },
{ SOL_IPV6, IPV6_RECVPKTINFO },
};
struct sk_conf {
int domain;
int type;
int protocol;
int sk;
} sk_confs[] = {
{ AF_INET, SOCK_DGRAM, IPPROTO_UDP },
{ AF_INET, SOCK_RAW, IPPROTO_UDP },
{ AF_INET6, SOCK_DGRAM, IPPROTO_UDP },
{ AF_INET6, SOCK_RAW, IPPROTO_UDP },
};
int main(int argc, char **argv)
{
struct sk_opt *opts;
int exit_code = 1;
int i, j, val;
socklen_t len;
int n_opts;
test_init(argc, argv);
for (i = 0; i < ARRAY_SIZE(sk_confs); i++) {
sk_confs[i].sk = socket(sk_confs[i].domain, sk_confs[i].type, sk_confs[i].protocol);
if (sk_confs[i].sk == -1) {
pr_perror("socket(%d,%d,%d) failed", sk_confs[i].domain, sk_confs[i].type,
sk_confs[i].protocol);
goto close;
}
}
for (i = 0; i < ARRAY_SIZE(sk_confs); i++) {
opts = sk_confs[i].domain == AF_INET ? sk_opts_v4 : sk_opts_v6;
n_opts = sk_confs[i].domain == AF_INET ? ARRAY_SIZE(sk_opts_v4) : ARRAY_SIZE(sk_opts_v6);
for (j = 0; j < n_opts; j++) {
val = IP_OPT_VAL;
if (setsockopt(sk_confs[i].sk, opts[j].level, opts[j].opt, &val, sizeof(int)) == -1) {
pr_perror("setsockopt(%d, %d) failed", opts[j].level, opts[j].opt);
goto close;
}
}
}
test_daemon();
test_waitsig();
for (i = 0; i < ARRAY_SIZE(sk_confs); i++) {
opts = sk_confs[i].domain == AF_INET ? sk_opts_v4 : sk_opts_v6;
n_opts = sk_confs[i].domain == AF_INET ? ARRAY_SIZE(sk_opts_v4) : ARRAY_SIZE(sk_opts_v6);
for (j = 0; j < n_opts; j++) {
len = sizeof(int);
if (getsockopt(sk_confs[i].sk, opts[j].level, opts[j].opt, &val, &len) == -1) {
pr_perror("getsockopt(%d, %d) failed", opts[j].level, opts[j].opt);
goto close;
}
if (val != IP_OPT_VAL) {
fail("Unexpected value socket(%d,%d,%d) opts(%d,%d)", sk_confs[i].domain,
sk_confs[i].type, sk_confs[i].protocol, opts[j].level, opts[j].opt);
goto close;
}
}
}
pass();
exit_code = 0;
close:
for (i = 0; i < ARRAY_SIZE(sk_confs); i++)
close(sk_confs[i].sk);
return exit_code;
}
| 2,587 | 22.315315 | 91 |
c
|
criu
|
criu-master/test/zdtm/static/socket-linger.c
|
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "zdtmtst.h"
const char *test_doc = "Check SO_LINGER socket option";
const char *test_author = "Radostin Stoyanov <[email protected]>";
int main(int argc, char **argv)
{
int sk;
struct linger dump = { true, 30 }, restore = { 0, 0 };
socklen_t optlen = sizeof(restore);
test_init(argc, argv);
sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sk < 0) {
pr_perror("Can't create socket");
return 1;
}
if (setsockopt(sk, SOL_SOCKET, SO_LINGER, &dump, sizeof(dump)) < 0) {
pr_perror("setsockopt SO_LINGER");
return 1;
}
test_daemon();
test_waitsig();
if (getsockopt(sk, SOL_SOCKET, SO_LINGER, &restore, &optlen) < 0) {
pr_perror("getsockopt SO_LINGER");
return 1;
}
if (restore.l_onoff != dump.l_onoff) {
fail("linger.l_onoff has incorrect value (%d != %d)", restore.l_onoff, dump.l_onoff);
return 1;
}
if (restore.l_linger != dump.l_linger) {
fail("linger.l_linger has incorrect value (%d != %d)", restore.l_linger, dump.l_linger);
return 1;
}
pass();
return 0;
}
| 1,109 | 21.2 | 90 |
c
|
criu
|
criu-master/test/zdtm/static/socket-raw.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <linux/icmp.h>
#include <linux/icmpv6.h>
#include <limits.h>
#include <fcntl.h>
#include "zdtmtst.h"
/*
* Some code snippets are taken from
* http://www.binarytides.com/raw-udp-sockets-c-linux/
*/
const char *test_doc = "Test RAW sockets (IPv4,6)\n";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
#ifndef SO_IP_SET
#define SO_IP_SET 83
#endif
#ifndef IP_SET_OP_VERSION
#define IP_SET_OP_VERSION 0x00000100 /* Ask kernel version */
#endif
#define pr_debug(format, arg...) test_msg("DBG: %s:%d: " format, __FILE__, __LINE__, ##arg)
struct ip_set_req_version {
unsigned int op;
unsigned int version;
};
struct pseudo_header {
uint32_t source_address;
uint32_t dest_address;
uint8_t placeholder;
uint8_t protocol;
uint16_t udp_length;
};
static int stop_icmp(int sk_icmp, int sk_icmpv6)
{
struct icmp6_filter filter6 = {};
struct icmp_filter filter = {};
socklen_t aux;
int ret = 0;
aux = sizeof(filter);
ret = getsockopt(sk_icmp, SOL_RAW, ICMP_FILTER, &filter, &aux);
if (ret < 0) {
pr_perror("stop_icmp: Can't fetch icmp filter");
return ret;
}
if (filter.data != (1 << ICMP_TIMESTAMP)) {
pr_err("data mismatch on icmp filter %d != %d\n", filter.data, (1 << ICMP_TIMESTAMP));
return -1;
}
aux = sizeof(filter6);
ret = getsockopt(sk_icmpv6, SOL_ICMPV6, ICMPV6_FILTER, &filter6, &aux);
if (ret < 0) {
pr_perror("stop_icmp: Can't fetch icmpv6 filter");
return ret;
}
if (filter6.data[0] != (1 << ICMP_TIMESTAMP)) {
pr_err("data mismatch on icmp filter %d != %d\n", filter6.data[0], (1 << ICMP_TIMESTAMP));
return -1;
}
return ret;
}
static int start_icmp(int sk_icmp, int sk_icmpv6, const char *a4, const char *a6, int port)
{
struct sockaddr_in addr_client;
struct icmp6_filter filter6 = {};
struct icmp_filter filter = {};
int ret = 0;
memset(&addr_client, 0, sizeof(addr_client));
addr_client.sin_family = AF_INET;
addr_client.sin_port = htons(port);
addr_client.sin_addr.s_addr = inet_addr(a4);
ret = bind(sk_icmp, (struct sockaddr *)&addr_client, sizeof(addr_client));
if (ret < 0) {
pr_perror("start_icmp: Can't bind RAW client socket");
return ret;
}
pr_debug("start_icmp: Bound sk_icmp\n");
filter.data = (1 << ICMP_TIMESTAMP);
ret = setsockopt(sk_icmp, SOL_RAW, ICMP_FILTER, &filter, sizeof(filter));
if (ret < 0) {
pr_perror("start_icmp: Can't setup icmp filter");
return ret;
}
filter6.data[0] = (1 << ICMP_TIMESTAMP);
ret = setsockopt(sk_icmpv6, SOL_ICMPV6, ICMPV6_FILTER, &filter6, sizeof(filter6));
if (ret < 0) {
pr_perror("start_icmp: Can't setup icmpv6 filter");
return ret;
}
return ret;
}
static unsigned short csum(unsigned short *ptr, int nbytes)
{
unsigned short oddbyte;
register short answer;
register long sum;
sum = 0;
while (nbytes > 1) {
sum += *ptr++;
nbytes -= 2;
}
if (nbytes == 1) {
oddbyte = 0;
*((unsigned char *)&oddbyte) = *(unsigned char *)ptr;
sum += oddbyte;
}
sum = (sum >> 16) + (sum & 0xffff);
sum = sum + (sum >> 16);
answer = (short)~sum;
return answer;
}
/*
* Just create IPv6/IPv6 sockets with any protos
* to make sure criu won't BUG on unknown proto.
*/
static void raw_socks_storm(void)
{
int sk4[IPPROTO_MAX];
int sk6[IPPROTO_MAX];
size_t i;
for (i = 1; i < ARRAY_SIZE(sk4); i++) {
sk4[i] = socket(PF_INET, SOCK_RAW | SOCK_NONBLOCK, i);
if (sk4[i] >= 0)
test_msg("Created IPv4 proto %zd: %d\n", i, sk4[i]);
}
for (i = 1; i < ARRAY_SIZE(sk6); i++) {
sk6[i] = socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, i);
if (sk6[i] >= 0)
test_msg("Created IPv6 proto %zd: %d\n", i, sk6[i]);
}
}
int main(int argc, char *argv[])
{
const char string_data[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char string_client_ip[] = "127.0.0.12";
const char string_serv_ip[] = "127.0.0.10";
const char string_client_icmp_ip[] = "127.0.0.14";
const char string_client_icmpv6_ip[] = "::14";
char datagram[512], *data, *pseudogram;
char receiver[512];
struct ip_set_req_version req_version;
socklen_t size = sizeof(req_version);
int sk_udp, sk_udp_serv;
int sk_raw, sk6_raw;
int sk_icmp, sk_icmpv6;
struct udphdr *udph = (struct udphdr *)(datagram + sizeof(struct ip));
struct iphdr *iph = (struct iphdr *)datagram;
struct sockaddr_in addr_serv, addr_client;
struct pseudo_header psh;
int port_client = 8080;
int port_serv = 8081;
int psize, one = 1;
const int *val = &one;
socklen_t len = sizeof(struct sockaddr_in);
int ret, status;
pid_t pid;
task_waiter_t waiter;
test_init(argc, argv);
task_waiter_init(&waiter);
sk_raw = socket(PF_INET, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_RAW);
if (sk_raw < 0) {
pr_perror("Can't create IPv4 raw socket");
exit(1);
}
pr_debug("sk_raw %d\n", sk_raw);
/* Simply to make sure it can be recreated on restore */
sk6_raw = socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_RAW);
if (sk6_raw < 0) {
pr_perror("Can't create IPv6 raw socket");
exit(1);
}
pr_debug("sk6_raw %d\n", sk6_raw);
sk_udp = socket(PF_INET, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_UDP);
if (sk_udp < 0) {
pr_perror("Can't create IPv4 raw-udp socket");
exit(1);
}
pr_debug("sk_udp %d\n", sk_udp);
sk_icmp = socket(PF_INET, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_ICMP);
if (sk_icmp < 0) {
pr_perror("Can't create IPv4 raw icmp socket");
exit(1);
}
pr_debug("sk_icmp %d\n", sk_icmp);
sk_icmpv6 = socket(PF_INET6, SOCK_RAW | SOCK_NONBLOCK, IPPROTO_ICMPV6);
if (sk_icmpv6 < 0) {
pr_perror("Can't create IPv6 raw icmpv6 socket");
exit(1);
}
pr_debug("sk_icmpv6 %d\n", sk_icmpv6);
sk_udp_serv = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sk_udp_serv < 0) {
pr_perror("Can't create DGRAM server socket");
exit(1);
}
pr_debug("sk_udp_serv %d\n", sk_udp_serv);
memset(datagram, 0, sizeof(datagram));
memset(receiver, 0, sizeof(receiver));
memset(&addr_serv, 0, sizeof(addr_serv));
memset(&addr_client, 0, sizeof(addr_client));
addr_client.sin_family = AF_INET;
addr_client.sin_port = htons(port_client);
addr_client.sin_addr.s_addr = inet_addr(string_client_ip);
addr_serv.sin_family = AF_INET;
addr_serv.sin_port = htons(port_serv);
addr_serv.sin_addr.s_addr = inet_addr(string_serv_ip);
ret = bind(sk_udp_serv, (struct sockaddr *)&addr_serv, sizeof(addr_serv));
if (ret < 0) {
pr_perror("Can't bind DGRAM server socket");
return 1;
}
pr_debug("Bound sk_udp_serv\n");
ret = bind(sk_udp, (struct sockaddr *)&addr_client, sizeof(addr_client));
if (ret < 0) {
pr_perror("Can't bind DGRAM client socket");
return 1;
}
pr_debug("Bound sk_udp\n");
if (start_icmp(sk_icmp, sk_icmpv6, string_client_icmp_ip, string_client_icmpv6_ip, port_client))
return 1;
data = datagram + sizeof(struct iphdr) + sizeof(struct udphdr);
strcpy(data, string_data);
iph->ihl = 5;
iph->version = 4;
iph->tos = 0;
iph->tot_len = sizeof(struct iphdr) + sizeof(struct udphdr) + strlen(string_data);
iph->id = htonl(54321);
iph->frag_off = 0;
iph->ttl = 255;
iph->protocol = IPPROTO_UDP;
iph->check = 0;
iph->saddr = inet_addr(string_client_ip);
iph->daddr = addr_serv.sin_addr.s_addr;
iph->check = csum((unsigned short *)datagram, sizeof(struct iphdr));
udph->source = htons(port_client);
udph->dest = htons(port_serv);
udph->len = htons(8 + strlen(data));
udph->check = 0;
psh.source_address = inet_addr(string_client_ip);
psh.dest_address = addr_serv.sin_addr.s_addr;
psh.placeholder = 0;
psh.protocol = IPPROTO_UDP;
psh.udp_length = htons(sizeof(struct udphdr) + strlen(string_data));
psize = sizeof(psh) + sizeof(struct udphdr) + strlen(string_data);
pseudogram = malloc(psize);
if (!pseudogram) {
pr_err("No free memory\n");
exit(1);
}
memcpy(pseudogram, (char *)&psh, sizeof(psh));
memcpy(pseudogram + sizeof(psh), udph, sizeof(*udph) + strlen(string_data));
udph->check = csum((unsigned short *)pseudogram, psize);
free(pseudogram);
if (setsockopt(sk_udp, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0) {
pr_perror("Error setting IP_HDRINCL");
exit(1);
}
pid = test_fork();
if (pid == 0) {
task_waiter_wait4(&waiter, 2);
pr_debug("Gonna read data\n");
ret = recvfrom(sk_udp_serv, receiver, sizeof(receiver), 0, (struct sockaddr *)&addr_client, &len);
if (ret < 0) {
task_waiter_complete(&waiter, 2);
fail("Can't read data");
exit(1);
}
receiver[ret] = '\0';
pr_debug("Read %d bytes\n", ret);
task_waiter_complete(&waiter, 3);
if (strcmp(receiver, string_data)) {
pr_err("Data mismatch (got %s but expected %s)\n", receiver, string_data);
exit(1);
} else
pr_debug("Data match\n");
exit(0);
} else if (pid < 0) {
pr_err("Can't fork\n");
exit(1);
}
raw_socks_storm();
test_daemon();
test_waitsig();
if (sendto(sk_udp, datagram, iph->tot_len, 0, (struct sockaddr *)&addr_serv, sizeof(addr_serv)) < 0) {
kill(pid, SIGKILL);
fail("Can't send RAW data");
exit(1);
}
task_waiter_complete(&waiter, 2);
pr_debug("Sent %d bytes\n", (int)iph->tot_len);
task_waiter_wait4(&waiter, 3);
ret = wait(&status);
if (ret == -1 || !WIFEXITED(status) || WEXITSTATUS(status)) {
kill(pid, SIGKILL);
fail("Failed waiting server");
exit(1);
}
req_version.op = IP_SET_OP_VERSION;
ret = getsockopt(sk_raw, SOL_IP, SO_IP_SET, &req_version, &size);
if (ret) {
pr_perror("xt_set getsockopt");
if (errno != ENOPROTOOPT) {
fail("Can't fetch SO_IP_SET");
exit(1);
}
} else
test_msg("SO_IP_SET version = %d\n", req_version.version);
if (stop_icmp(sk_icmp, sk_icmpv6)) {
fail("Failed on ICMP sockets");
exit(1);
}
pass();
return 0;
}
| 9,868 | 23.610973 | 103 |
c
|
criu
|
criu-master/test/zdtm/static/socket-tcp-keepalive.c
|
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include "zdtmtst.h"
const char *test_doc = "test checkpoint/restore of SO_KEEPALIVE\n";
const char *test_author = "Radostin Stoyanov <[email protected]>\n";
int main(int argc, char **argv)
{
int sk;
int alive = 1;
int cnt = 5;
int idle = 10;
int intvl = 15;
int optval;
socklen_t optlen;
test_init(argc, argv);
sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sk < 0) {
pr_perror("Can't create socket");
return 1;
}
/* Set the option active */
if (setsockopt(sk, SOL_SOCKET, SO_KEEPALIVE, &alive, sizeof(alive)) < 0) {
pr_perror("setsockopt SO_KEEPALIVE");
return 1;
}
if (setsockopt(sk, SOL_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt)) < 0) {
pr_perror("setsockopt TCP_KEEPCNT");
return 1;
}
if (setsockopt(sk, SOL_TCP, TCP_KEEPIDLE, &idle, sizeof(idle)) < 0) {
pr_perror("setsockopt TCP_KEEPIDLE");
return 1;
}
optval = 5;
optlen = sizeof(optval);
if (setsockopt(sk, SOL_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl)) < 0) {
pr_perror("setsockopt TCP_KEEPINTVL");
return 1;
}
test_daemon();
test_waitsig();
if (getsockopt(sk, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen)) {
pr_perror("getsockopt SO_KEEPALIVE");
return 1;
}
if (optlen != sizeof(optval) || optval != alive) {
fail("SO_KEEPALIVE not set");
return 1;
}
if (getsockopt(sk, SOL_TCP, TCP_KEEPCNT, &optval, &optlen) < 0) {
pr_perror("getsockopt TCP_KEEPCNT");
return 1;
}
if (optval != cnt) {
fail("TCP_KEEPCNT has incorrect value (%d != %d)", cnt, optval);
return 1;
}
if (getsockopt(sk, SOL_TCP, TCP_KEEPIDLE, &optval, &optlen) < 0) {
pr_perror("getsockopt TCP_KEEPIDLE");
return 1;
}
if (optval != idle) {
fail("TCP_KEEPIDLE has incorrect value (%d != %d)", idle, optval);
return 1;
}
if (getsockopt(sk, SOL_TCP, TCP_KEEPINTVL, &optval, &optlen) < 0) {
pr_perror("getsockopt TCP_KEEPINTVL");
return 1;
}
if (optval != intvl) {
fail("TCP_KEEPINTVL has incorrect value (%d != %d)", intvl, optval);
return 1;
}
pass();
return 0;
}
| 2,095 | 20.608247 | 75 |
c
|
criu
|
criu-master/test/zdtm/static/socket-tcp-reseted.c
|
#include "zdtmtst.h"
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <stdlib.h>
#include <sys/wait.h>
#include <signal.h>
#ifdef ZDTM_IPV4V6
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET6
#elif defined(ZDTM_IPV6)
#define ZDTM_FAMILY AF_INET6
#define ZDTM_SRV_FAMILY AF_INET6
#else
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET
#endif
const char *test_doc = "Check, that a reset TCP connection can be restored\n";
const char *test_author = "Andrey Vagin <[email protected]";
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <sched.h>
#include <netinet/tcp.h>
static int port = 8880;
int main(int argc, char **argv)
{
int fd, fd_s, clt;
char cmd[4096], buf[10];
test_init(argc, argv);
signal(SIGPIPE, SIG_IGN);
if ((fd_s = tcp_init_server(ZDTM_SRV_FAMILY, &port)) < 0) {
pr_err("initializing server failed\n");
return 1;
}
clt = tcp_init_client(ZDTM_FAMILY, "localhost", port);
if (clt < 0) {
pr_perror("Unable to create a client socket");
return 1;
}
/*
* parent is server of TCP connection
*/
fd = tcp_accept_server(fd_s);
if (fd < 0) {
pr_err("can't accept client connection\n");
return 1;
}
if (write(clt, "asd", 3) != 3) {
pr_perror("Unable to write into a socket");
return 1;
}
snprintf(cmd, sizeof(cmd),
"iptables -w -t filter --protocol tcp -A INPUT --dport %d -j REJECT --reject-with tcp-reset", port);
if (system(cmd))
return 1;
if (write(fd, "asdas", 5) == -1) {
pr_perror("Unable to write into a socket");
return 1;
}
snprintf(cmd, sizeof(cmd),
"iptables -w -t filter --protocol tcp -D INPUT --dport %d -j REJECT --reject-with tcp-reset", port);
if (system(cmd))
return 1;
test_daemon();
test_waitsig();
if (read(fd, buf, sizeof(buf)) != 3) {
fail("Unable to read data from a socket");
return 1;
}
if (write(fd, buf, 3) != -1) {
fail("Can write into a closed socket");
return 1;
}
pass();
return 0;
}
| 2,094 | 20.377551 | 103 |
c
|
criu
|
criu-master/test/zdtm/static/socket-tcp-syn-sent.c
|
#include "zdtmtst.h"
#ifdef ZDTM_IPV4V6
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET6
#elif defined(ZDTM_IPV6)
#define ZDTM_FAMILY AF_INET6
#define ZDTM_SRV_FAMILY AF_INET6
#else
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET
#endif
const char *test_doc = "Check unconnected tcp sockets\n";
const char *test_author = "Andrey Vagin <[email protected]";
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
static int port = 8880;
union sockaddr_inet {
struct sockaddr addr;
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
int main(int argc, char **argv)
{
int fd, fd_s, sock, sk;
union sockaddr_inet addr;
char c, cmd[4096];
test_init(argc, argv);
sk = socket(ZDTM_FAMILY, SOCK_STREAM, 0);
if (sk < 0) {
pr_perror("socket");
return 1;
}
if ((fd_s = tcp_init_server(ZDTM_SRV_FAMILY, &port)) < 0) {
pr_err("initializing server failed\n");
return 1;
}
if ((sock = socket(ZDTM_FAMILY, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) < 0) {
pr_perror("can't create socket");
return -1;
}
/* Construct the server address structure */
memset(&addr, 0, sizeof(addr));
if (ZDTM_FAMILY == AF_INET) {
addr.v4.sin_family = AF_INET;
inet_pton(AF_INET, "localhost", &addr.v4.sin_addr);
} else {
addr.v6.sin6_family = AF_INET6;
inet_pton(AF_INET6, "localhost", &addr.v6.sin6_addr);
}
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
pr_perror("can't connect to server");
return -1;
}
snprintf(cmd, sizeof(cmd), "iptables -w -t filter --protocol tcp -A INPUT --dport %d -j DROP", port);
if (system(cmd))
return -1;
/* Construct the server address structure */
memset(&addr, 0, sizeof(addr));
if (ZDTM_FAMILY == AF_INET) {
addr.v4.sin_family = AF_INET;
addr.v4.sin_port = htons(port);
inet_pton(AF_INET, "localhost", &addr.v4.sin_addr);
} else {
addr.v6.sin6_family = AF_INET6;
addr.v6.sin6_port = htons(port);
inet_pton(AF_INET6, "localhost", &addr.v6.sin6_addr);
}
errno = 0;
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0 || errno != EINPROGRESS) {
pr_perror("can't connect to server");
return -1;
}
test_daemon();
test_waitsig();
snprintf(cmd, sizeof(cmd), "iptables -w -t filter --protocol tcp -D INPUT --dport %d -j DROP", port);
if (system(cmd))
return -1;
/*
* parent is server of TCP connection
*/
fd = tcp_accept_server(fd_s);
if (fd < 0) {
pr_err("can't accept client connection\n");
return 1;
}
close(fd_s);
fcntl(sock, F_SETFL, 0);
c = 5;
if (write(sock, &c, 1) != 1) {
fail("Unable to send data");
return 1;
}
c = 0;
if (read(fd, &c, 1) != 1 || c != 5) {
fail("Unable to recv data");
return 1;
}
c = 6;
if (write(fd, &c, 1) != 1) {
fail("Unable to send data");
return 1;
}
c = 0;
if (read(sock, &c, 1) != 1 || c != 6) {
fail("Unable to recv data");
return 1;
}
pass();
return 0;
}
| 3,032 | 20.359155 | 102 |
c
|
criu
|
criu-master/test/zdtm/static/socket-tcp-unconn.c
|
#include "zdtmtst.h"
#ifdef ZDTM_IPV4V6
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET6
#elif defined(ZDTM_IPV6)
#define ZDTM_FAMILY AF_INET6
#define ZDTM_SRV_FAMILY AF_INET6
#else
#define ZDTM_FAMILY AF_INET
#define ZDTM_SRV_FAMILY AF_INET
#endif
const char *test_doc = "Check unconnected tcp sockets\n";
const char *test_author = "Andrey Vagin <[email protected]";
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
static int port = 8880;
union sockaddr_inet {
struct sockaddr addr;
struct sockaddr_in v4;
struct sockaddr_in6 v6;
};
int main(int argc, char **argv)
{
int fd, fd_s, sock, sk;
union sockaddr_inet addr, src_addr;
socklen_t aux;
test_init(argc, argv);
sk = socket(ZDTM_FAMILY, SOCK_STREAM, 0);
if (sk < 0) {
pr_perror("socket");
return 1;
}
if ((fd_s = tcp_init_server(ZDTM_SRV_FAMILY, &port)) < 0) {
pr_err("initializing server failed\n");
return 1;
}
if ((sock = socket(ZDTM_FAMILY, SOCK_STREAM, IPPROTO_TCP)) < 0) {
pr_perror("can't create socket");
return -1;
}
/* Construct the server address structure */
memset(&addr, 0, sizeof(addr));
if (ZDTM_FAMILY == AF_INET) {
addr.v4.sin_family = AF_INET;
inet_pton(AF_INET, "localhost", &addr.v4.sin_addr);
} else {
addr.v6.sin6_family = AF_INET6;
inet_pton(AF_INET6, "localhost", &addr.v6.sin6_addr);
}
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
pr_perror("can't connect to server");
return -1;
}
aux = sizeof(src_addr);
memset(&src_addr, 0, sizeof(src_addr));
if (getsockname(sock, &src_addr.addr, &aux)) {
pr_perror("getsockname");
return 1;
}
test_daemon();
test_waitsig();
memset(&addr, 0, sizeof(addr));
if (getsockname(sock, &addr.addr, &aux)) {
pr_perror("getsockname");
return 1;
}
if (memcmp(&addr, &src_addr, aux)) {
pr_err("A source address mismatch\n");
return 1;
}
/* Construct the server address structure */
memset(&addr, 0, sizeof(addr));
if (ZDTM_FAMILY == AF_INET) {
addr.v4.sin_family = AF_INET;
addr.v4.sin_port = htons(port);
inet_pton(AF_INET, "localhost", &addr.v4.sin_addr);
} else {
addr.v6.sin6_family = AF_INET6;
addr.v6.sin6_port = htons(port);
inet_pton(AF_INET6, "localhost", &addr.v6.sin6_addr);
}
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
pr_perror("can't connect to server");
return -1;
}
/*
* parent is server of TCP connection
*/
fd = tcp_accept_server(fd_s);
if (fd < 0) {
pr_err("can't accept client connection\n");
return 1;
}
close(fd_s);
pass();
return 0;
}
| 2,678 | 21.140496 | 66 |
c
|
criu
|
criu-master/test/zdtm/static/socket_queues.c
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <limits.h>
#include <fcntl.h>
#include "zdtmtst.h"
/* FIXME Need gram sockets tests */
const char *test_doc = "Test unix sockets queues (2 messages in queue)\n";
const char *test_author = "Stanislav Kinsbursky <[email protected]>\n";
#define SK_DATA_S1 "packet stream left"
#define SK_DATA_S2 "packet stream right"
#define SK_DATA_D1 "packet dgram left"
#define SK_DATA_D2 "packet dgram right"
#ifdef ZDTM_UNIX_SEQPACKET
#define SOCK_TYPE SOCK_SEQPACKET
#else
#define SOCK_TYPE SOCK_STREAM
#endif
int main(int argc, char *argv[])
{
int ssk_pair_d[2];
int ssk_pair_s[2];
char buf_left[64], buf_right[64];
test_init(argc, argv);
if (socketpair(AF_UNIX, SOCK_TYPE, 0, ssk_pair_s) == -1) {
fail("socketpair");
exit(1);
}
write(ssk_pair_s[0], SK_DATA_S1, sizeof(SK_DATA_S1));
write(ssk_pair_s[0], SK_DATA_S2, sizeof(SK_DATA_S2));
write(ssk_pair_s[1], SK_DATA_S2, sizeof(SK_DATA_S2));
write(ssk_pair_s[1], SK_DATA_S1, sizeof(SK_DATA_S1));
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, ssk_pair_d) == -1) {
fail("socketpair");
exit(1);
}
write(ssk_pair_d[0], SK_DATA_D1, sizeof(SK_DATA_D1));
write(ssk_pair_d[0], SK_DATA_D2, sizeof(SK_DATA_D2));
write(ssk_pair_d[1], SK_DATA_D2, sizeof(SK_DATA_D2));
write(ssk_pair_d[1], SK_DATA_D1, sizeof(SK_DATA_D1));
test_daemon();
test_waitsig();
read(ssk_pair_s[1], buf_left, strlen(SK_DATA_S1) + 1);
if (strcmp(buf_left, SK_DATA_S1)) {
fail("SK_DATA_S2: '%s", SK_DATA_S1);
exit(1);
}
read(ssk_pair_s[1], buf_right, strlen(SK_DATA_S2) + 1);
if (strcmp(buf_right, SK_DATA_S2)) {
fail("data corrupted");
exit(1);
}
test_msg("stream1 : '%s' '%s'\n", buf_left, buf_right);
read(ssk_pair_s[0], buf_left, strlen(SK_DATA_S2) + 1);
if (strcmp(buf_left, SK_DATA_S2)) {
fail("data corrupted");
exit(1);
}
read(ssk_pair_s[0], buf_right, strlen(SK_DATA_S1) + 1);
if (strcmp(buf_right, SK_DATA_S1)) {
fail("data corrupted");
exit(1);
}
test_msg("stream2 : '%s' '%s'\n", buf_left, buf_right);
read(ssk_pair_d[1], buf_left, strlen(SK_DATA_D1) + 1);
if (strcmp(buf_left, SK_DATA_D1)) {
fail("data corrupted");
exit(1);
}
read(ssk_pair_d[1], buf_right, strlen(SK_DATA_D2) + 1);
if (strcmp(buf_right, SK_DATA_D2)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram1 : '%s' '%s'\n", buf_left, buf_right);
read(ssk_pair_d[0], buf_left, strlen(SK_DATA_D2) + 1);
if (strcmp(buf_left, SK_DATA_D2)) {
fail("data corrupted");
exit(1);
}
read(ssk_pair_d[0], buf_right, strlen(SK_DATA_D1) + 1);
if (strcmp(buf_right, SK_DATA_D1)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram2 : '%s' '%s'\n", buf_left, buf_right);
pass();
return 0;
}
| 2,917 | 24.373913 | 79 |
c
|
criu
|
criu-master/test/zdtm/static/socket_snd_addr.c
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "zdtmtst.h"
const char *test_doc = "Check that sender addresses are restored";
const char *test_author = "Andrew Vagin <[email protected]";
#define SK_SRV "\0socket_snd_srv"
#define SK_NAME "\0A-socket_snd_clnt"
char sk_names[2][128] = {
SK_NAME,
SK_NAME,
};
#define MSG "hello"
int main(int argc, char **argv)
{
struct sockaddr_un addr;
unsigned int addrlen;
int srv, clnt = -1, ret, i;
char buf[1024];
struct iovec iov = {
.iov_base = &buf,
.iov_len = sizeof(buf),
};
struct msghdr hdr = {
.msg_name = &addr,
.msg_namelen = sizeof(addr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
test_init(argc, argv);
srv = socket(PF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, SK_SRV, sizeof(SK_SRV));
addrlen = sizeof(addr.sun_family) + sizeof(SK_SRV);
if (bind(srv, (struct sockaddr *)&addr, addrlen)) {
fail("bind");
exit(1);
}
for (i = 0; i < 2; i++) {
close(clnt);
clnt = socket(PF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0);
sk_names[i][1] += i;
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path, sk_names[i], sizeof(SK_NAME));
addrlen = sizeof(addr.sun_family) + sizeof(SK_NAME);
if (bind(clnt, (struct sockaddr *)&addr, addrlen)) {
fail("bind");
exit(1);
}
memcpy(addr.sun_path, SK_SRV, sizeof(SK_SRV));
addrlen = sizeof(addr.sun_family) + sizeof(SK_SRV);
if (connect(clnt, (struct sockaddr *)&addr, addrlen)) {
fail("connect");
exit(1);
}
if (send(clnt, MSG, sizeof(MSG), 0) != sizeof(MSG)) {
pr_perror("write");
return 1;
}
}
test_daemon();
test_waitsig();
for (i = 0; i < 2; i++) {
memset(addr.sun_path, 0, sizeof(addr.sun_path));
ret = recvmsg(srv, &hdr, MSG_DONTWAIT);
buf[ret > 0 ? ret : 0] = 0;
if (ret != sizeof(MSG)) {
fail("%d: %s", ret, buf);
return 1;
}
if (hdr.msg_namelen > sizeof(addr.sun_family) + 1)
pr_perror("%d, %s", hdr.msg_namelen, addr.sun_path + 1);
if (memcmp(addr.sun_path, sk_names[i], sizeof(SK_NAME))) {
fail("A sender address is mismatch");
return 1;
}
}
pass();
return 0;
}
| 2,201 | 20.80198 | 66 |
c
|
criu
|
criu-master/test/zdtm/static/socket_udp_shutdown.c
|
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <sys/wait.h>
#include "zdtmtst.h"
const char *test_doc = "static test for UDP shutdown'ed socket";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
static int port = 8881;
#define MSG1 "msg1"
int main(int argc, char **argv)
{
socklen_t len = sizeof(struct sockaddr_in);
struct sockaddr_in addr1, addr2, addr;
int ret, sk1, sk2;
char buf[512];
test_init(argc, argv);
sk1 = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
sk2 = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sk1 < 0 || sk2 < 0) {
pr_perror("Can't create socket");
exit(1);
return 1;
}
memset(&addr1, 0, sizeof(addr1));
memset(&addr2, 0, sizeof(addr1));
addr1.sin_family = AF_INET;
addr1.sin_addr.s_addr = inet_addr("127.0.0.10");
addr1.sin_port = htons(port);
addr2.sin_family = AF_INET;
addr2.sin_addr.s_addr = inet_addr("127.0.0.10");
addr2.sin_port = htons(port + 1);
if (bind(sk1, (struct sockaddr *)&addr1, len) < 0 || bind(sk2, (struct sockaddr *)&addr2, len) < 0) {
pr_perror("Can't bind socket");
return 1;
}
if (connect(sk1, (struct sockaddr *)&addr2, len) || connect(sk2, (struct sockaddr *)&addr1, len)) {
pr_perror("Can't connect");
return 1;
}
if (shutdown(sk1, SHUT_WR) || shutdown(sk2, SHUT_RD)) {
pr_perror("Can't shutdown");
return 1;
}
ret = sendto(sk2, MSG1, sizeof(MSG1), 0, (struct sockaddr *)&addr1, len);
if (ret < 0) {
pr_perror("Can't send");
return 1;
}
ret = recvfrom(sk1, buf, sizeof(buf), 0, (struct sockaddr *)&addr, &len);
if (ret <= 0) {
pr_perror("Can't receive data");
return 1;
}
if (len != sizeof(struct sockaddr_in) || memcmp(&addr2, &addr, len)) {
pr_err("Data received from wrong peer\n");
return 1;
}
if (ret != sizeof(MSG1) || memcmp(buf, MSG1, ret)) {
pr_err("Wrong message received\n");
return 1;
}
test_daemon();
test_waitsig();
ret = sendto(sk2, MSG1, sizeof(MSG1), 0, (struct sockaddr *)&addr1, len);
if (ret < 0) {
pr_perror("Can't send");
return 1;
}
ret = recvfrom(sk1, buf, sizeof(buf), 0, (struct sockaddr *)&addr, &len);
if (ret <= 0) {
pr_perror("Can't receive data");
return 1;
}
if (len != sizeof(struct sockaddr_in) || memcmp(&addr2, &addr, len)) {
pr_err("Data received from wrong peer\n");
return 1;
}
if (ret != sizeof(MSG1) || memcmp(buf, MSG1, ret)) {
pr_err("Wrong message received\n");
return 1;
}
ret = sendto(sk1, MSG1, sizeof(MSG1), 0, (struct sockaddr *)&addr2, len);
if (ret >= 0) {
fail("Sent to write-shutdown'ed socket");
return 1;
}
pass();
return 0;
}
| 2,788 | 22.049587 | 102 |
c
|
criu
|
criu-master/test/zdtm/static/sockets01.c
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <limits.h>
#include <fcntl.h>
#include "zdtmtst.h"
const char *test_doc = "Test unix sockets shutdown";
const char *test_author = "Pavel Emelyanov <[email protected]>";
#define fin(msg) \
do { \
pr_perror(msg); \
exit(1); \
} while (0)
#define ffin(msg) \
do { \
fail(msg); \
exit(1); \
} while (0)
#define TEST_MSG "test-message"
static char buf[sizeof(TEST_MSG)];
#ifdef ZDTM_UNIX_SEQPACKET
#define SOCK_TYPE SOCK_SEQPACKET
#else
#define SOCK_TYPE SOCK_STREAM
#endif
int main(int argc, char *argv[])
{
int spu[2], spb[2], dpu[2], dpb[2], dpd[2];
int ret;
test_init(argc, argv);
signal(SIGPIPE, SIG_IGN);
/* spu -- stream pair, unidirectional shutdown */
if (socketpair(PF_UNIX, SOCK_TYPE, 0, spu) < 0)
fin("no stream pair 1");
if (shutdown(spu[0], SHUT_RD) < 0)
fin("no stream shutdown 1");
/* spb -- stream pair, bidirectional shutdown */
if (socketpair(PF_UNIX, SOCK_TYPE, 0, spb) < 0)
fin("no stream pair 2");
if (shutdown(spb[0], SHUT_RDWR) < 0)
fin("no stream shutdown 2");
/* dpu -- dgram pair, one end read shutdown */
if (socketpair(PF_UNIX, SOCK_DGRAM, 0, dpu) < 0)
fin("no dgram pair 1");
if (shutdown(dpu[0], SHUT_RD) < 0)
fin("no dgram shutdown 1");
/* dpb -- dgram pair, one end read-write shutdown */
if (socketpair(PF_UNIX, SOCK_DGRAM, 0, dpb) < 0)
fin("no dgram pair 2");
if (shutdown(dpb[0], SHUT_RDWR) < 0)
fin("no dgram shutdown 2");
/* dpd -- dgram pair, one end write shutdown with data */
if (socketpair(PF_UNIX, SOCK_DGRAM, 0, dpd) < 0)
fin("no dgram pair 3");
if (write(dpd[0], TEST_MSG, sizeof(TEST_MSG)) < 0)
fin("no dgram write");
if (shutdown(dpd[0], SHUT_WR) < 0)
fin("no dgram shutdown 3");
test_daemon();
test_waitsig();
/*
* spu -- check that one direction is blocked and
* the other one is not
*/
ret = write(spu[0], TEST_MSG, sizeof(TEST_MSG));
if (ret < 0)
ffin("SU shutdown broken 1");
ret = read(spu[1], buf, sizeof(buf));
if (ret < 0)
ffin("SU shutdown broken 2");
ret = write(spu[1], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("SU shutdown broken 3");
/*
* spb -- check that both ends are off
*/
ret = write(spb[0], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("SB shutdown broken 1");
ret = write(spb[1], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("SB shutdown broken 2");
/*
* dpu -- check that one direction works, and
* the other does not
*/
ret = write(dpu[0], TEST_MSG, sizeof(TEST_MSG));
if (ret < 0)
ffin("DU shutdown broken 1");
ret = read(dpu[1], buf, sizeof(buf));
if (ret < 0)
ffin("DU shutdown broken 2");
ret = write(dpu[1], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("DU shutdown broken 3");
/*
* dpb -- check that both ends are read
*/
ret = write(dpb[0], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("DB shutdown broken 1");
ret = write(dpb[1], TEST_MSG, sizeof(TEST_MSG));
if (ret >= 0)
ffin("DB shutdown broken 2");
/*
* dpd -- check that data is in there, but can't
* feed more
*/
ret = read(dpd[1], buf, sizeof(buf));
if (ret < 0)
ffin("DD shutdown nodata");
ret = write(dpd[0], TEST_MSG, sizeof(buf));
if (ret >= 0)
ffin("DB shutdown broken");
pass();
return 0;
}
| 3,508 | 20.527607 | 66 |
c
|
criu
|
criu-master/test/zdtm/static/sockets_dgram.c
|
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <limits.h>
#include <fcntl.h>
#include "zdtmtst.h"
const char *test_doc = "Test unix dgram sockets\n";
const char *test_author = "Cyrill Gorcunov <[email protected]";
#define SK_DATA_BOUND "data-packet-bound"
#define SK_DATA_CONN "data-packet-conn"
#define SK_DATA_BOUND_CONN "data-packet-bound-conn"
char *filename;
TEST_OPTION(filename, string, "socket file name", 1);
int main(int argc, char *argv[])
{
struct sockaddr_un name_bound;
struct sockaddr_un name_conn;
struct sockaddr_un name_bound_conn;
int sk_dgram_bound_client;
int sk_dgram_bound_server;
int sk_dgram_conn_client;
int sk_dgram_conn_client2;
int sk_dgram_conn_server;
int sk_dgram_bound_conn;
char path[PATH_MAX];
char buf[64];
/*
* The original code makes dir to be current working
* directory. But it may be too long in google environment
* for path to be fit into struct sockaddr_un.
* One alternate way to resolve it is to use relative path
* for sockaddr_un, but criu has not supported relative
* bind path yet.
* We change it to "/tmp" to ensure its short length.
*/
char *dirname = "/tmp";
int ret;
test_init(argc, argv);
snprintf(path, sizeof(path), "%s/%s", dirname, filename);
unlink(path);
sk_dgram_bound_client = socket(AF_UNIX, SOCK_DGRAM, 0);
sk_dgram_bound_server = socket(AF_UNIX, SOCK_DGRAM, 0);
sk_dgram_conn_client = socket(AF_UNIX, SOCK_DGRAM, 0);
sk_dgram_conn_client2 = socket(AF_UNIX, SOCK_DGRAM, 0);
sk_dgram_conn_server = socket(AF_UNIX, SOCK_DGRAM, 0);
sk_dgram_bound_conn = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sk_dgram_conn_server < 0 || sk_dgram_bound_server < 0 || sk_dgram_conn_client < 0 ||
sk_dgram_conn_client2 < 0 || sk_dgram_conn_server < 0 || sk_dgram_bound_conn < 0) {
fail("socket");
exit(1);
}
snprintf(path, sizeof(path), "%s/%s.bound", dirname, filename);
unlink(path);
if (strlen(path) >= sizeof(name_bound.sun_path)) {
fail("too long path");
exit(1);
}
name_bound.sun_family = AF_UNIX;
strncpy(name_bound.sun_path, path, sizeof(name_bound.sun_path));
snprintf(path, sizeof(path), "%s/%s.conn", dirname, filename);
unlink(path);
if (strlen(path) >= sizeof(name_conn.sun_path)) {
fail("too long path");
exit(1);
}
name_conn.sun_family = AF_UNIX;
strncpy(name_conn.sun_path, path, sizeof(name_conn.sun_path));
snprintf(path, sizeof(path), "%s/%s.bound-conn", dirname, filename);
unlink(path);
if (strlen(path) >= sizeof(name_bound_conn.sun_path)) {
fail("too long path");
exit(1);
}
name_bound_conn.sun_family = AF_UNIX;
strncpy(name_bound_conn.sun_path, path, sizeof(name_bound_conn.sun_path));
ret = bind(sk_dgram_bound_server, (struct sockaddr *)&name_bound, sizeof(name_bound));
if (ret) {
fail("bind");
exit(1);
}
ret = bind(sk_dgram_conn_server, (struct sockaddr *)&name_conn, sizeof(name_conn));
if (ret) {
fail("bind");
exit(1);
}
ret = connect(sk_dgram_conn_client, (struct sockaddr *)&name_conn, sizeof(name_conn));
if (ret) {
fail("connect");
exit(1);
}
ret = connect(sk_dgram_conn_client2, (struct sockaddr *)&name_conn, sizeof(name_conn));
if (ret) {
fail("connect");
exit(1);
}
ret = bind(sk_dgram_bound_conn, (struct sockaddr *)&name_bound_conn, sizeof(name_bound_conn));
if (ret) {
fail("bind");
exit(1);
}
/* Note, it's already bound, so make it more idiotic! */
ret = connect(sk_dgram_bound_conn, (struct sockaddr *)&name_bound_conn, sizeof(name_bound_conn));
if (ret) {
fail("connect");
exit(1);
}
memset(buf, 0, sizeof(buf));
sendto(sk_dgram_bound_client, SK_DATA_BOUND, sizeof(SK_DATA_BOUND), 0, (struct sockaddr *)&name_bound,
sizeof(name_bound));
read(sk_dgram_bound_server, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_BOUND)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-bound : '%s'\n", buf);
memset(buf, 0, sizeof(buf));
write(sk_dgram_conn_client, SK_DATA_CONN, sizeof(SK_DATA_CONN));
read(sk_dgram_conn_server, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_CONN)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-conn : '%s'\n", buf);
memset(buf, 0, sizeof(buf));
write(sk_dgram_bound_conn, SK_DATA_BOUND_CONN, sizeof(SK_DATA_BOUND_CONN));
read(sk_dgram_bound_conn, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_BOUND_CONN)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-bound-conn : '%s'\n", buf);
test_daemon();
test_waitsig();
memset(buf, 0, sizeof(buf));
sendto(sk_dgram_bound_client, SK_DATA_BOUND, sizeof(SK_DATA_BOUND), 0, (struct sockaddr *)&name_bound,
sizeof(name_bound));
read(sk_dgram_bound_server, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_BOUND)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-bound : '%s'\n", buf);
memset(buf, 0, sizeof(buf));
write(sk_dgram_conn_client, SK_DATA_CONN, sizeof(SK_DATA_CONN));
read(sk_dgram_conn_server, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_CONN)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-conn : '%s'\n", buf);
memset(buf, 0, sizeof(buf));
write(sk_dgram_bound_conn, SK_DATA_BOUND_CONN, sizeof(SK_DATA_BOUND_CONN));
read(sk_dgram_bound_conn, &buf, sizeof(buf));
if (strcmp(buf, SK_DATA_BOUND_CONN)) {
fail("data corrupted");
exit(1);
}
test_msg("dgram-bound-conn : '%s'\n", buf);
pass();
/*
* Do cleanup work
*/
unlink(name_bound.sun_path);
unlink(name_conn.sun_path);
unlink(name_bound_conn.sun_path);
return 0;
}
| 5,637 | 26.236715 | 103 |
c
|
criu
|
criu-master/test/zdtm/static/thread_different_uid_gid.c
|
/*
* Check that we can dump a process with threads having mismatching UID/GID
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <syscall.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <pthread.h>
#include "zdtmtst.h"
#define exit_group(code) syscall(__NR_exit_group, code)
const char *test_doc = "Acquire UID/GID setting caps, create thread and drop thread to non-root by changing UID/GID\n";
const char *test_author = "Vitaly Ostrosablin <[email protected]>";
unsigned int gid;
unsigned int uid;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
task_waiter_t t;
int done = 0;
void *chg_uid_gid(void *arg)
{
cap_t newcaps;
cap_t mycaps;
int ret;
test_msg("Aux thread runs as UID: %d; GID: %d\n", getuid(), getgid());
newcaps = cap_from_text("cap_setgid,cap_setuid=+eip");
if (!newcaps) {
pr_perror("Failed to get capability struct");
exit(1);
}
ret = cap_set_proc(newcaps);
if (ret) {
pr_perror("Failed to set capabilities for the process");
exit(1);
}
mycaps = cap_get_proc();
if (!mycaps) {
pr_perror("Failed to get child thread capabilities");
exit_group(2);
}
test_msg("Child capabilities: %s\n", cap_to_text(mycaps, NULL));
test_msg("Changing UID/GID in child thread to %d:%d\n", uid, gid);
ret = syscall(SYS_setresgid, gid, gid, gid);
if (ret >= 0) {
syscall(SYS_setresuid, uid, uid, uid);
} else if (ret < 0) {
pr_perror("Failed to change UID/GID");
exit_group(2);
}
gid = getgid();
uid = getuid();
test_msg("Now aux thread runs as UID: %d; GID: %d\n", uid, gid);
test_msg("Child thread is waiting for main thread's signal\n");
task_waiter_complete(&t, 1);
pthread_mutex_lock(&mutex);
while (!done) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
test_msg("Child thread returns\n");
return NULL;
}
int main(int argc, char **argv)
{
pthread_t diff_cred_thread;
cap_t newcaps;
int maingroup;
int mainuser;
int ret;
test_init(argc, argv);
task_waiter_init(&t);
if (getuid() != 0) {
fail("Test is expected to be run with root privileges");
exit(1);
}
test_msg("Acquiring CAP_SETGID and CAP_SETUID...\n");
newcaps = cap_from_text("cap_setgid,cap_setuid=+eip");
if (!newcaps) {
pr_perror("Failed to get capability struct");
exit(1);
}
ret = cap_set_proc(newcaps);
if (ret) {
pr_perror("Failed to set capabilities for the process");
exit(1);
}
ret = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
if (ret) {
pr_perror("Unable to set KEEPCAPS");
exit(1);
}
test_msg("Main thread runs as UID: %d; GID: %d\n", getuid(), getgid());
gid = 99;
uid = 99;
maingroup = 8;
mainuser = 12;
test_msg("Creating thread with different UID/GID\n");
ret = pthread_create(&diff_cred_thread, NULL, &chg_uid_gid, NULL);
task_waiter_wait4(&t, 1);
test_msg("Relinquishing root privileges\n");
ret = syscall(SYS_setresgid, maingroup, maingroup, maingroup);
if (ret >= 0) {
ret = syscall(SYS_setresuid, mainuser, mainuser, mainuser);
} else if (ret < 0) {
pr_perror("Failed to drop privileges");
exit(1);
}
test_msg("Now main thread runs as UID: %d; GID: %d\n", getuid(), getgid());
if (gid == getgid() || uid == getuid()) {
pr_perror("Thread credentials match");
exit(1);
}
test_msg("Main thread is waiting for signal\n");
test_daemon();
test_waitsig();
if (gid == getgid() || uid == getuid()) {
pr_perror("Thread credentials match after restore");
exit(1);
}
pthread_mutex_lock(&mutex);
done = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(diff_cred_thread, NULL);
test_msg("Threads joined\n");
pass();
return 0;
}
| 3,723 | 21.846626 | 119 |
c
|
criu
|
criu-master/test/zdtm/static/timerfd.c
|
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <sys/timerfd.h>
#include "zdtmtst.h"
const char *test_doc = "Checks timerfd survives checkpoint/restore\n";
const char *test_author = "Cyrill Gorcunov <[email protected]>";
#define TIMERFD_VNSEC 50000
#define TIMERFD_ISEC 4
struct timerfd_status {
int clockid;
uint64_t ticks;
int settime_flags;
struct itimerspec v;
};
static void show_timerfd(char *prefix, struct timerfd_status *s)
{
test_msg("\t%s clockid %d ticks %llu settime_flags %d it_value(%llu, %llu) it_interval(%llu, %llu)\n", prefix,
s->clockid, (unsigned long long)s->ticks, s->settime_flags, (unsigned long long)s->v.it_value.tv_sec,
(unsigned long long)s->v.it_value.tv_nsec, (unsigned long long)s->v.it_interval.tv_sec,
(unsigned long long)s->v.it_interval.tv_nsec);
}
static int parse_self_fdinfo(int fd, struct timerfd_status *s)
{
char buf[256];
int ret = -1;
FILE *f;
sprintf(buf, "/proc/self/fdinfo/%d", fd);
f = fopen(buf, "r");
if (!f) {
pr_perror("Can't open %s to parse", buf);
return -1;
}
memset(s, 0, sizeof(*s));
/*
* clockid: 0
* ticks: 0
* settime flags: 01
* it_value: (0, 49406829)
* it_interval: (1, 0)
*/
while (fgets(buf, sizeof(buf), f)) {
if (strncmp(buf, "clockid:", 8))
continue;
if (sscanf(buf, "clockid: %d", &s->clockid) != 1)
goto parse_err;
if (!fgets(buf, sizeof(buf), f))
goto parse_err;
if (sscanf(buf, "ticks: %llu", (unsigned long long *)&s->ticks) != 1)
goto parse_err;
if (!fgets(buf, sizeof(buf), f))
goto parse_err;
if (sscanf(buf, "settime flags: 0%o", &s->settime_flags) != 1)
goto parse_err;
if (!fgets(buf, sizeof(buf), f))
goto parse_err;
if (sscanf(buf, "it_value: (%llu, %llu)", (unsigned long long *)&s->v.it_value.tv_sec,
(unsigned long long *)&s->v.it_value.tv_nsec) != 2)
goto parse_err;
if (!fgets(buf, sizeof(buf), f))
goto parse_err;
if (sscanf(buf, "it_interval: (%llu, %llu)", (unsigned long long *)&s->v.it_interval.tv_sec,
(unsigned long long *)&s->v.it_interval.tv_nsec) != 2)
goto parse_err;
ret = 0;
break;
}
if (ret)
goto parse_err;
err:
fclose(f);
return ret;
parse_err:
pr_perror("Format error");
goto err;
}
static int check_timerfd(int fd, struct timerfd_status *old)
{
struct timerfd_status new;
if (parse_self_fdinfo(fd, &new))
return -1;
show_timerfd("restored", &new);
if (old->clockid != new.clockid || old->settime_flags != new.settime_flags || old->ticks > new.ticks ||
old->v.it_value.tv_sec > new.v.it_value.tv_sec || old->v.it_interval.tv_sec != new.v.it_interval.tv_sec)
return -1;
return 0;
}
int main(int argc, char *argv[])
{
struct timerfd_status old = {
.clockid = CLOCK_MONOTONIC,
.ticks = 0,
.settime_flags = 0,
.v = {
.it_value = {
.tv_sec = 0,
.tv_nsec= TIMERFD_VNSEC,
},
.it_interval = {
.tv_sec = TIMERFD_ISEC,
.tv_nsec= 0,
},
},
};
int timerfd = 0, ret;
test_init(argc, argv);
timerfd = timerfd_create(old.clockid, 0);
if (timerfd < 0) {
pr_perror("timerfd_create failed");
return -1;
}
show_timerfd("setup", &old);
if (timerfd_settime(timerfd, old.settime_flags, &old.v, NULL)) {
pr_perror("timerfd_settime failed");
return -1;
}
sleep(1);
test_daemon();
test_waitsig();
ret = check_timerfd(timerfd, &old);
if (ret)
fail();
else
pass();
return ret;
}
| 3,442 | 20.929936 | 111 |
c
|
criu
|
criu-master/test/zdtm/static/unbindable.c
|
#include <fcntl.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include "zdtmtst.h"
const char *test_doc = "Check unbindable flag does not break mount restore";
const char *test_author = "Pavel Tikhomirov <[email protected]>";
char *dirname;
TEST_OPTION(dirname, string, "directory name", 1);
int main(int argc, char **argv)
{
char unbindable[PATH_MAX], bind_of_unbindable[PATH_MAX];
char auxiliary[PATH_MAX];
test_init(argc, argv);
mkdir(dirname, 0700);
snprintf(unbindable, sizeof(unbindable), "%s/unbindable", dirname);
if (mkdir(unbindable, 0700)) {
pr_perror("Unable to mkdir %s", unbindable);
return 1;
}
if (mount("unbindable", unbindable, "tmpfs", 0, NULL)) {
pr_perror("Unable to mount tmpfs to %s", unbindable);
return 1;
}
snprintf(auxiliary, sizeof(auxiliary), "%s/unbindable/auxiliary", dirname);
if (mkdir(auxiliary, 0700)) {
pr_perror("Unable to mkdir %s", auxiliary);
return 1;
}
snprintf(bind_of_unbindable, sizeof(bind_of_unbindable), "%s/bind_of_unbindable", dirname);
if (mkdir(bind_of_unbindable, 0700)) {
pr_perror("Unable to mkdir %s", bind_of_unbindable);
return 1;
}
if (mount(auxiliary, bind_of_unbindable, NULL, MS_BIND, NULL)) {
pr_perror("Unable to mount %s to %s", unbindable, bind_of_unbindable);
return 1;
}
if (mount(NULL, unbindable, NULL, MS_UNBINDABLE, NULL)) {
pr_perror("Unable to set %s unbindable", unbindable);
return 1;
}
test_daemon();
test_waitsig();
if (umount(bind_of_unbindable)) {
pr_perror("Unable to umount %s", bind_of_unbindable);
return 1;
}
if (umount(unbindable)) {
pr_perror("Unable to umount %s", unbindable);
return 1;
}
pass();
return 0;
}
| 1,726 | 23.671429 | 92 |
c
|
criu
|
criu-master/test/zdtm/static/unlink_multiple_largefiles.c
|
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <limits.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <linux/fiemap.h>
#include "zdtmtst.h"
#define FSIZE 0x3B600000ULL
#define NFILES 10
#define BUFSIZE (1 << 20)
const char *test_doc = "C/R of ten big (951MiB) unlinked files in root dir";
const char *test_author = "Vitaly Ostrosablin <[email protected]>";
void create_check_pattern(char *buf, size_t count, unsigned char seed)
{
int i;
for (i = 0; i < count; i++)
buf[i] = seed++;
}
struct fiemap *read_fiemap(int fd)
{
struct fiemap *fiemap, *tmp;
int extents_size;
test_msg("Obtaining fiemap for fd %d\n", fd);
fiemap = malloc(sizeof(struct fiemap));
if (fiemap == NULL) {
pr_perror("Cannot allocate fiemap");
return NULL;
}
memset(fiemap, 0, sizeof(struct fiemap));
fiemap->fm_length = FIEMAP_MAX_OFFSET;
fiemap->fm_start = 0;
fiemap->fm_flags = 0;
fiemap->fm_extent_count = 0;
if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0) {
pr_perror("FIEMAP ioctl failed");
free(fiemap);
return NULL;
}
extents_size = sizeof(struct fiemap_extent) * fiemap->fm_mapped_extents;
tmp = realloc(fiemap, sizeof(struct fiemap) + extents_size);
if (tmp == NULL) {
free(fiemap);
pr_perror("Cannot resize fiemap");
return NULL;
}
fiemap = tmp;
memset(fiemap->fm_extents, 0, extents_size);
fiemap->fm_extent_count = fiemap->fm_mapped_extents;
fiemap->fm_mapped_extents = 0;
if (ioctl(fd, FS_IOC_FIEMAP, fiemap) < 0) {
pr_perror("fiemap ioctl() failed");
free(fiemap);
return NULL;
}
test_msg("Debugkillme: %x\n", fiemap->fm_mapped_extents);
return fiemap;
}
void check_extent_map(struct fiemap *map)
{
int i;
unsigned long long datasize = 0;
unsigned long long holesize = 0;
test_msg("Verifying extent map...\n");
for (i = 0; i < map->fm_mapped_extents; i++) {
test_msg("Extent %d, start %llx, length %llx\n", i, (long long)map->fm_extents[i].fe_logical,
(long long)map->fm_extents[i].fe_length);
if (i == 0)
holesize = map->fm_extents[i].fe_logical;
datasize += map->fm_extents[i].fe_length;
}
if (holesize != FSIZE) {
pr_err("Unexpected hole size %llx != %llx\n", (long long)holesize, (unsigned long long)FSIZE);
exit(1);
}
if (datasize != BUFSIZE) {
pr_err("Unexpected data size %llx != %llx\n", (long long)datasize, (unsigned long long)BUFSIZE);
exit(1);
}
}
void compare_file_content(int fildes, int seed)
{
char ebuf[BUFSIZE];
char rbuf[BUFSIZE];
char linkpath[PATH_MAX];
int fd;
struct fiemap *fiemap;
ssprintf(linkpath, "/proc/self/fd/%d", fildes);
fd = open(linkpath, O_RDONLY | O_LARGEFILE);
if (fd < 0) {
pr_perror("Cannot open unlinked file %s", linkpath);
exit(1);
}
memset(ebuf, 0, BUFSIZE);
fiemap = read_fiemap(fd);
check_extent_map(fiemap);
free(fiemap);
lseek64(fd, FSIZE, SEEK_SET);
create_check_pattern(ebuf, BUFSIZE, seed);
if (read(fd, rbuf, BUFSIZE) != BUFSIZE) {
pr_perror("Cannot read %i bytes from file", BUFSIZE);
goto failed;
}
if (memcmp(&ebuf, &rbuf, BUFSIZE)) {
pr_err("Control Block: Data mismatch detected\n");
goto failed;
}
close(fd);
return;
failed:
close(fd);
exit(1);
}
void read_proc_fd_link(int fd, char *buf)
{
ssize_t res;
char linkpath[PATH_MAX];
ssprintf(linkpath, "/proc/%d/fd/%d", getpid(), fd);
res = readlink(linkpath, buf, PATH_MAX - 1);
buf[res] = 0;
if (res < 0) {
pr_perror("Cannot read fd symlink %s", linkpath);
exit(1);
}
}
int create_unlinked_file(int fileno)
{
int fd;
char buf[BUFSIZE];
char fnm[PATH_MAX];
ssprintf(fnm, "/unlinked%d", fileno);
fd = open(fnm, O_WRONLY | O_CREAT | O_TRUNC | O_LARGEFILE, 0644);
if (fd < 0) {
pr_perror("Cannot create file %s", fnm);
exit(1);
}
test_msg("Created file: %s, fd %d\n", fnm, fd);
if (lseek64(fd, FSIZE, SEEK_SET) < 0) {
pr_perror("Cannot seek to offset %llx", FSIZE);
goto failed;
}
test_msg("File positioning done, offset=%llx\n", FSIZE);
create_check_pattern(&buf[0], BUFSIZE, fileno);
if (write(fd, buf, BUFSIZE) != BUFSIZE) {
pr_perror("Cannot write %i bytes to file", BUFSIZE);
goto failed;
}
test_msg("%i bytes written to file\n", BUFSIZE);
if (unlink(fnm) < 0) {
pr_perror("Cannot unlink file %s", fnm);
goto failed;
}
test_msg("File %s is unlinked\n", fnm);
return fd;
failed:
unlink(fnm);
close(fd);
return -1;
}
int main(int argc, char **argv)
{
int fd[NFILES] = { 0 };
char links[NFILES][PATH_MAX];
char link[PATH_MAX];
int count = 0;
int tempfd;
test_init(argc, argv);
/* We need to create 10 unlinked files, each is around 1GB in size */
for (count = 0; count < NFILES; count++) {
test_msg("Creating unlinked file %d/%d\n", count + 1, NFILES);
tempfd = create_unlinked_file(count);
if (tempfd < 0) {
pr_err("Cannot create unlinked file %d/%d\n", count + 1, NFILES);
return 1;
}
memset(&links[count][0], 0, PATH_MAX);
read_proc_fd_link(tempfd, &links[count][0]);
fd[count] = tempfd;
}
test_msg("Created %d unlinked files\n", NFILES);
test_daemon();
test_msg("Test daemonized, PID %d\n", getpid());
test_waitsig();
test_msg("PID %d resumed, doing final checks...\n", getpid());
for (count = 0; count < NFILES; count++) {
test_msg("Processing fd #%d (%d)\n", count, fd[count]);
test_msg("Checking symlink consistency...\n");
memset(&link[0], 0, PATH_MAX);
read_proc_fd_link(fd[count], &link[0]);
if (strcmp(&links[count][0], &link[0])) {
pr_err("Symlink target %s has changed to %s\n", links[count], link);
return 1;
}
test_msg("Checking file contents...\n");
compare_file_content(fd[count], count);
test_msg("Closing file descriptor...\n");
if (close(fd[count]) == -1) {
pr_perror("Close failed");
return 1;
}
}
pass();
return 0;
}
| 5,829 | 21.337165 | 98 |
c
|
criu
|
criu-master/test/zdtm/static/uptime_grow.c
|
#include "zdtmtst.h"
const char *test_doc = "test to ensure that monotonic clock doesn't decrease";
const char *test_author = "Evgeny Antysev <[email protected]>";
#include <time.h>
#include <stdlib.h>
#define tv_ge(a, b) (((a)->tv_sec == (b)->tv_sec) ? ((a)->tv_nsec >= (b)->tv_nsec) : ((a)->tv_sec > (b)->tv_sec))
int main(int argc, char **argv)
{
struct timespec tm_old, tm, ts;
double diff_nsec;
ts.tv_sec = 0;
ts.tv_nsec = 1000000;
test_init(argc, argv);
if (clock_gettime(CLOCK_MONOTONIC, &tm_old)) {
pr_perror("clock_gettime failed");
exit(1);
}
test_daemon();
while (test_go()) {
if (clock_gettime(CLOCK_MONOTONIC, &tm)) {
pr_perror("clock_gettime failed");
exit(1);
}
if (!tv_ge(&tm, &tm_old)) {
diff_nsec = (tm_old.tv_sec - tm.tv_sec) * 1.0E9 + (tm_old.tv_nsec - tm.tv_nsec);
fail("clock step backward for %e nsec", diff_nsec);
exit(1);
}
tm_old = tm;
/*
Kernel can't suspend container by design if calls
clock_gettime() in a loop, so we need to sleep
between clock_gettime().
*/
nanosleep(&ts, NULL);
}
pass();
return 0;
}
| 1,101 | 21.958333 | 113 |
c
|
criu
|
criu-master/test/zdtm/static/vdso-proxy.c
|
#include <inttypes.h>
#include <stdbool.h>
#include <stdlib.h>
#include "zdtmtst.h"
const char *test_doc =
"Compare mappings before/after C/R for vdso/vvar presence. Should run iterative under vdso proxy fault-injection.\n";
const char *test_author = "Dmitry Safonov <[email protected]>";
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2 * !!(condition)]))
#define VSYSCALL_START 0xffffffffff600000ULL
/*
* Use constant MAX_VMAS - to minimize the risk of allocating a new
* mapping or changing the size of existent VMA with realloc()
*/
#define MAX_VMAS 80
#define BUF_SIZE 1024
/*
* After C/R with vdso trampolines insertion, there should
* be added one or two vmas: vdso and possibly vvar.
* We need to check that nr. vmas after C/R <= +2 new vmas.
* Also previous vdso/vvar vma should still be present after C/R.
*/
struct vm_area {
/*
* Intentionally use 64bit integer to make sure that it's possible
* to parse mappings >4Gb - those might appear on ia32
* that's restored by x86_64 CRIU ¯\(°_o)/¯
*/
uint64_t start;
uint64_t end;
bool is_vvar_or_vdso;
};
static char buf[BUF_SIZE];
static int parse_maps(struct vm_area *vmas)
{
FILE *maps;
int i;
maps = fopen("/proc/self/maps", "r");
if (maps == NULL) {
pr_perror("Failed to open maps file");
return -1;
}
for (i = 0; i < MAX_VMAS; i++) {
struct vm_area *v = &vmas[i];
char *end;
if (fgets(buf, BUF_SIZE, maps) == NULL)
break;
v->start = strtoull(buf, &end, 16);
v->end = strtoull(end + 1, NULL, 16);
#if defined(__i386__)
/*
* XXX: ia32 is being restored from x86_64 and leaves
* emulated vsyscall "mapping". Hopefully, will be done
* per-process, ignore for now.
*/
if (v->start == VSYSCALL_START) {
i--;
continue;
}
#endif
v->is_vvar_or_vdso |= strstr(buf, "[vdso]") != NULL;
v->is_vvar_or_vdso |= strstr(buf, "[vvar]") != NULL;
test_msg("[NOTE]\tVMA: [%#" PRIx64 ", %#" PRIx64 "]\n", v->start, v->end);
}
if (fclose(maps)) {
pr_perror("Failed to close maps file");
return -1;
}
if (i == MAX_VMAS) {
pr_err("Number of VMAs is bigger than reserved array's size\n");
return -1;
}
return i;
}
int compare_vmas(struct vm_area *vmax, struct vm_area *vmay)
{
if (vmax->start > vmay->start)
return 1;
if (vmax->start < vmay->start)
return -1;
if (vmax->end > vmay->end)
return 1;
if (vmax->end < vmay->end)
return -1;
return 0;
}
static int check_vvar_vdso(struct vm_area *before, struct vm_area *after)
{
int i, j = 0;
for (i = 0; i < MAX_VMAS && j < MAX_VMAS; i++, j++) {
int cmp = compare_vmas(&before[i], &after[j]);
if (cmp == 0)
continue;
if (cmp < 0) { /* Lost mapping */
test_msg("[NOTE]\tLost mapping: %#" PRIx64 "-%#" PRIx64 "\n", before[i].start, before[i].end);
j--;
if (before[i].is_vvar_or_vdso) {
fail("Lost vvar/vdso mapping");
return -1;
}
continue;
}
test_msg("[NOTE]\tNew mapping appeared: %#" PRIx64 "-%#" PRIx64 "\n", after[j].start, after[j].end);
i--;
}
return 0;
}
static struct vm_area vmas_before[MAX_VMAS];
static struct vm_area vmas_after[MAX_VMAS];
int main(int argc, char *argv[])
{
int nr_before, nr_after;
test_init(argc, argv);
test_msg("[NOTE]\tMappings before:\n");
nr_before = parse_maps(vmas_before);
if (nr_before < 0) {
pr_err("Failed to parse maps\n");
return -1;
}
test_daemon();
test_waitsig();
test_msg("[NOTE]\tMappings after:\n");
nr_after = parse_maps(vmas_after);
if (nr_after < 0) {
pr_err("Failed to parse maps\n");
return -1;
}
/* After restore vDSO/VVAR blobs must remain in the old place. */
if (check_vvar_vdso(vmas_before, vmas_after))
return -1;
if (nr_before + 2 < nr_after) {
fail("There is more than two (VVAR/vDSO) vmas added after C/R");
return -1;
}
pass();
return 0;
}
| 3,804 | 21.514793 | 118 |
c
|
criu
|
criu-master/test/zdtm/static/vdso01.c
|
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <elf.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include "zdtmtst.h"
const char *test_doc = "Check if we can use vDSO using direct vDSO calls\n";
const char *test_author = "Cyrill Gorcunov <[email protected]";
#ifdef __i386__
#define Ehdr_t Elf32_Ehdr
#define Sym_t Elf32_Sym
#define Phdr_t Elf32_Phdr
#define Word_t Elf32_Word
#define Dyn_t Elf32_Dyn
#define ELF_ST_TYPE ELF32_ST_TYPE
#define ELF_ST_BIND ELF32_ST_BIND
const char elf_ident[] = {
0x7f, 0x45, 0x4c, 0x46, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#else /* non-i386 */
#define Ehdr_t Elf64_Ehdr
#define Sym_t Elf64_Sym
#define Phdr_t Elf64_Phdr
#define Word_t Elf64_Word
#define Dyn_t Elf64_Dyn
#ifndef ELF_ST_TYPE
#define ELF_ST_TYPE ELF64_ST_TYPE
#endif
#ifndef ELF_ST_BIND
#define ELF_ST_BIND ELF64_ST_BIND
#endif
/*
* See Elf specification for this magic values.
*/
const char elf_ident[] = {
0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif
typedef int(__vdso_clock_gettime_t)(clockid_t clock, struct timespec *ts);
typedef long(__vdso_getcpu_t)(unsigned *cpu, unsigned *node, void *unused);
typedef int(__vdso_gettimeofday_t)(struct timeval *tv, struct timezone *tz);
typedef time_t(__vdso_time_t)(time_t *t);
#define TIME_DELTA_SEC (3)
#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2 * !!(condition)]))
#define VDSO_BAD_ADDR (-1ul)
struct vdso_symbol {
char name[32];
unsigned long offset;
};
#define VDSO_SYMBOL_INIT \
{ \
.offset = VDSO_BAD_ADDR, \
}
/* Check if symbol present in symtable */
static inline bool vdso_symbol_empty(struct vdso_symbol *s)
{
return s->offset == VDSO_BAD_ADDR && s->name[0] == '\0';
}
enum {
VDSO_SYMBOL_CLOCK_GETTIME,
VDSO_SYMBOL_GETCPU,
VDSO_SYMBOL_GETTIMEOFDAY,
VDSO_SYMBOL_TIME,
VDSO_SYMBOL_MAX
};
const char *vdso_symbols[VDSO_SYMBOL_MAX] = {
[VDSO_SYMBOL_CLOCK_GETTIME] = "__vdso_clock_gettime",
[VDSO_SYMBOL_GETCPU] = "__vdso_getcpu",
[VDSO_SYMBOL_GETTIMEOFDAY] = "__vdso_gettimeofday",
[VDSO_SYMBOL_TIME] = "__vdso_time",
};
struct vdso_symtable {
unsigned long vma_start;
unsigned long vma_end;
struct vdso_symbol symbols[VDSO_SYMBOL_MAX];
};
#define VDSO_SYMTABLE_INIT \
{ \
.vma_start = VDSO_BAD_ADDR, .vma_end = VDSO_BAD_ADDR, \
.symbols = { \
[0 ... VDSO_SYMBOL_MAX - 1] = (struct vdso_symbol)VDSO_SYMBOL_INIT, \
}, \
}
static bool __ptr_oob(void *ptr, void *start, size_t size)
{
void *end = (void *)((unsigned long)start + size);
return ptr > end || ptr < start;
}
static unsigned long elf_hash(const unsigned char *name)
{
unsigned long h = 0, g;
while (*name) {
h = (h << 4) + *name++;
g = h & 0xf0000000ul;
if (g)
h ^= g >> 24;
h &= ~g;
}
return h;
}
static int vdso_fill_symtable(char *mem, size_t size, struct vdso_symtable *t)
{
Phdr_t *dynamic = NULL, *load = NULL;
Ehdr_t *ehdr = (void *)mem;
Dyn_t *dyn_strtab = NULL;
Dyn_t *dyn_symtab = NULL;
Dyn_t *dyn_strsz = NULL;
Dyn_t *dyn_syment = NULL;
Dyn_t *dyn_hash = NULL;
Word_t *hash = NULL;
Phdr_t *phdr;
Dyn_t *d;
Word_t *bucket, *chain;
Word_t nbucket, nchain;
char *dynsymbol_names;
unsigned int i, j, k;
BUILD_BUG_ON(sizeof(elf_ident) != sizeof(ehdr->e_ident));
test_msg("Parsing at %lx %lx\n", (long)mem, (long)mem + (long)size);
/*
* Make sure it's a file we support.
*/
if (memcmp(ehdr->e_ident, elf_ident, sizeof(elf_ident))) {
pr_perror("Elf header magic mismatch");
return -EINVAL;
}
/*
* We need PT_LOAD and PT_DYNAMIC here. Each once.
*/
phdr = (void *)&mem[ehdr->e_phoff];
for (i = 0; i < ehdr->e_phnum; i++, phdr++) {
if (__ptr_oob(phdr, mem, size))
goto err_oob;
switch (phdr->p_type) {
case PT_DYNAMIC:
if (dynamic) {
pr_perror("Second PT_DYNAMIC header");
return -EINVAL;
}
dynamic = phdr;
break;
case PT_LOAD:
if (load) {
pr_perror("Second PT_LOAD header");
return -EINVAL;
}
load = phdr;
break;
}
}
if (!load || !dynamic) {
pr_perror("One of obligated program headers is missed");
return -EINVAL;
}
test_msg("PT_LOAD p_vaddr: %lx\n", (unsigned long)load->p_vaddr);
/*
* Dynamic section tags should provide us the rest of information
* needed. Note that we're interested in a small set of tags.
*/
d = (void *)&mem[dynamic->p_offset];
for (i = 0; i < dynamic->p_filesz / sizeof(*d); i++, d++) {
if (__ptr_oob(d, mem, size))
goto err_oob;
if (d->d_tag == DT_NULL) {
break;
} else if (d->d_tag == DT_STRTAB) {
dyn_strtab = d;
} else if (d->d_tag == DT_SYMTAB) {
dyn_symtab = d;
} else if (d->d_tag == DT_STRSZ) {
dyn_strsz = d;
} else if (d->d_tag == DT_SYMENT) {
dyn_syment = d;
} else if (d->d_tag == DT_HASH) {
dyn_hash = d;
}
}
if (!dyn_strtab || !dyn_symtab || !dyn_strsz || !dyn_syment || !dyn_hash) {
pr_perror("Not all dynamic entries are present");
return -EINVAL;
}
dynsymbol_names = &mem[dyn_strtab->d_un.d_val - load->p_vaddr];
if (__ptr_oob(dynsymbol_names, mem, size))
goto err_oob;
hash = (void *)&mem[(unsigned long)dyn_hash->d_un.d_ptr - (unsigned long)load->p_vaddr];
if (__ptr_oob(hash, mem, size))
goto err_oob;
nbucket = hash[0];
nchain = hash[1];
bucket = &hash[2];
chain = &hash[nbucket + 2];
test_msg("nbucket %lu nchain %lu bucket %p chain %p\n", (long)nbucket, (long)nchain, bucket, chain);
for (i = 0; i < ARRAY_SIZE(vdso_symbols); i++) {
k = elf_hash((const unsigned char *)vdso_symbols[i]);
for (j = bucket[k % nbucket]; j < nchain && j != STN_UNDEF; j = chain[j]) {
Sym_t *sym = (void *)&mem[dyn_symtab->d_un.d_ptr - load->p_vaddr];
char *name;
sym = &sym[j];
if (__ptr_oob(sym, mem, size))
continue;
if (ELF_ST_TYPE(sym->st_info) != STT_FUNC && ELF_ST_BIND(sym->st_info) != STB_GLOBAL)
continue;
name = &dynsymbol_names[sym->st_name];
if (__ptr_oob(name, mem, size))
continue;
if (strcmp(name, vdso_symbols[i]))
continue;
memcpy(t->symbols[i].name, name, sizeof(t->symbols[i].name));
t->symbols[i].offset = (unsigned long)sym->st_value - load->p_vaddr;
test_msg("symbol %s offset %lx\n", t->symbols[i].name, t->symbols[i].offset);
break;
}
}
return 0;
err_oob:
pr_perror("Corrupted Elf data");
return -EFAULT;
}
static int vdso_fill_self_symtable(struct vdso_symtable *s)
{
char buf[512];
int ret = -1;
FILE *maps;
*s = (struct vdso_symtable)VDSO_SYMTABLE_INIT;
maps = fopen("/proc/self/maps", "r");
if (!maps) {
pr_perror("Can't open self-vma");
return -1;
}
while (fgets(buf, sizeof(buf), maps)) {
unsigned long start, end;
if (!strstr(buf, "[vdso]"))
continue;
ret = sscanf(buf, "%lx-%lx", &start, &end);
if (ret != 2) {
ret = -1;
pr_perror("Can't find vDSO bounds");
goto err;
}
s->vma_start = start;
s->vma_end = end;
ret = vdso_fill_symtable((void *)start, end - start, s);
break;
}
test_msg("[vdso] %lx-%lx\n", s->vma_start, s->vma_end);
err:
fclose(maps);
return ret;
}
static int vdso_clock_gettime_handler(void *func)
{
__vdso_clock_gettime_t *vdso_clock_gettime = func;
struct timespec ts1, ts2;
clock_gettime(CLOCK_REALTIME, &ts1);
vdso_clock_gettime(CLOCK_REALTIME, &ts2);
test_msg("clock_gettime: tv_sec %li vdso_clock_gettime: tv_sec %li\n", ts1.tv_sec, ts2.tv_sec);
if (labs(ts1.tv_sec - ts2.tv_sec) > TIME_DELTA_SEC) {
pr_perror("Delta is too big");
return -1;
}
return 0;
}
static int vdso_getcpu_handler(void *func)
{
__vdso_getcpu_t *vdso_getcpu = func;
unsigned cpu, node;
vdso_getcpu(&cpu, &node, NULL);
test_msg("vdso_getcpu: cpu %d node %d\n", cpu, node);
return 0;
}
static int vdso_gettimeofday_handler(void *func)
{
__vdso_gettimeofday_t *vdso_gettimeofday = func;
struct timeval tv1, tv2;
struct timezone tz;
gettimeofday(&tv1, &tz);
vdso_gettimeofday(&tv2, &tz);
test_msg("gettimeofday: tv_sec %li vdso_gettimeofday: tv_sec %li\n", tv1.tv_sec, tv2.tv_sec);
if (labs(tv1.tv_sec - tv2.tv_sec) > TIME_DELTA_SEC) {
pr_perror("Delta is too big");
return -1;
}
return 0;
}
static int vdso_time_handler(void *func)
{
__vdso_time_t *vdso_time = func;
time_t t1, t2;
t1 = time(NULL);
t2 = vdso_time(NULL);
test_msg("time: %li vdso_time: %li\n", (long)t1, (long)t1);
if (labs(t1 - t2) > TIME_DELTA_SEC) {
pr_perror("Delta is too big");
return -1;
}
return 0;
}
static int call_handlers(struct vdso_symtable *symtable)
{
typedef int(handler_t)(void *func);
handler_t *handlers[VDSO_SYMBOL_MAX] = {
[VDSO_SYMBOL_CLOCK_GETTIME] = vdso_clock_gettime_handler,
[VDSO_SYMBOL_GETCPU] = vdso_getcpu_handler,
[VDSO_SYMBOL_GETTIMEOFDAY] = vdso_gettimeofday_handler,
[VDSO_SYMBOL_TIME] = vdso_time_handler,
};
size_t i;
for (i = 0; i < ARRAY_SIZE(symtable->symbols); i++) {
struct vdso_symbol *s = &symtable->symbols[i];
handler_t *func;
if (vdso_symbol_empty(s) || i > ARRAY_SIZE(handlers))
continue;
func = handlers[i];
if (func((void *)(s->offset + symtable->vma_start))) {
pr_perror("Handler error");
return -1;
}
}
return 0;
}
int main(int argc, char *argv[])
{
struct vdso_symtable symtable;
test_init(argc, argv);
if (vdso_fill_self_symtable(&symtable)) {
pr_perror("Failed to parse vdso");
return -1;
}
if (call_handlers(&symtable))
return -1;
test_daemon();
test_waitsig();
/*
* After restore the vDSO must remain in old place.
*/
if (call_handlers(&symtable)) {
fail("Failed to call vdso handlers from symtable after C/R");
return -1;
}
pass();
return 0;
}
| 10,085 | 21.819005 | 101 |
c
|
criu
|
criu-master/test/zdtm/static/vsx.c
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include "zdtmtst.h"
/*
* This test is specific to PowerPC
*/
#ifndef _ARCH_PPC64
int main(int argc, char *argv[])
{
test_init(argc, argv);
skip("Unsupported arch");
return 0;
}
#else
#include <sys/auxv.h>
#include <asm/cputable.h>
/*
* This test verifies that data stored in the VSX registers are still there
* once the restart is done.
*
* The test is filling the registers with dedicated values and then check
* their content.
*/
const char *test_doc = "Test if data in vector registers do survive the c/r";
const char *test_author = "Laurent Dufour <[email protected]>";
int is_test_doable(void)
{
unsigned long val;
val = getauxval(AT_HWCAP);
#define CHECK_FEATURE(f) \
do { \
if (!(val & f)) { \
test_msg("CPU feature " #f " is missing\n"); \
return 0; \
} \
} while (0)
CHECK_FEATURE(PPC_FEATURE_64);
CHECK_FEATURE(PPC_FEATURE_HAS_ALTIVEC);
CHECK_FEATURE(PPC_FEATURE_HAS_VSX);
return 1;
}
void fill_vsx(uint64_t *pt)
{
asm volatile("lis 3, 0 \n"
"lxvd2x 0, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 1, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 2, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 3, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 4, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 5, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 6, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 7, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 8, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 9, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 10, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 11, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 12, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 13, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 14, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 15, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 16, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 17, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 18, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 19, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 20, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 21, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 22, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 23, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 24, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 25, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 26, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 27, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 28, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 29, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 30, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 31, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 32, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 33, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 34, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 35, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 36, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 37, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 38, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 39, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 40, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 41, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 42, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 43, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 44, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 45, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 46, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 47, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 48, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 49, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 50, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 51, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 52, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 53, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 54, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 55, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 56, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 57, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 58, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 59, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 60, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 61, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 62, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"lxvd2x 63, 3, %0 \n"
: /* no output */
: "r"(pt)
: "3");
}
void read_vsx(uint64_t *pt)
{
asm volatile("lis 3, 0 \n"
"stxvd2x 0, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 1, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 2, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 3, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 4, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 5, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 6, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 7, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 8, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 9, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 10, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 11, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 12, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 13, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 14, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 15, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 16, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 17, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 18, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 19, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 20, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 21, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 22, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 23, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 24, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 25, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 26, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 27, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 28, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 29, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 30, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 31, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 32, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 33, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 34, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 35, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 36, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 37, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 38, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 39, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 40, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 41, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 42, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 43, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 44, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 45, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 46, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 47, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 48, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 49, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 50, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 51, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 52, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 53, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 54, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 55, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 56, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 57, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 58, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 59, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 60, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 61, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 62, 3, %0 \n"
"addi 3, 3, 16 \n" /* move to the next qword */
"stxvd2x 63, 3, %0 \n"
: /* no output */
: "r"(pt)
: "3");
}
int main(int argc, char *argv[])
{
/* A random buffer of 1024 bytes (64 * 128bit registers to fill) */
static const char ibuffer[128 / 8 * 64] = "sahwoleiGun9loosliz0Aech9aiph5eiIengei7Ogh8zu7ye"
"Aeshie6vai0thaehool1ooK6ayaj3Neitahn8yeeh5ahfuiT"
"uCeir1bife4ieceema8choo2Wengaec1seDaidohteipa4ai"
"aequee7AiriejaeJar1giak8Gei2uathloh5uemaeG6EiSoo"
"PhaenaethoPhej8nEecheegeihosho8Zohroo8ea6Juuheif"
"nu2Hahvai1tuf0Zeeeveephu2EitaexiVaekieboac7Nushu"
"aeTh6Quoo3iozeisaudaGheed0aPah2Schoog0eiChaeN5su"
"xoo1phoic1mahXohSai1thoogo0oesooeaxai7eBahHahMue"
"quiloh2ooPahpiujeithae0Dau0shuwicobinaaYooj0ajiw"
"iiheeS4awoh3haevlaiGe8phaev3eiluaChaF6ieng4aith4"
"aif3TooYo1aigoomZiuhai8eesoo4maiLahr3PoM8Eir5ooz"
"Iequ9ahre4Op4bahaiso6ohnah8Shokimooch1Oafahf5aih"
"xohphee1pi5Iecaiaigh7Eisah2uew5acie7wi6Zo0Eelah9"
"woi8QueerohfeiThaBoh5jaic3peiPohAhng0bu5shoop7ca"
"Qui5kodaika8quioahmohreeVe8loquaeeLi5ze3oceiHa0l"
"roh8Ooxae7uish9ioog7ieS3aibeo2thOosiuvaiS5lohp4U"
"emieG0eit6Bien8EzaiwiTh3geighaexshee8eHiec1TooH2"
"Eeceacai0inaejieboo8NeishieweiraHooj9apeecooy0th"
"daThei6aexeisahdsei3keik0diPheejchais6ezo0iep5Ae"
"Wiqu6aepeing4ba8diek3aev9waYooveAebai9eef6Iex6vo"
"Quee9MeitahMighoHuo3seveeMoh3ohtoxaib6ootaiF5EeT"
"Ohb9eijoonoh6ich";
char obuffer[128 / 8 * 64];
int do_test;
test_init(argc, argv);
do_test = is_test_doable();
if (do_test) {
memset(obuffer, 0xFF, sizeof(obuffer));
fill_vsx((uint64_t *)ibuffer);
}
test_daemon();
test_waitsig();
if (do_test) {
read_vsx((uint64_t *)obuffer);
if (!memcmp(ibuffer, obuffer, sizeof(ibuffer)))
pass();
else {
test_msg("Data mismatch\n");
fail();
}
} else {
test_msg("The CPU is missing some features.\n");
fail();
}
return 0;
}
#endif /* _ARCH_PPC64 */
| 14,102 | 34.434673 | 93 |
c
|
criu
|
criu-master/test/zdtm/transition/maps007.c
|
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/mman.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/uio.h>
#include <asm/unistd.h>
#include "zdtmtst.h"
#include "lock.h"
#define MAP_SIZE (1UL << 20)
#define MEM_SIZE (1UL << 29)
const char *test_doc = "create random mappings and touch memory";
int sys_process_vm_readv(pid_t pid, void *addr, void *buf, int size)
{
struct iovec lvec = { .iov_base = buf, .iov_len = size };
struct iovec rvec = { .iov_base = addr, .iov_len = size };
/* workaround bug in glibc with sixth argument of syscall */
char nop[PAGE_SIZE];
memset(nop, 0, sizeof(nop));
return syscall(__NR_process_vm_readv, pid, &lvec, 1, &rvec, 1, 0);
}
/* The child follows the parents two steps behind. */
#define MAX_DELTA 1000
int main(int argc, char **argv)
{
void *start, *end, *p;
pid_t child;
struct {
futex_t delta;
futex_t stop;
} *shm;
uint32_t v;
unsigned long long count = 0;
int i;
test_init(argc, argv);
/* shared memory for synchronization */
shm = mmap(NULL, PAGE_SIZE, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (shm == MAP_FAILED)
return -1;
/* allocate workspace */
start = mmap(NULL, MEM_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (start == MAP_FAILED)
return -1;
test_msg("%p-%p\n", start, start + MEM_SIZE);
end = start + MEM_SIZE;
v = 0;
futex_set(&shm->delta, v);
futex_set(&shm->stop, 0);
child = fork();
if (child < 0) {
pr_perror("fork");
return 1;
}
while (1) {
void *ret;
unsigned long size;
int prot = PROT_NONE;
if (child) {
if (!test_go())
break;
futex_wait_while_gt(&shm->delta, 2 * MAX_DELTA);
futex_inc_and_wake(&shm->delta);
} else {
if (!futex_get(&shm->stop))
/* shm->delta must be always bigger than MAX_DELTA */
futex_wait_while_lt(&shm->delta, MAX_DELTA + 2);
else if (count % 100 == 0)
test_msg("count %llu delta %d\n", count, futex_get(&shm->delta)); /* heartbeat */
if (futex_get(&shm->stop) && atomic_get(&shm->delta.raw) == MAX_DELTA)
break;
futex_dec_and_wake(&shm->delta);
}
count++;
if (child && count == MAX_DELTA + 1)
test_daemon();
p = start + ((lrand48() * PAGE_SIZE) % MEM_SIZE);
size = lrand48() * PAGE_SIZE;
size %= (end - p);
size %= MAP_SIZE;
if (size == 0)
size = PAGE_SIZE;
if (lrand48() % 2)
prot |= PROT_READ;
if (lrand48() % 2)
prot |= PROT_EXEC;
if (lrand48() % 2)
prot |= PROT_WRITE;
ret = mmap(p, size, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
if (ret == MAP_FAILED) {
pr_perror("%p-%p", p, p + size);
goto err;
}
if (!(prot & PROT_WRITE))
continue;
for (i = 0; i < lrand48() % 50; i++) {
char *t = p + (lrand48() * PAGE_SIZE) % (size);
t[0] = lrand48();
}
}
test_msg("count %llu\n", count);
if (child == 0) {
if (!test_go())
pr_perror("unexpected state");
futex_set_and_wake(&shm->stop, 2);
test_waitsig();
return 0;
} else {
int readable = 0, status = -1;
/* stop the child */
futex_set(&shm->stop, 1);
futex_add_and_wake(&shm->delta, MAX_DELTA);
/* wait until the child will be in the same point */
futex_wait_until(&shm->stop, 2);
/* check that child and parent have the identical content of memory */
for (p = start; p < end; p += PAGE_SIZE) {
char rbuf[PAGE_SIZE], lbuf[PAGE_SIZE];
int rret, lret;
lret = sys_process_vm_readv(getpid(), p, lbuf, PAGE_SIZE);
rret = sys_process_vm_readv(child, p, rbuf, PAGE_SIZE);
if (rret != lret) {
pr_perror("%p %d %d", p, lret, rret);
goto err;
}
if (lret < 0)
continue;
readable++;
if (memcmp(rbuf, lbuf, PAGE_SIZE)) {
pr_perror("%p", p);
goto err;
}
}
test_msg("readable %d\n", readable);
kill(child, SIGTERM);
wait(&status);
if (status != 0) {
pr_perror("Non-zero exit code: %d", status);
goto err;
}
pass();
}
return 0;
err:
kill(child, SIGSEGV);
*((volatile int *)0) = 0;
return 1;
}
| 4,002 | 21.488764 | 88 |
c
|
criu
|
criu-master/test/zdtm/transition/maps008.c
|
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include "zdtmtst.h"
#include "lock.h"
const char *test_doc = "ps tree with anon shared vmas for dedup";
/*
* 1. ps tree with non triavial anon shmem vmas is created first.
* 2. Each process gets its portion of shmem vmas.
* 3. Each process continuously datagens its portion until
* criu dump is finished.
* 4. Each process datachecks all its shmem portions after restore.
* 5. Contents of anon shmem vmas are checked for equality in
* different processes.
*/
typedef int (*proc_func_t)(task_waiter_t *setup_waiter);
static pid_t fork_and_setup(proc_func_t pfunc)
{
task_waiter_t setup_waiter;
pid_t pid;
task_waiter_init(&setup_waiter);
pid = test_fork();
if (pid < 0) {
pr_perror("fork failed");
exit(1);
}
if (pid == 0)
exit(pfunc(&setup_waiter));
task_waiter_wait4(&setup_waiter, pid);
task_waiter_fini(&setup_waiter);
return pid;
}
static void cont_and_wait_child(pid_t pid)
{
int status;
kill(pid, SIGTERM);
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status))
exit(WEXITSTATUS(status));
} else
exit(1);
}
static void *mmap_ashmem(size_t size)
{
void *mem = mmap(NULL, size, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (mem == MAP_FAILED) {
pr_perror("Can't map shmem %zx", size);
exit(1);
}
return mem;
}
static void *mmap_proc_mem(pid_t pid, unsigned long addr, unsigned long size)
{
int fd;
void *mem;
char path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/%d/map_files/%lx-%lx", (int)pid, addr, addr + size);
fd = open(path, O_RDWR);
if (fd == -1) {
pr_perror("Can't open file %s", path);
exit(1);
}
mem = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (mem == MAP_FAILED) {
pr_perror("Can't map file %s", path);
exit(1);
}
return mem;
}
static void check_mem_eq(void *addr1, size_t size1, void *addr2, size_t size2)
{
unsigned long min_size = size1 < size2 ? size1 : size2;
if (memcmp(addr1, addr2, min_size)) {
pr_err("Mem differs %lx %lx %lx\n", (unsigned long)addr1, (unsigned long)addr2, min_size);
exit(1);
}
}
static void xmunmap(void *map, size_t size)
{
if (munmap(map, size)) {
pr_perror("xmunmap");
exit(1);
}
}
static void chk_proc_mem_eq(pid_t pid1, void *addr1, unsigned long size1, pid_t pid2, void *addr2, unsigned long size2)
{
void *map1, *map2;
map1 = mmap_proc_mem(pid1, (unsigned long)addr1, size1);
map2 = mmap_proc_mem(pid2, (unsigned long)addr2, size2);
check_mem_eq(map1, size1, map2, size2);
xmunmap(map1, size1);
xmunmap(map2, size2);
}
/*
* ps tree:
* proc1_______________
* | | |
* proc11___ proc12 proc13
* | | |
* proc111 proc112 proc131
*/
#define PROC_CNT 7
#define PROC1_PGIX 0
#define PROC11_PGIX 1
#define PROC12_PGIX 2
#define PROC13_PGIX 3
#define PROC111_PGIX 4
#define PROC112_PGIX 5
#define PROC131_PGIX 6
#define ZERO_PGIX 7
/* unused pgix: 8 */
#define MEM_PERIOD (9 * PAGE_SIZE)
struct pstree {
pid_t proc1;
pid_t proc11;
pid_t proc12;
pid_t proc13;
pid_t proc111;
pid_t proc112;
pid_t proc131;
};
struct pstree *pstree;
struct test_sync {
futex_t datagen;
futex_t datagen_exit_cnt;
};
struct test_sync *test_sync;
size_t mem1_size, mem2_size, mem3_size;
uint8_t *mem1, *mem2, *mem3;
#define CRC_EPOCH_OFFSET (PAGE_SIZE - sizeof(uint32_t))
static void read_each_pg(volatile uint8_t *mem, size_t size, size_t off)
{
if (!mem)
return;
while (off < size) {
(mem + off)[0];
off += MEM_PERIOD;
}
}
void datagen_each_pg(uint8_t *mem, size_t size, size_t off, uint32_t crc_epoch)
{
if (!mem)
return;
while (futex_get(&test_sync->datagen) && (off < size)) {
uint32_t crc = crc_epoch;
datagen(mem + off, CRC_EPOCH_OFFSET, &crc);
*(uint32_t *)(mem + off + CRC_EPOCH_OFFSET) = crc_epoch;
off += MEM_PERIOD;
}
}
void datachck_each_pg(uint8_t *mem, size_t size, size_t off)
{
if (!mem)
return;
while (off < size) {
uint32_t crc = *(uint32_t *)(mem + off + CRC_EPOCH_OFFSET);
if (datachk(mem + off, CRC_EPOCH_OFFSET, &crc))
exit(1);
off += MEM_PERIOD;
}
}
static void mems_read_each_pgix(size_t pgix)
{
const size_t off = pgix * PAGE_SIZE;
read_each_pg(mem1, mem1_size, off);
read_each_pg(mem2, mem2_size, off);
read_each_pg(mem3, mem3_size, off);
}
static void mems_datagen_each_pgix(size_t pgix, uint32_t *crc_epoch)
{
const size_t off = pgix * PAGE_SIZE;
++(*crc_epoch);
datagen_each_pg(mem1, mem1_size, off, *crc_epoch);
datagen_each_pg(mem2, mem2_size, off, *crc_epoch);
datagen_each_pg(mem3, mem3_size, off, *crc_epoch);
}
static void mems_datachck_each_pgix(size_t pgix)
{
const size_t off = pgix * PAGE_SIZE;
datachck_each_pg(mem1, mem1_size, off);
datachck_each_pg(mem2, mem2_size, off);
datachck_each_pg(mem3, mem3_size, off);
}
static int proc131_func(task_waiter_t *setup_waiter)
{
uint32_t crc_epoch = 0;
pstree->proc131 = getpid();
mems_datagen_each_pgix(PROC131_PGIX, &crc_epoch);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC131_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC131_PGIX);
return 0;
}
static int proc13_func(task_waiter_t *setup_waiter)
{
size_t MEM1_HOLE_START = 2 * MEM_PERIOD;
size_t MEM1_HOLE_SIZE = 1 * MEM_PERIOD;
uint32_t crc_epoch = 0;
pstree->proc13 = getpid();
xmunmap(mem1 + MEM1_HOLE_START, MEM1_HOLE_SIZE);
xmunmap(mem2, mem2_size);
xmunmap(mem3, mem3_size);
mem2 = mem1 + MEM1_HOLE_START + MEM1_HOLE_SIZE;
mem2_size = mem1_size - (mem2 - mem1);
mem1_size = MEM1_HOLE_START;
mem3 = mmap_ashmem(mem3_size);
mems_datagen_each_pgix(PROC13_PGIX, &crc_epoch);
fork_and_setup(proc131_func);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC13_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC13_PGIX);
chk_proc_mem_eq(pstree->proc13, mem1, mem1_size, pstree->proc131, mem1, mem1_size);
chk_proc_mem_eq(pstree->proc13, mem2, mem2_size, pstree->proc131, mem2, mem2_size);
chk_proc_mem_eq(pstree->proc13, mem3, mem3_size, pstree->proc131, mem3, mem3_size);
cont_and_wait_child(pstree->proc131);
return 0;
}
static int proc12_func(task_waiter_t *setup_waiter)
{
uint32_t crc_epoch = 0;
pstree->proc12 = getpid();
mems_datagen_each_pgix(PROC12_PGIX, &crc_epoch);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC12_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC12_PGIX);
return 0;
}
static int proc111_func(task_waiter_t *setup_waiter)
{
uint32_t crc_epoch = 0;
pstree->proc111 = getpid();
mems_datagen_each_pgix(PROC111_PGIX, &crc_epoch);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC111_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC111_PGIX);
return 0;
}
static int proc112_func(task_waiter_t *setup_waiter)
{
uint32_t crc_epoch = 0;
pstree->proc112 = getpid();
mems_datagen_each_pgix(PROC112_PGIX, &crc_epoch);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC112_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC112_PGIX);
return 0;
}
static int proc11_func(task_waiter_t *setup_waiter)
{
const size_t MEM3_START_CUT = 1 * MEM_PERIOD;
const size_t MEM3_END_CUT = 2 * MEM_PERIOD;
void *mem3_old = mem3;
size_t mem3_size_old = mem3_size;
uint32_t crc_epoch = 0;
uint8_t *proc1_mem3;
pstree->proc11 = getpid();
xmunmap(mem3, MEM3_START_CUT);
mem3 += MEM3_START_CUT;
mem3_size -= MEM3_START_CUT;
fork_and_setup(proc111_func);
fork_and_setup(proc112_func);
xmunmap(mem3 + mem3_size - MEM3_END_CUT, MEM3_END_CUT);
mem3_size -= MEM3_END_CUT;
mems_datagen_each_pgix(PROC11_PGIX, &crc_epoch);
task_waiter_complete_current(setup_waiter);
while (futex_get(&test_sync->datagen))
mems_datagen_each_pgix(PROC11_PGIX, &crc_epoch);
futex_inc_and_wake(&test_sync->datagen_exit_cnt);
test_waitsig();
mems_datachck_each_pgix(PROC11_PGIX);
chk_proc_mem_eq(pstree->proc11, mem1, mem1_size, pstree->proc111, mem1, mem1_size);
chk_proc_mem_eq(pstree->proc11, mem1, mem1_size, pstree->proc112, mem1, mem1_size);
chk_proc_mem_eq(pstree->proc11, mem2, mem2_size, pstree->proc111, mem2, mem2_size);
chk_proc_mem_eq(pstree->proc11, mem2, mem2_size, pstree->proc112, mem2, mem2_size);
chk_proc_mem_eq(pstree->proc11, mem3, mem3_size, pstree->proc111, mem3, mem3_size + MEM3_END_CUT);
chk_proc_mem_eq(pstree->proc11, mem3, mem3_size, pstree->proc112, mem3, mem3_size + MEM3_END_CUT);
proc1_mem3 = mmap_proc_mem(pstree->proc1, (unsigned long)mem3_old, mem3_size_old);
check_mem_eq(mem3, mem3_size, proc1_mem3 + MEM3_START_CUT, mem3_size);
xmunmap(proc1_mem3, mem3_size_old);
cont_and_wait_child(pstree->proc111);
cont_and_wait_child(pstree->proc112);
return 0;
}
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MB(n) ((n) * (1UL << 20))
static int proc1_func(void)
{
uint32_t crc_epoch = 0;
uint8_t *mem2_old = NULL;
/*
* Min mem size:
* At least 5 mem periods for mem pages and vma holes.
* At least 1 MB mem size not to test on tiny working set.
*/
mem1_size = MEM_PERIOD * MAX(5, MB(1) / MEM_PERIOD + 1);
mem2_size = mem1_size * 2;
mem3_size = mem2_size * 3;
futex_set(&test_sync->datagen, 1);
pstree->proc1 = getpid();
mem1 = mmap_ashmem(mem1_size);
mem2 = mmap_ashmem(mem2_size);
mem3 = mmap_ashmem(mem3_size);
mems_datagen_each_pgix(PROC1_PGIX, &crc_epoch);
mems_read_each_pgix(ZERO_PGIX);
fork_and_setup(proc11_func);
fork_and_setup(proc12_func);
fork_and_setup(proc13_func);
xmunmap(mem1, mem1_size);
if (mremap(mem2, mem2_size, mem1_size, MREMAP_MAYMOVE | MREMAP_FIXED, mem1) != mem1) {
pr_perror("proc1 mem2 remap");
exit(1);
}
mem2_old = mem2;
mem2 = NULL;
test_daemon();
while (test_go())
mems_datagen_each_pgix(PROC1_PGIX, &crc_epoch);
test_waitsig();
futex_set(&test_sync->datagen_exit_cnt, 0);
futex_set(&test_sync->datagen, 0);
futex_wait_while(&test_sync->datagen_exit_cnt, PROC_CNT);
mems_datachck_each_pgix(PROC1_PGIX);
chk_proc_mem_eq(pstree->proc1, mem1, mem1_size, pstree->proc11, mem2_old, mem2_size);
chk_proc_mem_eq(pstree->proc1, mem1, mem1_size, pstree->proc12, mem2_old, mem2_size);
chk_proc_mem_eq(pstree->proc1, mem3, mem3_size, pstree->proc12, mem3, mem3_size);
cont_and_wait_child(pstree->proc11);
cont_and_wait_child(pstree->proc12);
cont_and_wait_child(pstree->proc13);
pass();
return 0;
}
static void kill_pstree_from_root(void)
{
if (getpid() != pstree->proc1)
return;
kill(pstree->proc11, SIGKILL);
kill(pstree->proc12, SIGKILL);
kill(pstree->proc13, SIGKILL);
kill(pstree->proc111, SIGKILL);
kill(pstree->proc112, SIGKILL);
kill(pstree->proc131, SIGKILL);
}
static void sigchld_hand(int signo, siginfo_t *info, void *ucontext)
{
if (info->si_code != CLD_EXITED)
return;
if (!info->si_status)
return;
/*
* If we are not ps tree root then propagate child error to parent.
* If we are ps tree root then also call all
* atexit handlers set up by zdtm test framework and this test.
* exit() is not async signal safe but it's ok for testing purposes.
* exit() usage allows us to use very simple error handling
* and pstree killing logic.
*/
exit(info->si_status);
}
int main(int argc, char **argv)
{
struct sigaction sa = { .sa_sigaction = sigchld_hand, .sa_flags = SA_RESTART | SA_SIGINFO | SA_NOCLDSTOP };
sigemptyset(&sa.sa_mask);
test_init(argc, argv);
pstree = (struct pstree *)mmap_ashmem(PAGE_SIZE);
test_sync = (struct test_sync *)mmap_ashmem(sizeof(*test_sync));
if (sigaction(SIGCHLD, &sa, NULL)) {
pr_perror("SIGCHLD handler setup");
exit(1);
};
if (atexit(kill_pstree_from_root)) {
pr_err("Can't setup atexit cleanup func\n");
exit(1);
}
return proc1_func();
}
| 12,395 | 24.144016 | 119 |
c
|
criu
|
criu-master/test/zdtm/transition/netlink00.c
|
/* Description: testcase for netlink sockets migration.
* e.g.
* ip rule show
* ip rule add
* ip rule show
* ip rule del
* in a loop
*/
#include <asm/types.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <linux/netlink.h>
#include <string.h>
#include <linux/rtnetlink.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include "zdtmtst.h"
#undef DEBUG
//#define DEBUG
const char *test_doc = "Netlink socket loop";
const char *test_author = "Andrew Vagin ([email protected])";
//buffer to hold the RTNETLINK request
struct {
struct nlmsghdr nl;
struct rtmsg rt;
char buf[8192];
} req;
// variables used for
// socket communications
int fd;
struct sockaddr_nl la;
struct sockaddr_nl pa;
struct msghdr msg;
struct iovec iov;
int rtn;
// buffer to hold the RTNETLINK reply(ies)
char buf[8192];
char dsts[24] = "192.168.0.255";
int pn = 32; //network prefix
// RTNETLINK message pointers & lengths
// used when processing messages
struct nlmsghdr *nlp;
int nll;
struct rtmsg *rtp;
int rtl;
struct rtattr *rtap;
int send_request(void);
int recv_reply(void);
int form_request_add(void);
int form_request_del(void);
int read_reply(void);
typedef int (*cmd_t)(void);
#define CMD_NUM 2
cmd_t cmd[CMD_NUM] = { form_request_add, form_request_del };
int main(int argc, char *argv[])
{
int i;
test_init(argc, argv);
fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
pr_perror("socket");
goto out;
}
// setup local address & bind using
// this address
bzero(&la, sizeof(la));
la.nl_family = AF_NETLINK;
la.nl_pid = getpid();
if (bind(fd, (struct sockaddr *)&la, sizeof(la))) {
pr_perror("bind failed");
goto out;
}
//Preparation:
form_request_del();
send_request();
recv_reply();
test_daemon();
while (test_go()) {
for (i = 0; i < CMD_NUM; i++) {
cmd[i]();
if (send_request() < 0) {
fail("send_request failed");
goto out;
};
if (recv_reply() < 0) {
fail("RTNETLINK answers");
goto out;
};
#ifdef DEBUG
if (read_reply() < 0) {
fail("read_reply failed");
goto out;
}
#endif
}
}
pass();
out:
return 0;
}
int send_request(void)
{
// create the remote address
// to communicate
bzero(&pa, sizeof(pa));
pa.nl_family = AF_NETLINK;
// initialize & create the struct msghdr supplied
// to the sendmsg() function
bzero(&msg, sizeof(msg));
msg.msg_name = (void *)&pa;
msg.msg_namelen = sizeof(pa);
// place the pointer & size of the RTNETLINK
// message in the struct msghdr
iov.iov_base = (void *)&req.nl;
iov.iov_len = req.nl.nlmsg_len;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
// send the RTNETLINK message to kernel
rtn = sendmsg(fd, &msg, 0);
if (rtn < 0) {
pr_perror("sendmsg failed");
return -1;
}
return 0;
}
int recv_reply(void)
{
char *p;
// initialize the socket read buffer
bzero(buf, sizeof(buf));
p = buf;
nll = 0;
// read from the socket until the NLMSG_DONE is
// returned in the type of the RTNETLINK message
// or if it was a monitoring socket
while (1) {
rtn = recv(fd, p, sizeof(buf) - nll, 0);
if (rtn < 0) {
pr_perror("recv failed");
return -1;
}
if (rtn == 0) {
pr_err("EOF on netlink\n");
return -1;
}
nlp = (struct nlmsghdr *)p;
if (nlp->nlmsg_type == NLMSG_DONE)
return 0;
if (nlp->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nlp);
errno = -err->error;
if (errno) {
return -1;
}
return 0;
}
// increment the buffer pointer to place
// next message
p += rtn;
// increment the total size by the size of
// the last received message
nll += rtn;
if ((la.nl_groups & RTMGRP_IPV4_ROUTE) == RTMGRP_IPV4_ROUTE)
break;
}
return 0;
}
int read_reply(void)
{
//string to hold content of the route
// table (i.e. one entry)
char dsts[24], gws[24], ifs[16], ms[24];
// outer loop: loops thru all the NETLINK
// headers that also include the route entry
// header
nlp = (struct nlmsghdr *)buf;
for (; NLMSG_OK(nlp, nll); nlp = NLMSG_NEXT(nlp, nll)) {
// get route entry header
rtp = (struct rtmsg *)NLMSG_DATA(nlp);
// we are only concerned about the
// main route table
if (rtp->rtm_table != RT_TABLE_MAIN)
continue;
// init all the strings
bzero(dsts, sizeof(dsts));
bzero(gws, sizeof(gws));
bzero(ifs, sizeof(ifs));
bzero(ms, sizeof(ms));
// inner loop: loop thru all the attributes of
// one route entry
rtap = (struct rtattr *)RTM_RTA(rtp);
rtl = RTM_PAYLOAD(nlp);
for (; RTA_OK(rtap, rtl); rtap = RTA_NEXT(rtap, rtl)) {
switch (rtap->rta_type) {
// destination IPv4 address
case RTA_DST:
inet_ntop(AF_INET, RTA_DATA(rtap), dsts, 24);
break;
// next hop IPv4 address
case RTA_GATEWAY:
inet_ntop(AF_INET, RTA_DATA(rtap), gws, 24);
break;
// unique ID associated with the network
// interface
case RTA_OIF:
sprintf(ifs, "%d", *((int *)RTA_DATA(rtap)));
default:
break;
}
}
sprintf(ms, "%d", rtp->rtm_dst_len);
test_msg("dst %s/%s gw %s if %s\n", dsts, ms, gws, ifs);
}
return 0;
}
#define NLMSG_TAIL(nmsg) ((struct rtattr *)(((void *)(nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
int form_request_del(void)
{
bzero(&req, sizeof(req));
req.nl.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
rtap = NLMSG_TAIL(&req.nl);
rtap->rta_type = RTA_DST;
rtap->rta_len = RTA_LENGTH(4);
inet_pton(AF_INET, dsts, ((char *)rtap) + sizeof(struct rtattr));
req.nl.nlmsg_len = NLMSG_ALIGN(req.nl.nlmsg_len) + RTA_ALIGN(rtap->rta_len);
req.nl.nlmsg_flags = NLM_F_CREATE | NLM_F_ACK | NLM_F_REQUEST;
req.nl.nlmsg_type = RTM_DELROUTE;
req.rt.rtm_family = AF_INET;
req.rt.rtm_table = RT_TABLE_MAIN;
req.rt.rtm_protocol = RTPROT_STATIC;
req.rt.rtm_scope = RT_SCOPE_UNIVERSE;
req.rt.rtm_type = RTN_UNICAST;
req.rt.rtm_dst_len = pn;
return 0;
}
int form_request_add(void)
{
int ifcn = 1; //interface number
bzero(&req, sizeof(req));
req.nl.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
rtap = NLMSG_TAIL(&req.nl);
rtap->rta_type = RTA_DST;
rtap->rta_len = RTA_LENGTH(4);
inet_pton(AF_INET, dsts, ((char *)rtap) + sizeof(struct rtattr));
req.nl.nlmsg_len = NLMSG_ALIGN(req.nl.nlmsg_len) + RTA_ALIGN(rtap->rta_len);
rtap = NLMSG_TAIL(&req.nl);
rtap->rta_type = RTA_OIF; //Output interface index
rtap->rta_len = RTA_LENGTH(sizeof(int));
memcpy(((char *)rtap) + sizeof(struct rtattr), &ifcn, sizeof(int));
req.nl.nlmsg_len = NLMSG_ALIGN(req.nl.nlmsg_len) + RTA_ALIGN(rtap->rta_len);
req.nl.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_ACK;
req.nl.nlmsg_type = RTM_NEWROUTE;
req.rt.rtm_family = AF_INET;
req.rt.rtm_table = RT_TABLE_MAIN;
req.rt.rtm_protocol = RTPROT_STATIC;
req.rt.rtm_scope = RT_SCOPE_UNIVERSE;
req.rt.rtm_type = RTN_UNICAST;
req.rt.rtm_dst_len = pn;
return 0;
}
| 6,892 | 22.525597 | 95 |
c
|
criu
|
criu-master/test/zdtm/transition/rseq01.c
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include <syscall.h>
#include "zdtmtst.h"
#ifdef __has_include
#if __has_include("sys/rseq.h")
#include <sys/rseq.h>
#endif
#endif
#if defined(__x86_64__)
#if defined(__x86_64__) && defined(RSEQ_SIG)
static inline void *thread_pointer(void)
{
void *result;
asm("mov %%fs:0, %0" : "=r"(result));
return result;
}
static inline void unregister_old_rseq(void)
{
/* unregister rseq */
syscall(__NR_rseq, (void *)((char *)thread_pointer() + __rseq_offset), __rseq_size, 1, RSEQ_SIG);
}
#else
static inline void unregister_old_rseq(void)
{
}
#endif
const char *test_doc = "rseq() transition test";
const char *test_author = "Alexander Mikhalitsyn <[email protected]>";
/*
* Thanks to Mathieu Desnoyers <[email protected]> (rseq author)
* who helped me with review and debugging the problem on the Alpine Linux.
*
* parts of code borrowed from
* https://www.efficios.com/blog/2019/02/08/linux-restartable-sequences/
*/
/* some useful definitions from kernel uapi */
#ifndef RSEQ_SIG
enum rseq_flags {
RSEQ_FLAG_UNREGISTER = (1 << 0),
};
enum rseq_cs_flags_bit {
RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT = 0,
RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT = 1,
RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT = 2,
};
enum rseq_cs_flags {
RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT),
RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT),
RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE = (1U << RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT),
};
struct rseq {
uint32_t cpu_id_start;
uint32_t cpu_id;
uint64_t rseq_cs;
uint32_t flags;
} __attribute__((aligned(4 * sizeof(uint64_t))));
#define RSEQ_SIG 0x53053053
#endif
#ifndef __NR_rseq
#define __NR_rseq 334
#endif
/* EOF */
static __thread volatile struct rseq *rseq_ptr;
static __thread volatile struct rseq __rseq_abi;
static int sys_rseq(volatile struct rseq *rseq_abi, uint32_t rseq_len, int flags, uint32_t sig)
{
return syscall(__NR_rseq, rseq_abi, rseq_len, flags, sig);
}
static void register_thread(void)
{
int rc;
unregister_old_rseq();
rc = sys_rseq(rseq_ptr, sizeof(struct rseq), 0, RSEQ_SIG);
if (rc) {
fail("Failed to register rseq");
exit(1);
}
}
static void check_thread(void)
{
int rc;
rc = sys_rseq(rseq_ptr, sizeof(struct rseq), 0, RSEQ_SIG);
if (!(rc && errno == EBUSY)) {
fail("Failed to check rseq %d", rc);
exit(1);
}
}
#define RSEQ_ACCESS_ONCE(x) (*(__volatile__ __typeof__(x) *)&(x))
#define rseq_after_asm_goto() asm volatile("" : : : "memory")
static int rseq_addv(intptr_t *v, intptr_t count, int cpu, bool ignore_abort, const char *id)
{
double a = 10000000000000000.0;
double b = -1;
uint64_t rseq_cs1 = 0, rseq_cs2 = 0;
/* clang-format off */
__asm__ __volatile__ goto(
".pushsection __rseq_table, \"aw\"\n\t"
".balign 32\n\t"
"cs_obj:\n\t"
/* version, flags */
".long 0, 0\n\t"
/* start_ip, post_commit_offset, abort_ip */
".quad 1f, (2f-1f), 4f\n\t"
".popsection\n\t"
"fldl %[x]\n\t" /* we have st clobbered */
"leaq cs_obj(%%rip), %%rax\n\t"
"1:\n\t"
"movq %%rax, %[rseq_cs]\n\t"
"cmpl %[cpu_id], %[current_cpu_id]\n\t"
"jnz 4f\n\t"
"addq %[count], %[v]\n\t" /* final store */
"mov $10000000, %%rcx\n\t"
"5:\n\t"
"fsqrt\n\t" /* heavy instruction */
"dec %%rcx\n\t"
"jnz 5b\n\t"
"movq %%rax, %[rseq_cs_check2]\n\t"
"movq %[rseq_cs], %%rax\n\t"
"movq %%rax, %[rseq_cs_check1]\n\t"
"fstpl %[y]\n\t"
"2:\n\t"
".pushsection __rseq_failure, \"ax\"\n\t"
/* Disassembler-friendly signature: nopl <sig>(%rip). */
".byte 0x0f, 0xb9, 0x3d\n\t"
".long 0x53053053\n\t" /* RSEQ_FLAGS */
"4:\n\t"
"fstpl %[y]\n\t"
"jmp %l[abort]\n\t"
/*"jmp 1b\n\t"*/
".popsection\n\t"
: /* gcc asm goto does not allow outputs */
: [cpu_id] "r" (cpu),
[current_cpu_id] "m" (rseq_ptr->cpu_id),
[rseq_cs] "m" (rseq_ptr->rseq_cs),
[rseq_cs_check1] "m" (rseq_cs1),
[rseq_cs_check2] "m" (rseq_cs2),
/* final store input */
[v] "m" (*v),
[count] "er" (count),
[x] "m" (a),
[y] "m" (b)
: "memory", "cc", "rax", "rcx", "st"
: abort
);
/* clang-format on */
rseq_after_asm_goto();
test_msg("exit %s, %lx %lx %f %f\n", id, rseq_cs1, rseq_cs2, a, b);
if (rseq_cs1 != rseq_cs2) {
/*
* It means that we finished critical section
* *normally* (haven't jumped to abort) but the kernel had cleaned up
* rseq_ptr->rseq_cs before we left critical section
* and CRIU didn't restore it correctly.
* That's a bug picture.
*/
return -1;
}
return 0;
abort:
rseq_after_asm_goto();
test_msg("abort %s, %lx %lx %f %f\n", id, rseq_cs1, rseq_cs2, a, b);
if (ignore_abort)
return 0;
return -1;
}
static task_waiter_t waiter;
static intptr_t *cpu_data;
bool ignore_abort = true;
int thread_ret;
void *thread_routine(void *args)
{
int cpu;
rseq_ptr = &__rseq_abi;
memset((void *)rseq_ptr, 0, sizeof(struct rseq));
register_thread();
task_waiter_complete(&waiter, 1);
task_waiter_wait4(&waiter, 2);
while (test_go()) {
cpu = RSEQ_ACCESS_ONCE(rseq_ptr->cpu_id_start);
thread_ret = rseq_addv(&cpu_data[cpu], 2, cpu, ignore_abort, "thread");
if (thread_ret)
break;
}
check_thread();
return NULL;
}
int main(int argc, char *argv[])
{
int cpu = 0;
int ret;
long nr_cpus;
pthread_t thread;
rseq_ptr = &__rseq_abi;
memset((void *)rseq_ptr, 0, sizeof(struct rseq));
test_init(argc, argv);
nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
cpu_data = calloc(nr_cpus, sizeof(*cpu_data));
if (!cpu_data) {
fail("calloc");
exit(EXIT_FAILURE);
}
register_thread();
/*
* We want to test that RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL
* is handled properly by CRIU, but that flag can be used
* only with all another flags set.
* Please, refer to
* https://github.com/torvalds/linux/blob/ce522ba9/kernel/rseq.c#L192
*/
#ifdef NORESTART
ignore_abort = false;
rseq_ptr->flags = RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT | RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL |
RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE;
#endif
task_waiter_init(&waiter);
if (pthread_create(&thread, NULL, thread_routine, NULL)) {
fail("pthread_create");
exit(EXIT_FAILURE);
}
task_waiter_wait4(&waiter, 1);
test_daemon();
task_waiter_complete(&waiter, 2);
while (test_go()) {
cpu = RSEQ_ACCESS_ONCE(rseq_ptr->cpu_id_start);
ret = rseq_addv(&cpu_data[cpu], 2, cpu, ignore_abort, "task");
if (ret)
break;
}
check_thread();
if (pthread_join(thread, NULL)) {
fail("pthread_join");
exit(EXIT_FAILURE);
}
if (ret || thread_ret)
fail();
else
pass();
return 0;
}
#else /* #if defined(__x86_64__) */
int main(int argc, char *argv[])
{
test_init(argc, argv);
skip("Unsupported arch");
test_daemon();
test_waitsig();
pass();
return 0;
}
#endif /* #if defined(__x86_64__) */
| 7,074 | 21.970779 | 98 |
c
|
criu
|
criu-master/test/zdtm/transition/socket_loop00.c
|
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include "zdtmtst.h"
const char *test_doc = "Multi-process socket loop";
const char *test_author = "Pavel Emelianov <[email protected]>";
#define PROCS_DEF 4
#define PROCS_MAX 64
unsigned int num_procs = PROCS_DEF;
TEST_OPTION(num_procs, uint,
"# processes to create "
"(default " __stringify(PROCS_DEF) ", max " __stringify(PROCS_MAX) ")",
0);
volatile sig_atomic_t num_exited = 0;
void inc_num_exited(int signo)
{
num_exited++;
}
int main(int argc, char **argv)
{
int ret = 0;
pid_t pid;
int i;
uint8_t buf[0x100000];
int socks[PROCS_MAX * 2];
int in, out;
test_init(argc, argv);
if (num_procs > PROCS_MAX) {
pr_err("%d processes is too many: max = %d\n", num_procs, PROCS_MAX);
exit(1);
}
for (i = 0; i < num_procs; i++)
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, socks + i * 2)) {
pr_perror("can't create sockets");
exit(1);
}
if (signal(SIGCHLD, inc_num_exited) == SIG_ERR) {
pr_perror("can't set SIGCHLD handler");
exit(1);
}
for (i = 1; i < num_procs; i++) { /* i = 0 - parent */
pid = test_fork();
if (pid < 0) {
pr_perror("Can't fork");
kill(0, SIGKILL);
exit(1);
}
if (pid == 0) {
int j;
in = i * 2;
out = in - 1;
for (j = 0; j < num_procs * 2; j++)
if (j != in && j != out)
close(socks[j]);
signal(SIGPIPE, SIG_IGN);
if (pipe_in2out(socks[in], socks[out], buf, sizeof(buf)) < 0)
/* pass errno as exit code to the parent */
if (test_go() /* signal NOT delivered */ ||
(errno != EINTR && errno != EPIPE && errno != ECONNRESET))
ret = errno;
test_waitsig(); /* even if failed, wait for migration to complete */
close(socks[in]);
close(socks[out]);
exit(ret);
}
}
for (i = 1; i < num_procs * 2 - 1; i++)
close(socks[i]);
in = socks[0];
out = socks[num_procs * 2 - 1];
/* don't block on writing, _do_ block on reading */
if (set_nonblock(out, 1) < 0) {
pr_perror("setting O_NONBLOCK failed");
exit(1);
}
if (num_exited) {
pr_err("Some children died unexpectedly\n");
kill(0, SIGKILL);
exit(1);
}
test_daemon();
while (test_go()) {
int len, rlen = 0, wlen;
uint8_t rbuf[sizeof(buf)], *p;
datagen(buf, sizeof(buf), NULL);
wlen = write(out, buf, sizeof(buf));
if (wlen < 0) {
if (errno == EINTR)
continue;
else {
fail("write failed");
ret = 1;
break;
}
}
for (p = rbuf, len = wlen; len > 0; p += rlen, len -= rlen) {
rlen = read(in, p, len);
if (rlen <= 0)
break;
}
if (rlen < 0 && errno == EINTR)
continue;
if (len > 0) {
fail("read failed");
ret = 1;
break;
}
if (memcmp(buf, rbuf, wlen)) {
fail("data mismatch");
ret = 1;
break;
}
}
test_waitsig(); /* even if failed, wait for migration to complete */
/* We expect that write(2) in child may return error only after signal
* has been received. Thus, send signal before closing parent fds.
*/
if (kill(0, SIGTERM)) {
fail("failed to send SIGTERM to my process group");
goto out; /* shouldn't wait() in this case */
}
if (close(out))
fail("Failed to close parent fd 'out'");
/* If last child in the chain (from whom we read data) receives signal
* after parent has finished reading but before calling write(2), this
* child can block forever. To avoid this, close 'in' fd.
*/
if (close(in))
fail("failed to close parent fd 'in'");
for (i = 1; i < num_procs; i++) { /* i = 0 - parent */
int chret;
if (wait(&chret) < 0) {
fail("can't wait for a child");
ret = 1;
continue;
}
chret = WEXITSTATUS(chret);
if (chret) {
fail("child %d exited with non-zero code %d (%s)", i, chret, strerror(chret));
ret = 1;
continue;
}
}
if (!ret)
pass();
out:
return 0;
}
| 3,937 | 20.172043 | 81 |
c
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/Myhal_Simulator/nav_noetic_ws/src/jackal_velodyne/src/pcl_filter_nodelet.h
|
#pragma once
#include <boost/thread/mutex.hpp>
#include <message_filters/subscriber.h>
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <string>
#include <tf2_ros/buffer.h>
#include <tf2_ros/message_filter.h>
#include <tf2_ros/transform_listener.h>
#include <vector>
namespace jackal_velodyne
{
typedef tf2_ros::MessageFilter<sensor_msgs::PointCloud2> MessageFilter;
/**
* Class to process incoming pointclouds into laserscans. Some initial code was pulled from the defunct turtlebot
* jackal_velodyne implementation.
*/
class PCLFilterNodelet : public nodelet::Nodelet
{
public:
PCLFilterNodelet();
private:
virtual void onInit();
void cloudCb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg);
void failureCb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg,
tf2_ros::filter_failure_reasons::FilterFailureReason reason);
void connectCb();
void disconnectCb();
ros::NodeHandle nh_, private_nh_;
ros::Publisher pub_;
boost::mutex connect_mutex_;
boost::shared_ptr<tf2_ros::Buffer> tf2_;
boost::shared_ptr<tf2_ros::TransformListener> tf2_listener_;
message_filters::Subscriber<sensor_msgs::PointCloud2> sub_;
boost::shared_ptr<MessageFilter> message_filter_;
// ROS Parameters
unsigned int input_queue_size_;
std::string target_frame_;
double tolerance_;
double min_height_, max_height_, angle_min_, angle_max_, angle_increment_, scan_time_, range_min_, range_max_;
bool use_inf_;
double inf_epsilon_;
std::vector<int> catagories;
bool filter_status = true;
};
} // namespace jackal_velodyne
| 1,614 | 25.916667 | 112 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/Myhal_Simulator/simu_melodic_ws/src/jackal_velodyne/src/pcl_filter_nodelet.h
|
#pragma once
#include <boost/thread/mutex.hpp>
#include <message_filters/subscriber.h>
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <string>
#include <tf2_ros/buffer.h>
#include <tf2_ros/message_filter.h>
#include <tf2_ros/transform_listener.h>
#include <vector>
namespace jackal_velodyne
{
typedef tf2_ros::MessageFilter<sensor_msgs::PointCloud2> MessageFilter;
/**
* Class to process incoming pointclouds into laserscans. Some initial code was pulled from the defunct turtlebot
* jackal_velodyne implementation.
*/
class PCLFilterNodelet : public nodelet::Nodelet
{
public:
PCLFilterNodelet();
private:
virtual void onInit();
void cloudCb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg);
void failureCb(const sensor_msgs::PointCloud2ConstPtr& cloud_msg,
tf2_ros::filter_failure_reasons::FilterFailureReason reason);
void connectCb();
void disconnectCb();
ros::NodeHandle nh_, private_nh_;
ros::Publisher pub_;
boost::mutex connect_mutex_;
boost::shared_ptr<tf2_ros::Buffer> tf2_;
boost::shared_ptr<tf2_ros::TransformListener> tf2_listener_;
message_filters::Subscriber<sensor_msgs::PointCloud2> sub_;
boost::shared_ptr<MessageFilter> message_filter_;
// ROS Parameters
unsigned int input_queue_size_;
std::string target_frame_;
double tolerance_;
double min_height_, max_height_, angle_min_, angle_max_, angle_increment_, scan_time_, range_min_, range_max_;
bool use_inf_;
double inf_epsilon_;
std::vector<int> catagories;
bool filter_status = true;
};
} // namespace jackal_velodyne
| 1,614 | 25.916667 | 112 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Cholesky/LLT_LAPACKE.h
|
/*
Copyright (c) 2011, Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************
* Content : Eigen bindings to LAPACKe
* LLt decomposition based on LAPACKE_?potrf function.
********************************************************************************
*/
#ifndef EIGEN_LLT_LAPACKE_H
#define EIGEN_LLT_LAPACKE_H
namespace Eigen {
namespace internal {
template<typename Scalar> struct lapacke_llt;
#define EIGEN_LAPACKE_LLT(EIGTYPE, BLASTYPE, LAPACKE_PREFIX) \
template<> struct lapacke_llt<EIGTYPE> \
{ \
template<typename MatrixType> \
static inline Index potrf(MatrixType& m, char uplo) \
{ \
lapack_int matrix_order; \
lapack_int size, lda, info, StorageOrder; \
EIGTYPE* a; \
eigen_assert(m.rows()==m.cols()); \
/* Set up parameters for ?potrf */ \
size = convert_index<lapack_int>(m.rows()); \
StorageOrder = MatrixType::Flags&RowMajorBit?RowMajor:ColMajor; \
matrix_order = StorageOrder==RowMajor ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \
a = &(m.coeffRef(0,0)); \
lda = convert_index<lapack_int>(m.outerStride()); \
\
info = LAPACKE_##LAPACKE_PREFIX##potrf( matrix_order, uplo, size, (BLASTYPE*)a, lda ); \
info = (info==0) ? -1 : info>0 ? info-1 : size; \
return info; \
} \
}; \
template<> struct llt_inplace<EIGTYPE, Lower> \
{ \
template<typename MatrixType> \
static Index blocked(MatrixType& m) \
{ \
return lapacke_llt<EIGTYPE>::potrf(m, 'L'); \
} \
template<typename MatrixType, typename VectorType> \
static Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \
{ return Eigen::internal::llt_rank_update_lower(mat, vec, sigma); } \
}; \
template<> struct llt_inplace<EIGTYPE, Upper> \
{ \
template<typename MatrixType> \
static Index blocked(MatrixType& m) \
{ \
return lapacke_llt<EIGTYPE>::potrf(m, 'U'); \
} \
template<typename MatrixType, typename VectorType> \
static Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \
{ \
Transpose<MatrixType> matt(mat); \
return llt_inplace<EIGTYPE, Lower>::rankUpdate(matt, vec.conjugate(), sigma); \
} \
};
EIGEN_LAPACKE_LLT(double, double, d)
EIGEN_LAPACKE_LLT(float, float, s)
EIGEN_LAPACKE_LLT(dcomplex, lapack_complex_double, z)
EIGEN_LAPACKE_LLT(scomplex, lapack_complex_float, c)
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_LLT_LAPACKE_H
| 3,974 | 38.75 | 113 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/ArrayBase.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAYBASE_H
#define EIGEN_ARRAYBASE_H
namespace Eigen {
template<typename ExpressionType> class MatrixWrapper;
/** \class ArrayBase
* \ingroup Core_Module
*
* \brief Base class for all 1D and 2D array, and related expressions
*
* An array is similar to a dense vector or matrix. While matrices are mathematical
* objects with well defined linear algebra operators, an array is just a collection
* of scalar values arranged in a one or two dimensionnal fashion. As the main consequence,
* all operations applied to an array are performed coefficient wise. Furthermore,
* arrays support scalar math functions of the c++ standard library (e.g., std::sin(x)), and convenient
* constructors allowing to easily write generic code working for both scalar values
* and arrays.
*
* This class is the base that is inherited by all array expression types.
*
* \tparam Derived is the derived type, e.g., an array or an expression type.
*
* This class can be extended with the help of the plugin mechanism described on the page
* \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAYBASE_PLUGIN.
*
* \sa class MatrixBase, \ref TopicClassHierarchy
*/
template<typename Derived> class ArrayBase
: public DenseBase<Derived>
{
public:
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** The base class for a given storage type. */
typedef ArrayBase StorageBaseType;
typedef ArrayBase Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl;
typedef typename internal::traits<Derived>::StorageKind StorageKind;
typedef typename internal::traits<Derived>::Scalar Scalar;
typedef typename internal::packet_traits<Scalar>::type PacketScalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef DenseBase<Derived> Base;
using Base::RowsAtCompileTime;
using Base::ColsAtCompileTime;
using Base::SizeAtCompileTime;
using Base::MaxRowsAtCompileTime;
using Base::MaxColsAtCompileTime;
using Base::MaxSizeAtCompileTime;
using Base::IsVectorAtCompileTime;
using Base::Flags;
using Base::derived;
using Base::const_cast_derived;
using Base::rows;
using Base::cols;
using Base::size;
using Base::coeff;
using Base::coeffRef;
using Base::lazyAssign;
using Base::operator=;
using Base::operator+=;
using Base::operator-=;
using Base::operator*=;
using Base::operator/=;
typedef typename Base::CoeffReturnType CoeffReturnType;
#endif // not EIGEN_PARSED_BY_DOXYGEN
#ifndef EIGEN_PARSED_BY_DOXYGEN
typedef typename Base::PlainObject PlainObject;
/** \internal Represents a matrix with all coefficients equal to one another*/
typedef CwiseNullaryOp<internal::scalar_constant_op<Scalar>,PlainObject> ConstantReturnType;
#endif // not EIGEN_PARSED_BY_DOXYGEN
#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::ArrayBase
#define EIGEN_DOC_UNARY_ADDONS(X,Y)
# include "../plugins/CommonCwiseUnaryOps.h"
# include "../plugins/MatrixCwiseUnaryOps.h"
# include "../plugins/ArrayCwiseUnaryOps.h"
# include "../plugins/CommonCwiseBinaryOps.h"
# include "../plugins/MatrixCwiseBinaryOps.h"
# include "../plugins/ArrayCwiseBinaryOps.h"
# ifdef EIGEN_ARRAYBASE_PLUGIN
# include EIGEN_ARRAYBASE_PLUGIN
# endif
#undef EIGEN_CURRENT_STORAGE_BASE_CLASS
#undef EIGEN_DOC_UNARY_ADDONS
/** Special case of the template operator=, in order to prevent the compiler
* from generating a default operator= (issue hit with g++ 4.1)
*/
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator=(const ArrayBase& other)
{
internal::call_assignment(derived(), other.derived());
return derived();
}
/** Set all the entries to \a value.
* \sa DenseBase::setConstant(), DenseBase::fill() */
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator=(const Scalar &value)
{ Base::setConstant(value); return derived(); }
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator+=(const Scalar& scalar);
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator-=(const Scalar& scalar);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator+=(const ArrayBase<OtherDerived>& other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator-=(const ArrayBase<OtherDerived>& other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator*=(const ArrayBase<OtherDerived>& other);
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Derived& operator/=(const ArrayBase<OtherDerived>& other);
public:
EIGEN_DEVICE_FUNC
ArrayBase<Derived>& array() { return *this; }
EIGEN_DEVICE_FUNC
const ArrayBase<Derived>& array() const { return *this; }
/** \returns an \link Eigen::MatrixBase Matrix \endlink expression of this array
* \sa MatrixBase::array() */
EIGEN_DEVICE_FUNC
MatrixWrapper<Derived> matrix() { return MatrixWrapper<Derived>(derived()); }
EIGEN_DEVICE_FUNC
const MatrixWrapper<const Derived> matrix() const { return MatrixWrapper<const Derived>(derived()); }
// template<typename Dest>
// inline void evalTo(Dest& dst) const { dst = matrix(); }
protected:
EIGEN_DEVICE_FUNC
ArrayBase() : Base() {}
private:
explicit ArrayBase(Index);
ArrayBase(Index,Index);
template<typename OtherDerived> explicit ArrayBase(const ArrayBase<OtherDerived>&);
protected:
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator+=(const MatrixBase<OtherDerived>& )
{EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
// mixing arrays and matrices is not legal
template<typename OtherDerived> Derived& operator-=(const MatrixBase<OtherDerived>& )
{EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;}
};
/** replaces \c *this by \c *this - \a other.
*
* \returns a reference to \c *this
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived &
ArrayBase<Derived>::operator-=(const ArrayBase<OtherDerived> &other)
{
call_assignment(derived(), other.derived(), internal::sub_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
/** replaces \c *this by \c *this + \a other.
*
* \returns a reference to \c *this
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived &
ArrayBase<Derived>::operator+=(const ArrayBase<OtherDerived>& other)
{
call_assignment(derived(), other.derived(), internal::add_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
/** replaces \c *this by \c *this * \a other coefficient wise.
*
* \returns a reference to \c *this
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived &
ArrayBase<Derived>::operator*=(const ArrayBase<OtherDerived>& other)
{
call_assignment(derived(), other.derived(), internal::mul_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
/** replaces \c *this by \c *this / \a other coefficient wise.
*
* \returns a reference to \c *this
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived &
ArrayBase<Derived>::operator/=(const ArrayBase<OtherDerived>& other)
{
call_assignment(derived(), other.derived(), internal::div_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
} // end namespace Eigen
#endif // EIGEN_ARRAYBASE_H
| 8,179 | 35.035242 | 134 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/ArrayWrapper.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARRAYWRAPPER_H
#define EIGEN_ARRAYWRAPPER_H
namespace Eigen {
/** \class ArrayWrapper
* \ingroup Core_Module
*
* \brief Expression of a mathematical vector or matrix as an array object
*
* This class is the return type of MatrixBase::array(), and most of the time
* this is the only way it is use.
*
* \sa MatrixBase::array(), class MatrixWrapper
*/
namespace internal {
template<typename ExpressionType>
struct traits<ArrayWrapper<ExpressionType> >
: public traits<typename remove_all<typename ExpressionType::Nested>::type >
{
typedef ArrayXpr XprKind;
// Let's remove NestByRefBit
enum {
Flags0 = traits<typename remove_all<typename ExpressionType::Nested>::type >::Flags,
LvalueBitFlag = is_lvalue<ExpressionType>::value ? LvalueBit : 0,
Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag
};
};
}
template<typename ExpressionType>
class ArrayWrapper : public ArrayBase<ArrayWrapper<ExpressionType> >
{
public:
typedef ArrayBase<ArrayWrapper> Base;
EIGEN_DENSE_PUBLIC_INTERFACE(ArrayWrapper)
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ArrayWrapper)
typedef typename internal::remove_all<ExpressionType>::type NestedExpression;
typedef typename internal::conditional<
internal::is_lvalue<ExpressionType>::value,
Scalar,
const Scalar
>::type ScalarWithConstIfNotLvalue;
typedef typename internal::ref_selector<ExpressionType>::non_const_type NestedExpressionType;
using Base::coeffRef;
EIGEN_DEVICE_FUNC
explicit EIGEN_STRONG_INLINE ArrayWrapper(ExpressionType& matrix) : m_expression(matrix) {}
EIGEN_DEVICE_FUNC
inline Index rows() const { return m_expression.rows(); }
EIGEN_DEVICE_FUNC
inline Index cols() const { return m_expression.cols(); }
EIGEN_DEVICE_FUNC
inline Index outerStride() const { return m_expression.outerStride(); }
EIGEN_DEVICE_FUNC
inline Index innerStride() const { return m_expression.innerStride(); }
EIGEN_DEVICE_FUNC
inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); }
EIGEN_DEVICE_FUNC
inline const Scalar* data() const { return m_expression.data(); }
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index rowId, Index colId) const
{
return m_expression.coeffRef(rowId, colId);
}
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index index) const
{
return m_expression.coeffRef(index);
}
template<typename Dest>
EIGEN_DEVICE_FUNC
inline void evalTo(Dest& dst) const { dst = m_expression; }
const typename internal::remove_all<NestedExpressionType>::type&
EIGEN_DEVICE_FUNC
nestedExpression() const
{
return m_expression;
}
/** Forwards the resizing request to the nested expression
* \sa DenseBase::resize(Index) */
EIGEN_DEVICE_FUNC
void resize(Index newSize) { m_expression.resize(newSize); }
/** Forwards the resizing request to the nested expression
* \sa DenseBase::resize(Index,Index)*/
EIGEN_DEVICE_FUNC
void resize(Index rows, Index cols) { m_expression.resize(rows,cols); }
protected:
NestedExpressionType m_expression;
};
/** \class MatrixWrapper
* \ingroup Core_Module
*
* \brief Expression of an array as a mathematical vector or matrix
*
* This class is the return type of ArrayBase::matrix(), and most of the time
* this is the only way it is use.
*
* \sa MatrixBase::matrix(), class ArrayWrapper
*/
namespace internal {
template<typename ExpressionType>
struct traits<MatrixWrapper<ExpressionType> >
: public traits<typename remove_all<typename ExpressionType::Nested>::type >
{
typedef MatrixXpr XprKind;
// Let's remove NestByRefBit
enum {
Flags0 = traits<typename remove_all<typename ExpressionType::Nested>::type >::Flags,
LvalueBitFlag = is_lvalue<ExpressionType>::value ? LvalueBit : 0,
Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag
};
};
}
template<typename ExpressionType>
class MatrixWrapper : public MatrixBase<MatrixWrapper<ExpressionType> >
{
public:
typedef MatrixBase<MatrixWrapper<ExpressionType> > Base;
EIGEN_DENSE_PUBLIC_INTERFACE(MatrixWrapper)
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(MatrixWrapper)
typedef typename internal::remove_all<ExpressionType>::type NestedExpression;
typedef typename internal::conditional<
internal::is_lvalue<ExpressionType>::value,
Scalar,
const Scalar
>::type ScalarWithConstIfNotLvalue;
typedef typename internal::ref_selector<ExpressionType>::non_const_type NestedExpressionType;
using Base::coeffRef;
EIGEN_DEVICE_FUNC
explicit inline MatrixWrapper(ExpressionType& matrix) : m_expression(matrix) {}
EIGEN_DEVICE_FUNC
inline Index rows() const { return m_expression.rows(); }
EIGEN_DEVICE_FUNC
inline Index cols() const { return m_expression.cols(); }
EIGEN_DEVICE_FUNC
inline Index outerStride() const { return m_expression.outerStride(); }
EIGEN_DEVICE_FUNC
inline Index innerStride() const { return m_expression.innerStride(); }
EIGEN_DEVICE_FUNC
inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); }
EIGEN_DEVICE_FUNC
inline const Scalar* data() const { return m_expression.data(); }
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index rowId, Index colId) const
{
return m_expression.derived().coeffRef(rowId, colId);
}
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index index) const
{
return m_expression.coeffRef(index);
}
EIGEN_DEVICE_FUNC
const typename internal::remove_all<NestedExpressionType>::type&
nestedExpression() const
{
return m_expression;
}
/** Forwards the resizing request to the nested expression
* \sa DenseBase::resize(Index) */
EIGEN_DEVICE_FUNC
void resize(Index newSize) { m_expression.resize(newSize); }
/** Forwards the resizing request to the nested expression
* \sa DenseBase::resize(Index,Index)*/
EIGEN_DEVICE_FUNC
void resize(Index rows, Index cols) { m_expression.resize(rows,cols); }
protected:
NestedExpressionType m_expression;
};
} // end namespace Eigen
#endif // EIGEN_ARRAYWRAPPER_H
| 6,775 | 31.266667 | 97 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/BooleanRedux.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ALLANDANY_H
#define EIGEN_ALLANDANY_H
namespace Eigen {
namespace internal {
template<typename Derived, int UnrollCount>
struct all_unroller
{
typedef typename Derived::ExpressionTraits Traits;
enum {
col = (UnrollCount-1) / Traits::RowsAtCompileTime,
row = (UnrollCount-1) % Traits::RowsAtCompileTime
};
static inline bool run(const Derived &mat)
{
return all_unroller<Derived, UnrollCount-1>::run(mat) && mat.coeff(row, col);
}
};
template<typename Derived>
struct all_unroller<Derived, 0>
{
static inline bool run(const Derived &/*mat*/) { return true; }
};
template<typename Derived>
struct all_unroller<Derived, Dynamic>
{
static inline bool run(const Derived &) { return false; }
};
template<typename Derived, int UnrollCount>
struct any_unroller
{
typedef typename Derived::ExpressionTraits Traits;
enum {
col = (UnrollCount-1) / Traits::RowsAtCompileTime,
row = (UnrollCount-1) % Traits::RowsAtCompileTime
};
static inline bool run(const Derived &mat)
{
return any_unroller<Derived, UnrollCount-1>::run(mat) || mat.coeff(row, col);
}
};
template<typename Derived>
struct any_unroller<Derived, 0>
{
static inline bool run(const Derived & /*mat*/) { return false; }
};
template<typename Derived>
struct any_unroller<Derived, Dynamic>
{
static inline bool run(const Derived &) { return false; }
};
} // end namespace internal
/** \returns true if all coefficients are true
*
* Example: \include MatrixBase_all.cpp
* Output: \verbinclude MatrixBase_all.out
*
* \sa any(), Cwise::operator<()
*/
template<typename Derived>
inline bool DenseBase<Derived>::all() const
{
typedef internal::evaluator<Derived> Evaluator;
enum {
unroll = SizeAtCompileTime != Dynamic
&& SizeAtCompileTime * (Evaluator::CoeffReadCost + NumTraits<Scalar>::AddCost) <= EIGEN_UNROLLING_LIMIT
};
Evaluator evaluator(derived());
if(unroll)
return internal::all_unroller<Evaluator, unroll ? int(SizeAtCompileTime) : Dynamic>::run(evaluator);
else
{
for(Index j = 0; j < cols(); ++j)
for(Index i = 0; i < rows(); ++i)
if (!evaluator.coeff(i, j)) return false;
return true;
}
}
/** \returns true if at least one coefficient is true
*
* \sa all()
*/
template<typename Derived>
inline bool DenseBase<Derived>::any() const
{
typedef internal::evaluator<Derived> Evaluator;
enum {
unroll = SizeAtCompileTime != Dynamic
&& SizeAtCompileTime * (Evaluator::CoeffReadCost + NumTraits<Scalar>::AddCost) <= EIGEN_UNROLLING_LIMIT
};
Evaluator evaluator(derived());
if(unroll)
return internal::any_unroller<Evaluator, unroll ? int(SizeAtCompileTime) : Dynamic>::run(evaluator);
else
{
for(Index j = 0; j < cols(); ++j)
for(Index i = 0; i < rows(); ++i)
if (evaluator.coeff(i, j)) return true;
return false;
}
}
/** \returns the number of coefficients which evaluate to true
*
* \sa all(), any()
*/
template<typename Derived>
inline Eigen::Index DenseBase<Derived>::count() const
{
return derived().template cast<bool>().template cast<Index>().sum();
}
/** \returns true is \c *this contains at least one Not A Number (NaN).
*
* \sa allFinite()
*/
template<typename Derived>
inline bool DenseBase<Derived>::hasNaN() const
{
#if EIGEN_COMP_MSVC || (defined __FAST_MATH__)
return derived().array().isNaN().any();
#else
return !((derived().array()==derived().array()).all());
#endif
}
/** \returns true if \c *this contains only finite numbers, i.e., no NaN and no +/-INF values.
*
* \sa hasNaN()
*/
template<typename Derived>
inline bool DenseBase<Derived>::allFinite() const
{
#if EIGEN_COMP_MSVC || (defined __FAST_MATH__)
return derived().array().isFinite().all();
#else
return !((derived()-derived()).hasNaN());
#endif
}
} // end namespace Eigen
#endif // EIGEN_ALLANDANY_H
| 4,249 | 24.757576 | 113 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/CommaInitializer.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COMMAINITIALIZER_H
#define EIGEN_COMMAINITIALIZER_H
namespace Eigen {
/** \class CommaInitializer
* \ingroup Core_Module
*
* \brief Helper class used by the comma initializer operator
*
* This class is internally used to implement the comma initializer feature. It is
* the return type of MatrixBase::operator<<, and most of the time this is the only
* way it is used.
*
* \sa \blank \ref MatrixBaseCommaInitRef "MatrixBase::operator<<", CommaInitializer::finished()
*/
template<typename XprType>
struct CommaInitializer
{
typedef typename XprType::Scalar Scalar;
EIGEN_DEVICE_FUNC
inline CommaInitializer(XprType& xpr, const Scalar& s)
: m_xpr(xpr), m_row(0), m_col(1), m_currentBlockRows(1)
{
m_xpr.coeffRef(0,0) = s;
}
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
inline CommaInitializer(XprType& xpr, const DenseBase<OtherDerived>& other)
: m_xpr(xpr), m_row(0), m_col(other.cols()), m_currentBlockRows(other.rows())
{
m_xpr.block(0, 0, other.rows(), other.cols()) = other;
}
/* Copy/Move constructor which transfers ownership. This is crucial in
* absence of return value optimization to avoid assertions during destruction. */
// FIXME in C++11 mode this could be replaced by a proper RValue constructor
EIGEN_DEVICE_FUNC
inline CommaInitializer(const CommaInitializer& o)
: m_xpr(o.m_xpr), m_row(o.m_row), m_col(o.m_col), m_currentBlockRows(o.m_currentBlockRows) {
// Mark original object as finished. In absence of R-value references we need to const_cast:
const_cast<CommaInitializer&>(o).m_row = m_xpr.rows();
const_cast<CommaInitializer&>(o).m_col = m_xpr.cols();
const_cast<CommaInitializer&>(o).m_currentBlockRows = 0;
}
/* inserts a scalar value in the target matrix */
EIGEN_DEVICE_FUNC
CommaInitializer& operator,(const Scalar& s)
{
if (m_col==m_xpr.cols())
{
m_row+=m_currentBlockRows;
m_col = 0;
m_currentBlockRows = 1;
eigen_assert(m_row<m_xpr.rows()
&& "Too many rows passed to comma initializer (operator<<)");
}
eigen_assert(m_col<m_xpr.cols()
&& "Too many coefficients passed to comma initializer (operator<<)");
eigen_assert(m_currentBlockRows==1);
m_xpr.coeffRef(m_row, m_col++) = s;
return *this;
}
/* inserts a matrix expression in the target matrix */
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
CommaInitializer& operator,(const DenseBase<OtherDerived>& other)
{
if (m_col==m_xpr.cols() && (other.cols()!=0 || other.rows()!=m_currentBlockRows))
{
m_row+=m_currentBlockRows;
m_col = 0;
m_currentBlockRows = other.rows();
eigen_assert(m_row+m_currentBlockRows<=m_xpr.rows()
&& "Too many rows passed to comma initializer (operator<<)");
}
eigen_assert((m_col + other.cols() <= m_xpr.cols())
&& "Too many coefficients passed to comma initializer (operator<<)");
eigen_assert(m_currentBlockRows==other.rows());
m_xpr.template block<OtherDerived::RowsAtCompileTime, OtherDerived::ColsAtCompileTime>
(m_row, m_col, other.rows(), other.cols()) = other;
m_col += other.cols();
return *this;
}
EIGEN_DEVICE_FUNC
inline ~CommaInitializer()
#if defined VERIFY_RAISES_ASSERT && (!defined EIGEN_NO_ASSERTION_CHECKING) && defined EIGEN_EXCEPTIONS
EIGEN_EXCEPTION_SPEC(Eigen::eigen_assert_exception)
#endif
{
finished();
}
/** \returns the built matrix once all its coefficients have been set.
* Calling finished is 100% optional. Its purpose is to write expressions
* like this:
* \code
* quaternion.fromRotationMatrix((Matrix3f() << axis0, axis1, axis2).finished());
* \endcode
*/
EIGEN_DEVICE_FUNC
inline XprType& finished() {
eigen_assert(((m_row+m_currentBlockRows) == m_xpr.rows() || m_xpr.cols() == 0)
&& m_col == m_xpr.cols()
&& "Too few coefficients passed to comma initializer (operator<<)");
return m_xpr;
}
XprType& m_xpr; // target expression
Index m_row; // current row id
Index m_col; // current col id
Index m_currentBlockRows; // current block height
};
/** \anchor MatrixBaseCommaInitRef
* Convenient operator to set the coefficients of a matrix.
*
* The coefficients must be provided in a row major order and exactly match
* the size of the matrix. Otherwise an assertion is raised.
*
* Example: \include MatrixBase_set.cpp
* Output: \verbinclude MatrixBase_set.out
*
* \note According the c++ standard, the argument expressions of this comma initializer are evaluated in arbitrary order.
*
* \sa CommaInitializer::finished(), class CommaInitializer
*/
template<typename Derived>
inline CommaInitializer<Derived> DenseBase<Derived>::operator<< (const Scalar& s)
{
return CommaInitializer<Derived>(*static_cast<Derived*>(this), s);
}
/** \sa operator<<(const Scalar&) */
template<typename Derived>
template<typename OtherDerived>
inline CommaInitializer<Derived>
DenseBase<Derived>::operator<<(const DenseBase<OtherDerived>& other)
{
return CommaInitializer<Derived>(*static_cast<Derived *>(this), other);
}
} // end namespace Eigen
#endif // EIGEN_COMMAINITIALIZER_H
| 5,689 | 34.341615 | 122 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/ConditionEstimator.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Rasmus Munk Larsen ([email protected])
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CONDITIONESTIMATOR_H
#define EIGEN_CONDITIONESTIMATOR_H
namespace Eigen {
namespace internal {
template <typename Vector, typename RealVector, bool IsComplex>
struct rcond_compute_sign {
static inline Vector run(const Vector& v) {
const RealVector v_abs = v.cwiseAbs();
return (v_abs.array() == static_cast<typename Vector::RealScalar>(0))
.select(Vector::Ones(v.size()), v.cwiseQuotient(v_abs));
}
};
// Partial specialization to avoid elementwise division for real vectors.
template <typename Vector>
struct rcond_compute_sign<Vector, Vector, false> {
static inline Vector run(const Vector& v) {
return (v.array() < static_cast<typename Vector::RealScalar>(0))
.select(-Vector::Ones(v.size()), Vector::Ones(v.size()));
}
};
/**
* \returns an estimate of ||inv(matrix)||_1 given a decomposition of
* \a matrix that implements .solve() and .adjoint().solve() methods.
*
* This function implements Algorithms 4.1 and 5.1 from
* http://www.maths.manchester.ac.uk/~higham/narep/narep135.pdf
* which also forms the basis for the condition number estimators in
* LAPACK. Since at most 10 calls to the solve method of dec are
* performed, the total cost is O(dims^2), as opposed to O(dims^3)
* needed to compute the inverse matrix explicitly.
*
* The most common usage is in estimating the condition number
* ||matrix||_1 * ||inv(matrix)||_1. The first term ||matrix||_1 can be
* computed directly in O(n^2) operations.
*
* Supports the following decompositions: FullPivLU, PartialPivLU, LDLT, and
* LLT.
*
* \sa FullPivLU, PartialPivLU, LDLT, LLT.
*/
template <typename Decomposition>
typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomposition& dec)
{
typedef typename Decomposition::MatrixType MatrixType;
typedef typename Decomposition::Scalar Scalar;
typedef typename Decomposition::RealScalar RealScalar;
typedef typename internal::plain_col_type<MatrixType>::type Vector;
typedef typename internal::plain_col_type<MatrixType, RealScalar>::type RealVector;
const bool is_complex = (NumTraits<Scalar>::IsComplex != 0);
eigen_assert(dec.rows() == dec.cols());
const Index n = dec.rows();
if (n == 0)
return 0;
// Disable Index to float conversion warning
#ifdef __INTEL_COMPILER
#pragma warning push
#pragma warning ( disable : 2259 )
#endif
Vector v = dec.solve(Vector::Ones(n) / Scalar(n));
#ifdef __INTEL_COMPILER
#pragma warning pop
#endif
// lower_bound is a lower bound on
// ||inv(matrix)||_1 = sup_v ||inv(matrix) v||_1 / ||v||_1
// and is the objective maximized by the ("super-") gradient ascent
// algorithm below.
RealScalar lower_bound = v.template lpNorm<1>();
if (n == 1)
return lower_bound;
// Gradient ascent algorithm follows: We know that the optimum is achieved at
// one of the simplices v = e_i, so in each iteration we follow a
// super-gradient to move towards the optimal one.
RealScalar old_lower_bound = lower_bound;
Vector sign_vector(n);
Vector old_sign_vector;
Index v_max_abs_index = -1;
Index old_v_max_abs_index = v_max_abs_index;
for (int k = 0; k < 4; ++k)
{
sign_vector = internal::rcond_compute_sign<Vector, RealVector, is_complex>::run(v);
if (k > 0 && !is_complex && sign_vector == old_sign_vector) {
// Break if the solution stagnated.
break;
}
// v_max_abs_index = argmax |real( inv(matrix)^T * sign_vector )|
v = dec.adjoint().solve(sign_vector);
v.real().cwiseAbs().maxCoeff(&v_max_abs_index);
if (v_max_abs_index == old_v_max_abs_index) {
// Break if the solution stagnated.
break;
}
// Move to the new simplex e_j, where j = v_max_abs_index.
v = dec.solve(Vector::Unit(n, v_max_abs_index)); // v = inv(matrix) * e_j.
lower_bound = v.template lpNorm<1>();
if (lower_bound <= old_lower_bound) {
// Break if the gradient step did not increase the lower_bound.
break;
}
if (!is_complex) {
old_sign_vector = sign_vector;
}
old_v_max_abs_index = v_max_abs_index;
old_lower_bound = lower_bound;
}
// The following calculates an independent estimate of ||matrix||_1 by
// multiplying matrix by a vector with entries of slowly increasing
// magnitude and alternating sign:
// v_i = (-1)^{i} (1 + (i / (dim-1))), i = 0,...,dim-1.
// This improvement to Hager's algorithm above is due to Higham. It was
// added to make the algorithm more robust in certain corner cases where
// large elements in the matrix might otherwise escape detection due to
// exact cancellation (especially when op and op_adjoint correspond to a
// sequence of backsubstitutions and permutations), which could cause
// Hager's algorithm to vastly underestimate ||matrix||_1.
Scalar alternating_sign(RealScalar(1));
for (Index i = 0; i < n; ++i) {
// The static_cast is needed when Scalar is a complex and RealScalar implements expression templates
v[i] = alternating_sign * static_cast<RealScalar>(RealScalar(1) + (RealScalar(i) / (RealScalar(n - 1))));
alternating_sign = -alternating_sign;
}
v = dec.solve(v);
const RealScalar alternate_lower_bound = (2 * v.template lpNorm<1>()) / (3 * RealScalar(n));
return numext::maxi(lower_bound, alternate_lower_bound);
}
/** \brief Reciprocal condition number estimator.
*
* Computing a decomposition of a dense matrix takes O(n^3) operations, while
* this method estimates the condition number quickly and reliably in O(n^2)
* operations.
*
* \returns an estimate of the reciprocal condition number
* (1 / (||matrix||_1 * ||inv(matrix)||_1)) of matrix, given ||matrix||_1 and
* its decomposition. Supports the following decompositions: FullPivLU,
* PartialPivLU, LDLT, and LLT.
*
* \sa FullPivLU, PartialPivLU, LDLT, LLT.
*/
template <typename Decomposition>
typename Decomposition::RealScalar
rcond_estimate_helper(typename Decomposition::RealScalar matrix_norm, const Decomposition& dec)
{
typedef typename Decomposition::RealScalar RealScalar;
eigen_assert(dec.rows() == dec.cols());
if (dec.rows() == 0) return NumTraits<RealScalar>::infinity();
if (matrix_norm == RealScalar(0)) return RealScalar(0);
if (dec.rows() == 1) return RealScalar(1);
const RealScalar inverse_matrix_norm = rcond_invmatrix_L1_norm_estimate(dec);
return (inverse_matrix_norm == RealScalar(0) ? RealScalar(0)
: (RealScalar(1) / inverse_matrix_norm) / matrix_norm);
}
} // namespace internal
} // namespace Eigen
#endif
| 6,990 | 38.721591 | 109 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/CoreIterators.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_COREITERATORS_H
#define EIGEN_COREITERATORS_H
namespace Eigen {
/* This file contains the respective InnerIterator definition of the expressions defined in Eigen/Core
*/
namespace internal {
template<typename XprType, typename EvaluatorKind>
class inner_iterator_selector;
}
/** \class InnerIterator
* \brief An InnerIterator allows to loop over the element of any matrix expression.
*
* \warning To be used with care because an evaluator is constructed every time an InnerIterator iterator is constructed.
*
* TODO: add a usage example
*/
template<typename XprType>
class InnerIterator
{
protected:
typedef internal::inner_iterator_selector<XprType, typename internal::evaluator_traits<XprType>::Kind> IteratorType;
typedef internal::evaluator<XprType> EvaluatorType;
typedef typename internal::traits<XprType>::Scalar Scalar;
public:
/** Construct an iterator over the \a outerId -th row or column of \a xpr */
InnerIterator(const XprType &xpr, const Index &outerId)
: m_eval(xpr), m_iter(m_eval, outerId, xpr.innerSize())
{}
/// \returns the value of the current coefficient.
EIGEN_STRONG_INLINE Scalar value() const { return m_iter.value(); }
/** Increment the iterator \c *this to the next non-zero coefficient.
* Explicit zeros are not skipped over. To skip explicit zeros, see class SparseView
*/
EIGEN_STRONG_INLINE InnerIterator& operator++() { m_iter.operator++(); return *this; }
/// \returns the column or row index of the current coefficient.
EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); }
/// \returns the row index of the current coefficient.
EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); }
/// \returns the column index of the current coefficient.
EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); }
/// \returns \c true if the iterator \c *this still references a valid coefficient.
EIGEN_STRONG_INLINE operator bool() const { return m_iter; }
protected:
EvaluatorType m_eval;
IteratorType m_iter;
private:
// If you get here, then you're not using the right InnerIterator type, e.g.:
// SparseMatrix<double,RowMajor> A;
// SparseMatrix<double>::InnerIterator it(A,0);
template<typename T> InnerIterator(const EigenBase<T>&,Index outer);
};
namespace internal {
// Generic inner iterator implementation for dense objects
template<typename XprType>
class inner_iterator_selector<XprType, IndexBased>
{
protected:
typedef evaluator<XprType> EvaluatorType;
typedef typename traits<XprType>::Scalar Scalar;
enum { IsRowMajor = (XprType::Flags&RowMajorBit)==RowMajorBit };
public:
EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &innerSize)
: m_eval(eval), m_inner(0), m_outer(outerId), m_end(innerSize)
{}
EIGEN_STRONG_INLINE Scalar value() const
{
return (IsRowMajor) ? m_eval.coeff(m_outer, m_inner)
: m_eval.coeff(m_inner, m_outer);
}
EIGEN_STRONG_INLINE inner_iterator_selector& operator++() { m_inner++; return *this; }
EIGEN_STRONG_INLINE Index index() const { return m_inner; }
inline Index row() const { return IsRowMajor ? m_outer : index(); }
inline Index col() const { return IsRowMajor ? index() : m_outer; }
EIGEN_STRONG_INLINE operator bool() const { return m_inner < m_end && m_inner>=0; }
protected:
const EvaluatorType& m_eval;
Index m_inner;
const Index m_outer;
const Index m_end;
};
// For iterator-based evaluator, inner-iterator is already implemented as
// evaluator<>::InnerIterator
template<typename XprType>
class inner_iterator_selector<XprType, IteratorBased>
: public evaluator<XprType>::InnerIterator
{
protected:
typedef typename evaluator<XprType>::InnerIterator Base;
typedef evaluator<XprType> EvaluatorType;
public:
EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &/*innerSize*/)
: Base(eval, outerId)
{}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_COREITERATORS_H
| 4,525 | 34.359375 | 122 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/CwiseTernaryOp.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2014 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
// Copyright (C) 2016 Eugene Brevdo <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_CWISE_TERNARY_OP_H
#define EIGEN_CWISE_TERNARY_OP_H
namespace Eigen {
namespace internal {
template <typename TernaryOp, typename Arg1, typename Arg2, typename Arg3>
struct traits<CwiseTernaryOp<TernaryOp, Arg1, Arg2, Arg3> > {
// we must not inherit from traits<Arg1> since it has
// the potential to cause problems with MSVC
typedef typename remove_all<Arg1>::type Ancestor;
typedef typename traits<Ancestor>::XprKind XprKind;
enum {
RowsAtCompileTime = traits<Ancestor>::RowsAtCompileTime,
ColsAtCompileTime = traits<Ancestor>::ColsAtCompileTime,
MaxRowsAtCompileTime = traits<Ancestor>::MaxRowsAtCompileTime,
MaxColsAtCompileTime = traits<Ancestor>::MaxColsAtCompileTime
};
// even though we require Arg1, Arg2, and Arg3 to have the same scalar type
// (see CwiseTernaryOp constructor),
// we still want to handle the case when the result type is different.
typedef typename result_of<TernaryOp(
const typename Arg1::Scalar&, const typename Arg2::Scalar&,
const typename Arg3::Scalar&)>::type Scalar;
typedef typename internal::traits<Arg1>::StorageKind StorageKind;
typedef typename internal::traits<Arg1>::StorageIndex StorageIndex;
typedef typename Arg1::Nested Arg1Nested;
typedef typename Arg2::Nested Arg2Nested;
typedef typename Arg3::Nested Arg3Nested;
typedef typename remove_reference<Arg1Nested>::type _Arg1Nested;
typedef typename remove_reference<Arg2Nested>::type _Arg2Nested;
typedef typename remove_reference<Arg3Nested>::type _Arg3Nested;
enum { Flags = _Arg1Nested::Flags & RowMajorBit };
};
} // end namespace internal
template <typename TernaryOp, typename Arg1, typename Arg2, typename Arg3,
typename StorageKind>
class CwiseTernaryOpImpl;
/** \class CwiseTernaryOp
* \ingroup Core_Module
*
* \brief Generic expression where a coefficient-wise ternary operator is
* applied to two expressions
*
* \tparam TernaryOp template functor implementing the operator
* \tparam Arg1Type the type of the first argument
* \tparam Arg2Type the type of the second argument
* \tparam Arg3Type the type of the third argument
*
* This class represents an expression where a coefficient-wise ternary
* operator is applied to three expressions.
* It is the return type of ternary operators, by which we mean only those
* ternary operators where
* all three arguments are Eigen expressions.
* For example, the return type of betainc(matrix1, matrix2, matrix3) is a
* CwiseTernaryOp.
*
* Most of the time, this is the only way that it is used, so you typically
* don't have to name
* CwiseTernaryOp types explicitly.
*
* \sa MatrixBase::ternaryExpr(const MatrixBase<Argument2> &, const
* MatrixBase<Argument3> &, const CustomTernaryOp &) const, class CwiseBinaryOp,
* class CwiseUnaryOp, class CwiseNullaryOp
*/
template <typename TernaryOp, typename Arg1Type, typename Arg2Type,
typename Arg3Type>
class CwiseTernaryOp : public CwiseTernaryOpImpl<
TernaryOp, Arg1Type, Arg2Type, Arg3Type,
typename internal::traits<Arg1Type>::StorageKind>,
internal::no_assignment_operator
{
public:
typedef typename internal::remove_all<Arg1Type>::type Arg1;
typedef typename internal::remove_all<Arg2Type>::type Arg2;
typedef typename internal::remove_all<Arg3Type>::type Arg3;
typedef typename CwiseTernaryOpImpl<
TernaryOp, Arg1Type, Arg2Type, Arg3Type,
typename internal::traits<Arg1Type>::StorageKind>::Base Base;
EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseTernaryOp)
typedef typename internal::ref_selector<Arg1Type>::type Arg1Nested;
typedef typename internal::ref_selector<Arg2Type>::type Arg2Nested;
typedef typename internal::ref_selector<Arg3Type>::type Arg3Nested;
typedef typename internal::remove_reference<Arg1Nested>::type _Arg1Nested;
typedef typename internal::remove_reference<Arg2Nested>::type _Arg2Nested;
typedef typename internal::remove_reference<Arg3Nested>::type _Arg3Nested;
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE CwiseTernaryOp(const Arg1& a1, const Arg2& a2,
const Arg3& a3,
const TernaryOp& func = TernaryOp())
: m_arg1(a1), m_arg2(a2), m_arg3(a3), m_functor(func) {
// require the sizes to match
EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg2)
EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg3)
// The index types should match
EIGEN_STATIC_ASSERT((internal::is_same<
typename internal::traits<Arg1Type>::StorageKind,
typename internal::traits<Arg2Type>::StorageKind>::value),
STORAGE_KIND_MUST_MATCH)
EIGEN_STATIC_ASSERT((internal::is_same<
typename internal::traits<Arg1Type>::StorageKind,
typename internal::traits<Arg3Type>::StorageKind>::value),
STORAGE_KIND_MUST_MATCH)
eigen_assert(a1.rows() == a2.rows() && a1.cols() == a2.cols() &&
a1.rows() == a3.rows() && a1.cols() == a3.cols());
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Index rows() const {
// return the fixed size type if available to enable compile time
// optimizations
if (internal::traits<typename internal::remove_all<Arg1Nested>::type>::
RowsAtCompileTime == Dynamic &&
internal::traits<typename internal::remove_all<Arg2Nested>::type>::
RowsAtCompileTime == Dynamic)
return m_arg3.rows();
else if (internal::traits<typename internal::remove_all<Arg1Nested>::type>::
RowsAtCompileTime == Dynamic &&
internal::traits<typename internal::remove_all<Arg3Nested>::type>::
RowsAtCompileTime == Dynamic)
return m_arg2.rows();
else
return m_arg1.rows();
}
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Index cols() const {
// return the fixed size type if available to enable compile time
// optimizations
if (internal::traits<typename internal::remove_all<Arg1Nested>::type>::
ColsAtCompileTime == Dynamic &&
internal::traits<typename internal::remove_all<Arg2Nested>::type>::
ColsAtCompileTime == Dynamic)
return m_arg3.cols();
else if (internal::traits<typename internal::remove_all<Arg1Nested>::type>::
ColsAtCompileTime == Dynamic &&
internal::traits<typename internal::remove_all<Arg3Nested>::type>::
ColsAtCompileTime == Dynamic)
return m_arg2.cols();
else
return m_arg1.cols();
}
/** \returns the first argument nested expression */
EIGEN_DEVICE_FUNC
const _Arg1Nested& arg1() const { return m_arg1; }
/** \returns the first argument nested expression */
EIGEN_DEVICE_FUNC
const _Arg2Nested& arg2() const { return m_arg2; }
/** \returns the third argument nested expression */
EIGEN_DEVICE_FUNC
const _Arg3Nested& arg3() const { return m_arg3; }
/** \returns the functor representing the ternary operation */
EIGEN_DEVICE_FUNC
const TernaryOp& functor() const { return m_functor; }
protected:
Arg1Nested m_arg1;
Arg2Nested m_arg2;
Arg3Nested m_arg3;
const TernaryOp m_functor;
};
// Generic API dispatcher
template <typename TernaryOp, typename Arg1, typename Arg2, typename Arg3,
typename StorageKind>
class CwiseTernaryOpImpl
: public internal::generic_xpr_base<
CwiseTernaryOp<TernaryOp, Arg1, Arg2, Arg3> >::type {
public:
typedef typename internal::generic_xpr_base<
CwiseTernaryOp<TernaryOp, Arg1, Arg2, Arg3> >::type Base;
};
} // end namespace Eigen
#endif // EIGEN_CWISE_TERNARY_OP_H
| 8,256 | 40.70202 | 83 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/DiagonalProduct.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2007-2009 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_DIAGONALPRODUCT_H
#define EIGEN_DIAGONALPRODUCT_H
namespace Eigen {
/** \returns the diagonal matrix product of \c *this by the diagonal matrix \a diagonal.
*/
template<typename Derived>
template<typename DiagonalDerived>
inline const Product<Derived, DiagonalDerived, LazyProduct>
MatrixBase<Derived>::operator*(const DiagonalBase<DiagonalDerived> &a_diagonal) const
{
return Product<Derived, DiagonalDerived, LazyProduct>(derived(),a_diagonal.derived());
}
} // end namespace Eigen
#endif // EIGEN_DIAGONALPRODUCT_H
| 970 | 32.482759 | 88 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/EigenBase.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Benoit Jacob <[email protected]>
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_EIGENBASE_H
#define EIGEN_EIGENBASE_H
namespace Eigen {
/** \class EigenBase
* \ingroup Core_Module
*
* Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor MatrixBase(T).
*
* In other words, an EigenBase object is an object that can be copied into a MatrixBase.
*
* Besides MatrixBase-derived classes, this also includes special matrix classes such as diagonal matrices, etc.
*
* Notice that this class is trivial, it is only used to disambiguate overloaded functions.
*
* \sa \blank \ref TopicClassHierarchy
*/
template<typename Derived> struct EigenBase
{
// typedef typename internal::plain_matrix_type<Derived>::type PlainObject;
/** \brief The interface type of indices
* \details To change this, \c \#define the preprocessor symbol \c EIGEN_DEFAULT_DENSE_INDEX_TYPE.
* \deprecated Since Eigen 3.3, its usage is deprecated. Use Eigen::Index instead.
* \sa StorageIndex, \ref TopicPreprocessorDirectives.
*/
typedef Eigen::Index Index;
// FIXME is it needed?
typedef typename internal::traits<Derived>::StorageKind StorageKind;
/** \returns a reference to the derived object */
EIGEN_DEVICE_FUNC
Derived& derived() { return *static_cast<Derived*>(this); }
/** \returns a const reference to the derived object */
EIGEN_DEVICE_FUNC
const Derived& derived() const { return *static_cast<const Derived*>(this); }
EIGEN_DEVICE_FUNC
inline Derived& const_cast_derived() const
{ return *static_cast<Derived*>(const_cast<EigenBase*>(this)); }
EIGEN_DEVICE_FUNC
inline const Derived& const_derived() const
{ return *static_cast<const Derived*>(this); }
/** \returns the number of rows. \sa cols(), RowsAtCompileTime */
EIGEN_DEVICE_FUNC
inline Index rows() const { return derived().rows(); }
/** \returns the number of columns. \sa rows(), ColsAtCompileTime*/
EIGEN_DEVICE_FUNC
inline Index cols() const { return derived().cols(); }
/** \returns the number of coefficients, which is rows()*cols().
* \sa rows(), cols(), SizeAtCompileTime. */
EIGEN_DEVICE_FUNC
inline Index size() const { return rows() * cols(); }
/** \internal Don't use it, but do the equivalent: \code dst = *this; \endcode */
template<typename Dest>
EIGEN_DEVICE_FUNC
inline void evalTo(Dest& dst) const
{ derived().evalTo(dst); }
/** \internal Don't use it, but do the equivalent: \code dst += *this; \endcode */
template<typename Dest>
EIGEN_DEVICE_FUNC
inline void addTo(Dest& dst) const
{
// This is the default implementation,
// derived class can reimplement it in a more optimized way.
typename Dest::PlainObject res(rows(),cols());
evalTo(res);
dst += res;
}
/** \internal Don't use it, but do the equivalent: \code dst -= *this; \endcode */
template<typename Dest>
EIGEN_DEVICE_FUNC
inline void subTo(Dest& dst) const
{
// This is the default implementation,
// derived class can reimplement it in a more optimized way.
typename Dest::PlainObject res(rows(),cols());
evalTo(res);
dst -= res;
}
/** \internal Don't use it, but do the equivalent: \code dst.applyOnTheRight(*this); \endcode */
template<typename Dest>
EIGEN_DEVICE_FUNC inline void applyThisOnTheRight(Dest& dst) const
{
// This is the default implementation,
// derived class can reimplement it in a more optimized way.
dst = dst * this->derived();
}
/** \internal Don't use it, but do the equivalent: \code dst.applyOnTheLeft(*this); \endcode */
template<typename Dest>
EIGEN_DEVICE_FUNC inline void applyThisOnTheLeft(Dest& dst) const
{
// This is the default implementation,
// derived class can reimplement it in a more optimized way.
dst = this->derived() * dst;
}
};
/***************************************************************************
* Implementation of matrix base methods
***************************************************************************/
/** \brief Copies the generic expression \a other into *this.
*
* \details The expression must provide a (templated) evalTo(Derived& dst) const
* function which does the actual job. In practice, this allows any user to write
* its own special matrix without having to modify MatrixBase
*
* \returns a reference to *this.
*/
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& DenseBase<Derived>::operator=(const EigenBase<OtherDerived> &other)
{
call_assignment(derived(), other.derived());
return derived();
}
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& DenseBase<Derived>::operator+=(const EigenBase<OtherDerived> &other)
{
call_assignment(derived(), other.derived(), internal::add_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
template<typename Derived>
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
Derived& DenseBase<Derived>::operator-=(const EigenBase<OtherDerived> &other)
{
call_assignment(derived(), other.derived(), internal::sub_assign_op<Scalar,typename OtherDerived::Scalar>());
return derived();
}
} // end namespace Eigen
#endif // EIGEN_EIGENBASE_H
| 5,619 | 34.125 | 113 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/GenericPacketMath.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERIC_PACKET_MATH_H
#define EIGEN_GENERIC_PACKET_MATH_H
namespace Eigen {
namespace internal {
/** \internal
* \file GenericPacketMath.h
*
* Default implementation for types not supported by the vectorization.
* In practice these functions are provided to make easier the writing
* of generic vectorized code.
*/
#ifndef EIGEN_DEBUG_ALIGNED_LOAD
#define EIGEN_DEBUG_ALIGNED_LOAD
#endif
#ifndef EIGEN_DEBUG_UNALIGNED_LOAD
#define EIGEN_DEBUG_UNALIGNED_LOAD
#endif
#ifndef EIGEN_DEBUG_ALIGNED_STORE
#define EIGEN_DEBUG_ALIGNED_STORE
#endif
#ifndef EIGEN_DEBUG_UNALIGNED_STORE
#define EIGEN_DEBUG_UNALIGNED_STORE
#endif
struct default_packet_traits
{
enum {
HasHalfPacket = 0,
HasAdd = 1,
HasSub = 1,
HasMul = 1,
HasNegate = 1,
HasAbs = 1,
HasArg = 0,
HasAbs2 = 1,
HasMin = 1,
HasMax = 1,
HasConj = 1,
HasSetLinear = 1,
HasBlend = 0,
HasDiv = 0,
HasSqrt = 0,
HasRsqrt = 0,
HasExp = 0,
HasLog = 0,
HasLog1p = 0,
HasLog10 = 0,
HasPow = 0,
HasSin = 0,
HasCos = 0,
HasTan = 0,
HasASin = 0,
HasACos = 0,
HasATan = 0,
HasSinh = 0,
HasCosh = 0,
HasTanh = 0,
HasLGamma = 0,
HasDiGamma = 0,
HasZeta = 0,
HasPolygamma = 0,
HasErf = 0,
HasErfc = 0,
HasIGamma = 0,
HasIGammac = 0,
HasBetaInc = 0,
HasRound = 0,
HasFloor = 0,
HasCeil = 0,
HasSign = 0
};
};
template<typename T> struct packet_traits : default_packet_traits
{
typedef T type;
typedef T half;
enum {
Vectorizable = 0,
size = 1,
AlignedOnScalar = 0,
HasHalfPacket = 0
};
enum {
HasAdd = 0,
HasSub = 0,
HasMul = 0,
HasNegate = 0,
HasAbs = 0,
HasAbs2 = 0,
HasMin = 0,
HasMax = 0,
HasConj = 0,
HasSetLinear = 0
};
};
template<typename T> struct packet_traits<const T> : packet_traits<T> { };
template <typename Src, typename Tgt> struct type_casting_traits {
enum {
VectorizedCast = 0,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
/** \internal \returns static_cast<TgtType>(a) (coeff-wise) */
template <typename SrcPacket, typename TgtPacket>
EIGEN_DEVICE_FUNC inline TgtPacket
pcast(const SrcPacket& a) {
return static_cast<TgtPacket>(a);
}
template <typename SrcPacket, typename TgtPacket>
EIGEN_DEVICE_FUNC inline TgtPacket
pcast(const SrcPacket& a, const SrcPacket& /*b*/) {
return static_cast<TgtPacket>(a);
}
template <typename SrcPacket, typename TgtPacket>
EIGEN_DEVICE_FUNC inline TgtPacket
pcast(const SrcPacket& a, const SrcPacket& /*b*/, const SrcPacket& /*c*/, const SrcPacket& /*d*/) {
return static_cast<TgtPacket>(a);
}
/** \internal \returns a + b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
padd(const Packet& a,
const Packet& b) { return a+b; }
/** \internal \returns a - b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
psub(const Packet& a,
const Packet& b) { return a-b; }
/** \internal \returns -a (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pnegate(const Packet& a) { return -a; }
/** \internal \returns conj(a) (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pconj(const Packet& a) { return numext::conj(a); }
/** \internal \returns a * b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pmul(const Packet& a,
const Packet& b) { return a*b; }
/** \internal \returns a / b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pdiv(const Packet& a,
const Packet& b) { return a/b; }
/** \internal \returns the min of \a a and \a b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pmin(const Packet& a,
const Packet& b) { return numext::mini(a, b); }
/** \internal \returns the max of \a a and \a b (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pmax(const Packet& a,
const Packet& b) { return numext::maxi(a, b); }
/** \internal \returns the absolute value of \a a */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pabs(const Packet& a) { using std::abs; return abs(a); }
/** \internal \returns the phase angle of \a a */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
parg(const Packet& a) { using numext::arg; return arg(a); }
/** \internal \returns the bitwise and of \a a and \a b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pand(const Packet& a, const Packet& b) { return a & b; }
/** \internal \returns the bitwise or of \a a and \a b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
por(const Packet& a, const Packet& b) { return a | b; }
/** \internal \returns the bitwise xor of \a a and \a b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pxor(const Packet& a, const Packet& b) { return a ^ b; }
/** \internal \returns the bitwise andnot of \a a and \a b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pandnot(const Packet& a, const Packet& b) { return a & (!b); }
/** \internal \returns a packet version of \a *from, from must be 16 bytes aligned */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pload(const typename unpacket_traits<Packet>::type* from) { return *from; }
/** \internal \returns a packet version of \a *from, (un-aligned load) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
ploadu(const typename unpacket_traits<Packet>::type* from) { return *from; }
/** \internal \returns a packet with constant coefficients \a a, e.g.: (a,a,a,a) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pset1(const typename unpacket_traits<Packet>::type& a) { return a; }
/** \internal \returns a packet with constant coefficients \a a[0], e.g.: (a[0],a[0],a[0],a[0]) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pload1(const typename unpacket_traits<Packet>::type *a) { return pset1<Packet>(*a); }
/** \internal \returns a packet with elements of \a *from duplicated.
* For instance, for a packet of 8 elements, 4 scalars will be read from \a *from and
* duplicated to form: {from[0],from[0],from[1],from[1],from[2],from[2],from[3],from[3]}
* Currently, this function is only used for scalar * complex products.
*/
template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet
ploaddup(const typename unpacket_traits<Packet>::type* from) { return *from; }
/** \internal \returns a packet with elements of \a *from quadrupled.
* For instance, for a packet of 8 elements, 2 scalars will be read from \a *from and
* replicated to form: {from[0],from[0],from[0],from[0],from[1],from[1],from[1],from[1]}
* Currently, this function is only used in matrix products.
* For packet-size smaller or equal to 4, this function is equivalent to pload1
*/
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
ploadquad(const typename unpacket_traits<Packet>::type* from)
{ return pload1<Packet>(from); }
/** \internal equivalent to
* \code
* a0 = pload1(a+0);
* a1 = pload1(a+1);
* a2 = pload1(a+2);
* a3 = pload1(a+3);
* \endcode
* \sa pset1, pload1, ploaddup, pbroadcast2
*/
template<typename Packet> EIGEN_DEVICE_FUNC
inline void pbroadcast4(const typename unpacket_traits<Packet>::type *a,
Packet& a0, Packet& a1, Packet& a2, Packet& a3)
{
a0 = pload1<Packet>(a+0);
a1 = pload1<Packet>(a+1);
a2 = pload1<Packet>(a+2);
a3 = pload1<Packet>(a+3);
}
/** \internal equivalent to
* \code
* a0 = pload1(a+0);
* a1 = pload1(a+1);
* \endcode
* \sa pset1, pload1, ploaddup, pbroadcast4
*/
template<typename Packet> EIGEN_DEVICE_FUNC
inline void pbroadcast2(const typename unpacket_traits<Packet>::type *a,
Packet& a0, Packet& a1)
{
a0 = pload1<Packet>(a+0);
a1 = pload1<Packet>(a+1);
}
/** \internal \brief Returns a packet with coefficients (a,a+1,...,a+packet_size-1). */
template<typename Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet
plset(const typename unpacket_traits<Packet>::type& a) { return a; }
/** \internal copy the packet \a from to \a *to, \a to must be 16 bytes aligned */
template<typename Scalar, typename Packet> EIGEN_DEVICE_FUNC inline void pstore(Scalar* to, const Packet& from)
{ (*to) = from; }
/** \internal copy the packet \a from to \a *to, (un-aligned store) */
template<typename Scalar, typename Packet> EIGEN_DEVICE_FUNC inline void pstoreu(Scalar* to, const Packet& from)
{ (*to) = from; }
template<typename Scalar, typename Packet> EIGEN_DEVICE_FUNC inline Packet pgather(const Scalar* from, Index /*stride*/)
{ return ploadu<Packet>(from); }
template<typename Scalar, typename Packet> EIGEN_DEVICE_FUNC inline void pscatter(Scalar* to, const Packet& from, Index /*stride*/)
{ pstore(to, from); }
/** \internal tries to do cache prefetching of \a addr */
template<typename Scalar> EIGEN_DEVICE_FUNC inline void prefetch(const Scalar* addr)
{
#ifdef __CUDA_ARCH__
#if defined(__LP64__)
// 64-bit pointer operand constraint for inlined asm
asm(" prefetch.L1 [ %1 ];" : "=l"(addr) : "l"(addr));
#else
// 32-bit pointer operand constraint for inlined asm
asm(" prefetch.L1 [ %1 ];" : "=r"(addr) : "r"(addr));
#endif
#elif (!EIGEN_COMP_MSVC) && (EIGEN_COMP_GNUC || EIGEN_COMP_CLANG || EIGEN_COMP_ICC)
__builtin_prefetch(addr);
#endif
}
/** \internal \returns the first element of a packet */
template<typename Packet> EIGEN_DEVICE_FUNC inline typename unpacket_traits<Packet>::type pfirst(const Packet& a)
{ return a; }
/** \internal \returns a packet where the element i contains the sum of the packet of \a vec[i] */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
preduxp(const Packet* vecs) { return vecs[0]; }
/** \internal \returns the sum of the elements of \a a*/
template<typename Packet> EIGEN_DEVICE_FUNC inline typename unpacket_traits<Packet>::type predux(const Packet& a)
{ return a; }
/** \internal \returns the sum of the elements of \a a by block of 4 elements.
* For a packet {a0, a1, a2, a3, a4, a5, a6, a7}, it returns a half packet {a0+a4, a1+a5, a2+a6, a3+a7}
* For packet-size smaller or equal to 4, this boils down to a noop.
*/
template<typename Packet> EIGEN_DEVICE_FUNC inline
typename conditional<(unpacket_traits<Packet>::size%8)==0,typename unpacket_traits<Packet>::half,Packet>::type
predux_downto4(const Packet& a)
{ return a; }
/** \internal \returns the product of the elements of \a a*/
template<typename Packet> EIGEN_DEVICE_FUNC inline typename unpacket_traits<Packet>::type predux_mul(const Packet& a)
{ return a; }
/** \internal \returns the min of the elements of \a a*/
template<typename Packet> EIGEN_DEVICE_FUNC inline typename unpacket_traits<Packet>::type predux_min(const Packet& a)
{ return a; }
/** \internal \returns the max of the elements of \a a*/
template<typename Packet> EIGEN_DEVICE_FUNC inline typename unpacket_traits<Packet>::type predux_max(const Packet& a)
{ return a; }
/** \internal \returns the reversed elements of \a a*/
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet preverse(const Packet& a)
{ return a; }
/** \internal \returns \a a with real and imaginary part flipped (for complex type only) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet pcplxflip(const Packet& a)
{
// FIXME: uncomment the following in case we drop the internal imag and real functions.
// using std::imag;
// using std::real;
return Packet(imag(a),real(a));
}
/**************************
* Special math functions
***************************/
/** \internal \returns the sine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet psin(const Packet& a) { using std::sin; return sin(a); }
/** \internal \returns the cosine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pcos(const Packet& a) { using std::cos; return cos(a); }
/** \internal \returns the tan of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet ptan(const Packet& a) { using std::tan; return tan(a); }
/** \internal \returns the arc sine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pasin(const Packet& a) { using std::asin; return asin(a); }
/** \internal \returns the arc cosine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pacos(const Packet& a) { using std::acos; return acos(a); }
/** \internal \returns the arc tangent of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet patan(const Packet& a) { using std::atan; return atan(a); }
/** \internal \returns the hyperbolic sine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet psinh(const Packet& a) { using std::sinh; return sinh(a); }
/** \internal \returns the hyperbolic cosine of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pcosh(const Packet& a) { using std::cosh; return cosh(a); }
/** \internal \returns the hyperbolic tan of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet ptanh(const Packet& a) { using std::tanh; return tanh(a); }
/** \internal \returns the exp of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pexp(const Packet& a) { using std::exp; return exp(a); }
/** \internal \returns the log of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet plog(const Packet& a) { using std::log; return log(a); }
/** \internal \returns the log1p of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet plog1p(const Packet& a) { return numext::log1p(a); }
/** \internal \returns the log10 of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet plog10(const Packet& a) { using std::log10; return log10(a); }
/** \internal \returns the square-root of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet psqrt(const Packet& a) { using std::sqrt; return sqrt(a); }
/** \internal \returns the reciprocal square-root of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet prsqrt(const Packet& a) {
return pdiv(pset1<Packet>(1), psqrt(a));
}
/** \internal \returns the rounded value of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pround(const Packet& a) { using numext::round; return round(a); }
/** \internal \returns the floor of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pfloor(const Packet& a) { using numext::floor; return floor(a); }
/** \internal \returns the ceil of \a a (coeff-wise) */
template<typename Packet> EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS
Packet pceil(const Packet& a) { using numext::ceil; return ceil(a); }
/***************************************************************************
* The following functions might not have to be overwritten for vectorized types
***************************************************************************/
/** \internal copy a packet with constant coeficient \a a (e.g., [a,a,a,a]) to \a *to. \a to must be 16 bytes aligned */
// NOTE: this function must really be templated on the packet type (think about different packet types for the same scalar type)
template<typename Packet>
inline void pstore1(typename unpacket_traits<Packet>::type* to, const typename unpacket_traits<Packet>::type& a)
{
pstore(to, pset1<Packet>(a));
}
/** \internal \returns a * b + c (coeff-wise) */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pmadd(const Packet& a,
const Packet& b,
const Packet& c)
{ return padd(pmul(a, b),c); }
/** \internal \returns a packet version of \a *from.
* The pointer \a from must be aligned on a \a Alignment bytes boundary. */
template<typename Packet, int Alignment>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt(const typename unpacket_traits<Packet>::type* from)
{
if(Alignment >= unpacket_traits<Packet>::alignment)
return pload<Packet>(from);
else
return ploadu<Packet>(from);
}
/** \internal copy the packet \a from to \a *to.
* The pointer \a from must be aligned on a \a Alignment bytes boundary. */
template<typename Scalar, typename Packet, int Alignment>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void pstoret(Scalar* to, const Packet& from)
{
if(Alignment >= unpacket_traits<Packet>::alignment)
pstore(to, from);
else
pstoreu(to, from);
}
/** \internal \returns a packet version of \a *from.
* Unlike ploadt, ploadt_ro takes advantage of the read-only memory path on the
* hardware if available to speedup the loading of data that won't be modified
* by the current computation.
*/
template<typename Packet, int LoadMode>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt_ro(const typename unpacket_traits<Packet>::type* from)
{
return ploadt<Packet, LoadMode>(from);
}
/** \internal default implementation of palign() allowing partial specialization */
template<int Offset,typename PacketType>
struct palign_impl
{
// by default data are aligned, so there is nothing to be done :)
static inline void run(PacketType&, const PacketType&) {}
};
/** \internal update \a first using the concatenation of the packet_size minus \a Offset last elements
* of \a first and \a Offset first elements of \a second.
*
* This function is currently only used to optimize matrix-vector products on unligned matrices.
* It takes 2 packets that represent a contiguous memory array, and returns a packet starting
* at the position \a Offset. For instance, for packets of 4 elements, we have:
* Input:
* - first = {f0,f1,f2,f3}
* - second = {s0,s1,s2,s3}
* Output:
* - if Offset==0 then {f0,f1,f2,f3}
* - if Offset==1 then {f1,f2,f3,s0}
* - if Offset==2 then {f2,f3,s0,s1}
* - if Offset==3 then {f3,s0,s1,s3}
*/
template<int Offset,typename PacketType>
inline void palign(PacketType& first, const PacketType& second)
{
palign_impl<Offset,PacketType>::run(first,second);
}
/***************************************************************************
* Fast complex products (GCC generates a function call which is very slow)
***************************************************************************/
// Eigen+CUDA does not support complexes.
#ifndef __CUDACC__
template<> inline std::complex<float> pmul(const std::complex<float>& a, const std::complex<float>& b)
{ return std::complex<float>(real(a)*real(b) - imag(a)*imag(b), imag(a)*real(b) + real(a)*imag(b)); }
template<> inline std::complex<double> pmul(const std::complex<double>& a, const std::complex<double>& b)
{ return std::complex<double>(real(a)*real(b) - imag(a)*imag(b), imag(a)*real(b) + real(a)*imag(b)); }
#endif
/***************************************************************************
* PacketBlock, that is a collection of N packets where the number of words
* in the packet is a multiple of N.
***************************************************************************/
template <typename Packet,int N=unpacket_traits<Packet>::size> struct PacketBlock {
Packet packet[N];
};
template<typename Packet> EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<Packet,1>& /*kernel*/) {
// Nothing to do in the scalar case, i.e. a 1x1 matrix.
}
/***************************************************************************
* Selector, i.e. vector of N boolean values used to select (i.e. blend)
* words from 2 packets.
***************************************************************************/
template <size_t N> struct Selector {
bool select[N];
};
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pblend(const Selector<unpacket_traits<Packet>::size>& ifPacket, const Packet& thenPacket, const Packet& elsePacket) {
return ifPacket.select[0] ? thenPacket : elsePacket;
}
/** \internal \returns \a a with the first coefficient replaced by the scalar b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pinsertfirst(const Packet& a, typename unpacket_traits<Packet>::type b)
{
// Default implementation based on pblend.
// It must be specialized for higher performance.
Selector<unpacket_traits<Packet>::size> mask;
mask.select[0] = true;
// This for loop should be optimized away by the compiler.
for(Index i=1; i<unpacket_traits<Packet>::size; ++i)
mask.select[i] = false;
return pblend(mask, pset1<Packet>(b), a);
}
/** \internal \returns \a a with the last coefficient replaced by the scalar b */
template<typename Packet> EIGEN_DEVICE_FUNC inline Packet
pinsertlast(const Packet& a, typename unpacket_traits<Packet>::type b)
{
// Default implementation based on pblend.
// It must be specialized for higher performance.
Selector<unpacket_traits<Packet>::size> mask;
// This for loop should be optimized away by the compiler.
for(Index i=0; i<unpacket_traits<Packet>::size-1; ++i)
mask.select[i] = false;
mask.select[unpacket_traits<Packet>::size-1] = true;
return pblend(mask, pset1<Packet>(b), a);
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_GENERIC_PACKET_MATH_H
| 22,185 | 36.350168 | 132 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Inverse.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_INVERSE_H
#define EIGEN_INVERSE_H
namespace Eigen {
template<typename XprType,typename StorageKind> class InverseImpl;
namespace internal {
template<typename XprType>
struct traits<Inverse<XprType> >
: traits<typename XprType::PlainObject>
{
typedef typename XprType::PlainObject PlainObject;
typedef traits<PlainObject> BaseTraits;
enum {
Flags = BaseTraits::Flags & RowMajorBit
};
};
} // end namespace internal
/** \class Inverse
*
* \brief Expression of the inverse of another expression
*
* \tparam XprType the type of the expression we are taking the inverse
*
* This class represents an abstract expression of A.inverse()
* and most of the time this is the only way it is used.
*
*/
template<typename XprType>
class Inverse : public InverseImpl<XprType,typename internal::traits<XprType>::StorageKind>
{
public:
typedef typename XprType::StorageIndex StorageIndex;
typedef typename XprType::PlainObject PlainObject;
typedef typename XprType::Scalar Scalar;
typedef typename internal::ref_selector<XprType>::type XprTypeNested;
typedef typename internal::remove_all<XprTypeNested>::type XprTypeNestedCleaned;
typedef typename internal::ref_selector<Inverse>::type Nested;
typedef typename internal::remove_all<XprType>::type NestedExpression;
explicit EIGEN_DEVICE_FUNC Inverse(const XprType &xpr)
: m_xpr(xpr)
{}
EIGEN_DEVICE_FUNC Index rows() const { return m_xpr.rows(); }
EIGEN_DEVICE_FUNC Index cols() const { return m_xpr.cols(); }
EIGEN_DEVICE_FUNC const XprTypeNestedCleaned& nestedExpression() const { return m_xpr; }
protected:
XprTypeNested m_xpr;
};
// Generic API dispatcher
template<typename XprType, typename StorageKind>
class InverseImpl
: public internal::generic_xpr_base<Inverse<XprType> >::type
{
public:
typedef typename internal::generic_xpr_base<Inverse<XprType> >::type Base;
typedef typename XprType::Scalar Scalar;
private:
Scalar coeff(Index row, Index col) const;
Scalar coeff(Index i) const;
};
namespace internal {
/** \internal
* \brief Default evaluator for Inverse expression.
*
* This default evaluator for Inverse expression simply evaluate the inverse into a temporary
* by a call to internal::call_assignment_no_alias.
* Therefore, inverse implementers only have to specialize Assignment<Dst,Inverse<...>, ...> for
* there own nested expression.
*
* \sa class Inverse
*/
template<typename ArgType>
struct unary_evaluator<Inverse<ArgType> >
: public evaluator<typename Inverse<ArgType>::PlainObject>
{
typedef Inverse<ArgType> InverseType;
typedef typename InverseType::PlainObject PlainObject;
typedef evaluator<PlainObject> Base;
enum { Flags = Base::Flags | EvalBeforeNestingBit };
unary_evaluator(const InverseType& inv_xpr)
: m_result(inv_xpr.rows(), inv_xpr.cols())
{
::new (static_cast<Base*>(this)) Base(m_result);
internal::call_assignment_no_alias(m_result, inv_xpr);
}
protected:
PlainObject m_result;
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_INVERSE_H
| 3,519 | 28.579832 | 97 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/MathFunctionsImpl.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Pedro Gonnet ([email protected])
// Copyright (C) 2016 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATHFUNCTIONSIMPL_H
#define EIGEN_MATHFUNCTIONSIMPL_H
namespace Eigen {
namespace internal {
/** \internal \returns the hyperbolic tan of \a a (coeff-wise)
Doesn't do anything fancy, just a 13/6-degree rational interpolant which
is accurate up to a couple of ulp in the range [-9, 9], outside of which
the tanh(x) = +/-1.
This implementation works on both scalars and packets.
*/
template<typename T>
T generic_fast_tanh_float(const T& a_x)
{
// Clamp the inputs to the range [-9, 9] since anything outside
// this range is +/-1.0f in single-precision.
const T plus_9 = pset1<T>(9.f);
const T minus_9 = pset1<T>(-9.f);
// NOTE GCC prior to 6.3 might improperly optimize this max/min
// step such that if a_x is nan, x will be either 9 or -9,
// and tanh will return 1 or -1 instead of nan.
// This is supposed to be fixed in gcc6.3,
// see: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=72867
const T x = pmax(minus_9,pmin(plus_9,a_x));
// The monomial coefficients of the numerator polynomial (odd).
const T alpha_1 = pset1<T>(4.89352455891786e-03f);
const T alpha_3 = pset1<T>(6.37261928875436e-04f);
const T alpha_5 = pset1<T>(1.48572235717979e-05f);
const T alpha_7 = pset1<T>(5.12229709037114e-08f);
const T alpha_9 = pset1<T>(-8.60467152213735e-11f);
const T alpha_11 = pset1<T>(2.00018790482477e-13f);
const T alpha_13 = pset1<T>(-2.76076847742355e-16f);
// The monomial coefficients of the denominator polynomial (even).
const T beta_0 = pset1<T>(4.89352518554385e-03f);
const T beta_2 = pset1<T>(2.26843463243900e-03f);
const T beta_4 = pset1<T>(1.18534705686654e-04f);
const T beta_6 = pset1<T>(1.19825839466702e-06f);
// Since the polynomials are odd/even, we need x^2.
const T x2 = pmul(x, x);
// Evaluate the numerator polynomial p.
T p = pmadd(x2, alpha_13, alpha_11);
p = pmadd(x2, p, alpha_9);
p = pmadd(x2, p, alpha_7);
p = pmadd(x2, p, alpha_5);
p = pmadd(x2, p, alpha_3);
p = pmadd(x2, p, alpha_1);
p = pmul(x, p);
// Evaluate the denominator polynomial p.
T q = pmadd(x2, beta_6, beta_4);
q = pmadd(x2, q, beta_2);
q = pmadd(x2, q, beta_0);
// Divide the numerator by the denominator.
return pdiv(p, q);
}
template<typename RealScalar>
EIGEN_STRONG_INLINE
RealScalar positive_real_hypot(const RealScalar& x, const RealScalar& y)
{
EIGEN_USING_STD_MATH(sqrt);
RealScalar p, qp;
p = numext::maxi(x,y);
if(p==RealScalar(0)) return RealScalar(0);
qp = numext::mini(y,x) / p;
return p * sqrt(RealScalar(1) + qp*qp);
}
template<typename Scalar>
struct hypot_impl
{
typedef typename NumTraits<Scalar>::Real RealScalar;
static inline RealScalar run(const Scalar& x, const Scalar& y)
{
EIGEN_USING_STD_MATH(abs);
return positive_real_hypot<RealScalar>(abs(x), abs(y));
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATHFUNCTIONSIMPL_H
| 3,369 | 32.039216 | 76 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/NestByValue.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NESTBYVALUE_H
#define EIGEN_NESTBYVALUE_H
namespace Eigen {
namespace internal {
template<typename ExpressionType>
struct traits<NestByValue<ExpressionType> > : public traits<ExpressionType>
{};
}
/** \class NestByValue
* \ingroup Core_Module
*
* \brief Expression which must be nested by value
*
* \tparam ExpressionType the type of the object of which we are requiring nesting-by-value
*
* This class is the return type of MatrixBase::nestByValue()
* and most of the time this is the only way it is used.
*
* \sa MatrixBase::nestByValue()
*/
template<typename ExpressionType> class NestByValue
: public internal::dense_xpr_base< NestByValue<ExpressionType> >::type
{
public:
typedef typename internal::dense_xpr_base<NestByValue>::type Base;
EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue)
EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {}
EIGEN_DEVICE_FUNC inline Index rows() const { return m_expression.rows(); }
EIGEN_DEVICE_FUNC inline Index cols() const { return m_expression.cols(); }
EIGEN_DEVICE_FUNC inline Index outerStride() const { return m_expression.outerStride(); }
EIGEN_DEVICE_FUNC inline Index innerStride() const { return m_expression.innerStride(); }
EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const
{
return m_expression.coeff(row, col);
}
EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col)
{
return m_expression.const_cast_derived().coeffRef(row, col);
}
EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const
{
return m_expression.coeff(index);
}
EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index)
{
return m_expression.const_cast_derived().coeffRef(index);
}
template<int LoadMode>
inline const PacketScalar packet(Index row, Index col) const
{
return m_expression.template packet<LoadMode>(row, col);
}
template<int LoadMode>
inline void writePacket(Index row, Index col, const PacketScalar& x)
{
m_expression.const_cast_derived().template writePacket<LoadMode>(row, col, x);
}
template<int LoadMode>
inline const PacketScalar packet(Index index) const
{
return m_expression.template packet<LoadMode>(index);
}
template<int LoadMode>
inline void writePacket(Index index, const PacketScalar& x)
{
m_expression.const_cast_derived().template writePacket<LoadMode>(index, x);
}
EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; }
protected:
const ExpressionType m_expression;
};
/** \returns an expression of the temporary version of *this.
*/
template<typename Derived>
inline const NestByValue<Derived>
DenseBase<Derived>::nestByValue() const
{
return NestByValue<Derived>(derived());
}
} // end namespace Eigen
#endif // EIGEN_NESTBYVALUE_H
| 3,400 | 29.63964 | 105 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/NoAlias.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_NOALIAS_H
#define EIGEN_NOALIAS_H
namespace Eigen {
/** \class NoAlias
* \ingroup Core_Module
*
* \brief Pseudo expression providing an operator = assuming no aliasing
*
* \tparam ExpressionType the type of the object on which to do the lazy assignment
*
* This class represents an expression with special assignment operators
* assuming no aliasing between the target expression and the source expression.
* More precisely it alloas to bypass the EvalBeforeAssignBit flag of the source expression.
* It is the return type of MatrixBase::noalias()
* and most of the time this is the only way it is used.
*
* \sa MatrixBase::noalias()
*/
template<typename ExpressionType, template <typename> class StorageBase>
class NoAlias
{
public:
typedef typename ExpressionType::Scalar Scalar;
explicit NoAlias(ExpressionType& expression) : m_expression(expression) {}
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE ExpressionType& operator=(const StorageBase<OtherDerived>& other)
{
call_assignment_no_alias(m_expression, other.derived(), internal::assign_op<Scalar,typename OtherDerived::Scalar>());
return m_expression;
}
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE ExpressionType& operator+=(const StorageBase<OtherDerived>& other)
{
call_assignment_no_alias(m_expression, other.derived(), internal::add_assign_op<Scalar,typename OtherDerived::Scalar>());
return m_expression;
}
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE ExpressionType& operator-=(const StorageBase<OtherDerived>& other)
{
call_assignment_no_alias(m_expression, other.derived(), internal::sub_assign_op<Scalar,typename OtherDerived::Scalar>());
return m_expression;
}
EIGEN_DEVICE_FUNC
ExpressionType& expression() const
{
return m_expression;
}
protected:
ExpressionType& m_expression;
};
/** \returns a pseudo expression of \c *this with an operator= assuming
* no aliasing between \c *this and the source expression.
*
* More precisely, noalias() allows to bypass the EvalBeforeAssignBit flag.
* Currently, even though several expressions may alias, only product
* expressions have this flag. Therefore, noalias() is only usefull when
* the source expression contains a matrix product.
*
* Here are some examples where noalias is usefull:
* \code
* D.noalias() = A * B;
* D.noalias() += A.transpose() * B;
* D.noalias() -= 2 * A * B.adjoint();
* \endcode
*
* On the other hand the following example will lead to a \b wrong result:
* \code
* A.noalias() = A * B;
* \endcode
* because the result matrix A is also an operand of the matrix product. Therefore,
* there is no alternative than evaluating A * B in a temporary, that is the default
* behavior when you write:
* \code
* A = A * B;
* \endcode
*
* \sa class NoAlias
*/
template<typename Derived>
NoAlias<Derived,MatrixBase> MatrixBase<Derived>::noalias()
{
return NoAlias<Derived, Eigen::MatrixBase >(derived());
}
} // end namespace Eigen
#endif // EIGEN_NOALIAS_H
| 3,582 | 31.87156 | 127 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Product.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2011 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PRODUCT_H
#define EIGEN_PRODUCT_H
namespace Eigen {
template<typename Lhs, typename Rhs, int Option, typename StorageKind> class ProductImpl;
namespace internal {
template<typename Lhs, typename Rhs, int Option>
struct traits<Product<Lhs, Rhs, Option> >
{
typedef typename remove_all<Lhs>::type LhsCleaned;
typedef typename remove_all<Rhs>::type RhsCleaned;
typedef traits<LhsCleaned> LhsTraits;
typedef traits<RhsCleaned> RhsTraits;
typedef MatrixXpr XprKind;
typedef typename ScalarBinaryOpTraits<typename traits<LhsCleaned>::Scalar, typename traits<RhsCleaned>::Scalar>::ReturnType Scalar;
typedef typename product_promote_storage_type<typename LhsTraits::StorageKind,
typename RhsTraits::StorageKind,
internal::product_type<Lhs,Rhs>::ret>::ret StorageKind;
typedef typename promote_index_type<typename LhsTraits::StorageIndex,
typename RhsTraits::StorageIndex>::type StorageIndex;
enum {
RowsAtCompileTime = LhsTraits::RowsAtCompileTime,
ColsAtCompileTime = RhsTraits::ColsAtCompileTime,
MaxRowsAtCompileTime = LhsTraits::MaxRowsAtCompileTime,
MaxColsAtCompileTime = RhsTraits::MaxColsAtCompileTime,
// FIXME: only needed by GeneralMatrixMatrixTriangular
InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsTraits::ColsAtCompileTime, RhsTraits::RowsAtCompileTime),
// The storage order is somewhat arbitrary here. The correct one will be determined through the evaluator.
Flags = (MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1) ? RowMajorBit
: (MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1) ? 0
: ( ((LhsTraits::Flags&NoPreferredStorageOrderBit) && (RhsTraits::Flags&RowMajorBit))
|| ((RhsTraits::Flags&NoPreferredStorageOrderBit) && (LhsTraits::Flags&RowMajorBit)) ) ? RowMajorBit
: NoPreferredStorageOrderBit
};
};
} // end namespace internal
/** \class Product
* \ingroup Core_Module
*
* \brief Expression of the product of two arbitrary matrices or vectors
*
* \tparam _Lhs the type of the left-hand side expression
* \tparam _Rhs the type of the right-hand side expression
*
* This class represents an expression of the product of two arbitrary matrices.
*
* The other template parameters are:
* \tparam Option can be DefaultProduct, AliasFreeProduct, or LazyProduct
*
*/
template<typename _Lhs, typename _Rhs, int Option>
class Product : public ProductImpl<_Lhs,_Rhs,Option,
typename internal::product_promote_storage_type<typename internal::traits<_Lhs>::StorageKind,
typename internal::traits<_Rhs>::StorageKind,
internal::product_type<_Lhs,_Rhs>::ret>::ret>
{
public:
typedef _Lhs Lhs;
typedef _Rhs Rhs;
typedef typename ProductImpl<
Lhs, Rhs, Option,
typename internal::product_promote_storage_type<typename internal::traits<Lhs>::StorageKind,
typename internal::traits<Rhs>::StorageKind,
internal::product_type<Lhs,Rhs>::ret>::ret>::Base Base;
EIGEN_GENERIC_PUBLIC_INTERFACE(Product)
typedef typename internal::ref_selector<Lhs>::type LhsNested;
typedef typename internal::ref_selector<Rhs>::type RhsNested;
typedef typename internal::remove_all<LhsNested>::type LhsNestedCleaned;
typedef typename internal::remove_all<RhsNested>::type RhsNestedCleaned;
EIGEN_DEVICE_FUNC Product(const Lhs& lhs, const Rhs& rhs) : m_lhs(lhs), m_rhs(rhs)
{
eigen_assert(lhs.cols() == rhs.rows()
&& "invalid matrix product"
&& "if you wanted a coeff-wise or a dot product use the respective explicit functions");
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rows() const { return m_lhs.rows(); }
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index cols() const { return m_rhs.cols(); }
EIGEN_DEVICE_FUNC const LhsNestedCleaned& lhs() const { return m_lhs; }
EIGEN_DEVICE_FUNC const RhsNestedCleaned& rhs() const { return m_rhs; }
protected:
LhsNested m_lhs;
RhsNested m_rhs;
};
namespace internal {
template<typename Lhs, typename Rhs, int Option, int ProductTag = internal::product_type<Lhs,Rhs>::ret>
class dense_product_base
: public internal::dense_xpr_base<Product<Lhs,Rhs,Option> >::type
{};
/** Convertion to scalar for inner-products */
template<typename Lhs, typename Rhs, int Option>
class dense_product_base<Lhs, Rhs, Option, InnerProduct>
: public internal::dense_xpr_base<Product<Lhs,Rhs,Option> >::type
{
typedef Product<Lhs,Rhs,Option> ProductXpr;
typedef typename internal::dense_xpr_base<ProductXpr>::type Base;
public:
using Base::derived;
typedef typename Base::Scalar Scalar;
EIGEN_STRONG_INLINE operator const Scalar() const
{
return internal::evaluator<ProductXpr>(derived()).coeff(0,0);
}
};
} // namespace internal
// Generic API dispatcher
template<typename Lhs, typename Rhs, int Option, typename StorageKind>
class ProductImpl : public internal::generic_xpr_base<Product<Lhs,Rhs,Option>, MatrixXpr, StorageKind>::type
{
public:
typedef typename internal::generic_xpr_base<Product<Lhs,Rhs,Option>, MatrixXpr, StorageKind>::type Base;
};
template<typename Lhs, typename Rhs, int Option>
class ProductImpl<Lhs,Rhs,Option,Dense>
: public internal::dense_product_base<Lhs,Rhs,Option>
{
typedef Product<Lhs, Rhs, Option> Derived;
public:
typedef typename internal::dense_product_base<Lhs, Rhs, Option> Base;
EIGEN_DENSE_PUBLIC_INTERFACE(Derived)
protected:
enum {
IsOneByOne = (RowsAtCompileTime == 1 || RowsAtCompileTime == Dynamic) &&
(ColsAtCompileTime == 1 || ColsAtCompileTime == Dynamic),
EnableCoeff = IsOneByOne || Option==LazyProduct
};
public:
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index row, Index col) const
{
EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS);
eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) );
return internal::evaluator<Derived>(derived()).coeff(row,col);
}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index i) const
{
EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS);
eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) );
return internal::evaluator<Derived>(derived()).coeff(i);
}
};
} // end namespace Eigen
#endif // EIGEN_PRODUCT_H
| 7,235 | 37.695187 | 133 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Random.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_RANDOM_H
#define EIGEN_RANDOM_H
namespace Eigen {
namespace internal {
template<typename Scalar> struct scalar_random_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_random_op)
inline const Scalar operator() () const { return random<Scalar>(); }
};
template<typename Scalar>
struct functor_traits<scalar_random_op<Scalar> >
{ enum { Cost = 5 * NumTraits<Scalar>::MulCost, PacketAccess = false, IsRepeatable = false }; };
} // end namespace internal
/** \returns a random matrix expression
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* The parameters \a rows and \a cols are the number of rows and of columns of
* the returned matrix. Must be compatible with this MatrixBase type.
*
* \not_reentrant
*
* This variant is meant to be used for dynamic-size matrix types. For fixed-size types,
* it is redundant to pass \a rows and \a cols as arguments, so Random() should be used
* instead.
*
*
* Example: \include MatrixBase_random_int_int.cpp
* Output: \verbinclude MatrixBase_random_int_int.out
*
* This expression has the "evaluate before nesting" flag so that it will be evaluated into
* a temporary matrix whenever it is nested in a larger expression. This prevents unexpected
* behavior with expressions involving random matrices.
*
* See DenseBase::NullaryExpr(Index, const CustomNullaryOp&) for an example using C++11 random generators.
*
* \sa DenseBase::setRandom(), DenseBase::Random(Index), DenseBase::Random()
*/
template<typename Derived>
inline const typename DenseBase<Derived>::RandomReturnType
DenseBase<Derived>::Random(Index rows, Index cols)
{
return NullaryExpr(rows, cols, internal::scalar_random_op<Scalar>());
}
/** \returns a random vector expression
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* The parameter \a size is the size of the returned vector.
* Must be compatible with this MatrixBase type.
*
* \only_for_vectors
* \not_reentrant
*
* This variant is meant to be used for dynamic-size vector types. For fixed-size types,
* it is redundant to pass \a size as argument, so Random() should be used
* instead.
*
* Example: \include MatrixBase_random_int.cpp
* Output: \verbinclude MatrixBase_random_int.out
*
* This expression has the "evaluate before nesting" flag so that it will be evaluated into
* a temporary vector whenever it is nested in a larger expression. This prevents unexpected
* behavior with expressions involving random matrices.
*
* \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random()
*/
template<typename Derived>
inline const typename DenseBase<Derived>::RandomReturnType
DenseBase<Derived>::Random(Index size)
{
return NullaryExpr(size, internal::scalar_random_op<Scalar>());
}
/** \returns a fixed-size random matrix or vector expression
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* This variant is only for fixed-size MatrixBase types. For dynamic-size types, you
* need to use the variants taking size arguments.
*
* Example: \include MatrixBase_random.cpp
* Output: \verbinclude MatrixBase_random.out
*
* This expression has the "evaluate before nesting" flag so that it will be evaluated into
* a temporary matrix whenever it is nested in a larger expression. This prevents unexpected
* behavior with expressions involving random matrices.
*
* \not_reentrant
*
* \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random(Index)
*/
template<typename Derived>
inline const typename DenseBase<Derived>::RandomReturnType
DenseBase<Derived>::Random()
{
return NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_random_op<Scalar>());
}
/** Sets all coefficients in this expression to random values.
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* \not_reentrant
*
* Example: \include MatrixBase_setRandom.cpp
* Output: \verbinclude MatrixBase_setRandom.out
*
* \sa class CwiseNullaryOp, setRandom(Index), setRandom(Index,Index)
*/
template<typename Derived>
inline Derived& DenseBase<Derived>::setRandom()
{
return *this = Random(rows(), cols());
}
/** Resizes to the given \a newSize, and sets all coefficients in this expression to random values.
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* \only_for_vectors
* \not_reentrant
*
* Example: \include Matrix_setRandom_int.cpp
* Output: \verbinclude Matrix_setRandom_int.out
*
* \sa DenseBase::setRandom(), setRandom(Index,Index), class CwiseNullaryOp, DenseBase::Random()
*/
template<typename Derived>
EIGEN_STRONG_INLINE Derived&
PlainObjectBase<Derived>::setRandom(Index newSize)
{
resize(newSize);
return setRandom();
}
/** Resizes to the given size, and sets all coefficients in this expression to random values.
*
* Numbers are uniformly spread through their whole definition range for integer types,
* and in the [-1:1] range for floating point scalar types.
*
* \not_reentrant
*
* \param rows the new number of rows
* \param cols the new number of columns
*
* Example: \include Matrix_setRandom_int_int.cpp
* Output: \verbinclude Matrix_setRandom_int_int.out
*
* \sa DenseBase::setRandom(), setRandom(Index), class CwiseNullaryOp, DenseBase::Random()
*/
template<typename Derived>
EIGEN_STRONG_INLINE Derived&
PlainObjectBase<Derived>::setRandom(Index rows, Index cols)
{
resize(rows, cols);
return setRandom();
}
} // end namespace Eigen
#endif // EIGEN_RANDOM_H
| 6,379 | 33.863388 | 107 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Replicate.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REPLICATE_H
#define EIGEN_REPLICATE_H
namespace Eigen {
namespace internal {
template<typename MatrixType,int RowFactor,int ColFactor>
struct traits<Replicate<MatrixType,RowFactor,ColFactor> >
: traits<MatrixType>
{
typedef typename MatrixType::Scalar Scalar;
typedef typename traits<MatrixType>::StorageKind StorageKind;
typedef typename traits<MatrixType>::XprKind XprKind;
typedef typename ref_selector<MatrixType>::type MatrixTypeNested;
typedef typename remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
enum {
RowsAtCompileTime = RowFactor==Dynamic || int(MatrixType::RowsAtCompileTime)==Dynamic
? Dynamic
: RowFactor * MatrixType::RowsAtCompileTime,
ColsAtCompileTime = ColFactor==Dynamic || int(MatrixType::ColsAtCompileTime)==Dynamic
? Dynamic
: ColFactor * MatrixType::ColsAtCompileTime,
//FIXME we don't propagate the max sizes !!!
MaxRowsAtCompileTime = RowsAtCompileTime,
MaxColsAtCompileTime = ColsAtCompileTime,
IsRowMajor = MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1 ? 1
: MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1 ? 0
: (MatrixType::Flags & RowMajorBit) ? 1 : 0,
// FIXME enable DirectAccess with negative strides?
Flags = IsRowMajor ? RowMajorBit : 0
};
};
}
/**
* \class Replicate
* \ingroup Core_Module
*
* \brief Expression of the multiple replication of a matrix or vector
*
* \tparam MatrixType the type of the object we are replicating
* \tparam RowFactor number of repetitions at compile time along the vertical direction, can be Dynamic.
* \tparam ColFactor number of repetitions at compile time along the horizontal direction, can be Dynamic.
*
* This class represents an expression of the multiple replication of a matrix or vector.
* It is the return type of DenseBase::replicate() and most of the time
* this is the only way it is used.
*
* \sa DenseBase::replicate()
*/
template<typename MatrixType,int RowFactor,int ColFactor> class Replicate
: public internal::dense_xpr_base< Replicate<MatrixType,RowFactor,ColFactor> >::type
{
typedef typename internal::traits<Replicate>::MatrixTypeNested MatrixTypeNested;
typedef typename internal::traits<Replicate>::_MatrixTypeNested _MatrixTypeNested;
public:
typedef typename internal::dense_xpr_base<Replicate>::type Base;
EIGEN_DENSE_PUBLIC_INTERFACE(Replicate)
typedef typename internal::remove_all<MatrixType>::type NestedExpression;
template<typename OriginalMatrixType>
EIGEN_DEVICE_FUNC
inline explicit Replicate(const OriginalMatrixType& matrix)
: m_matrix(matrix), m_rowFactor(RowFactor), m_colFactor(ColFactor)
{
EIGEN_STATIC_ASSERT((internal::is_same<typename internal::remove_const<MatrixType>::type,OriginalMatrixType>::value),
THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE)
eigen_assert(RowFactor!=Dynamic && ColFactor!=Dynamic);
}
template<typename OriginalMatrixType>
EIGEN_DEVICE_FUNC
inline Replicate(const OriginalMatrixType& matrix, Index rowFactor, Index colFactor)
: m_matrix(matrix), m_rowFactor(rowFactor), m_colFactor(colFactor)
{
EIGEN_STATIC_ASSERT((internal::is_same<typename internal::remove_const<MatrixType>::type,OriginalMatrixType>::value),
THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE)
}
EIGEN_DEVICE_FUNC
inline Index rows() const { return m_matrix.rows() * m_rowFactor.value(); }
EIGEN_DEVICE_FUNC
inline Index cols() const { return m_matrix.cols() * m_colFactor.value(); }
EIGEN_DEVICE_FUNC
const _MatrixTypeNested& nestedExpression() const
{
return m_matrix;
}
protected:
MatrixTypeNested m_matrix;
const internal::variable_if_dynamic<Index, RowFactor> m_rowFactor;
const internal::variable_if_dynamic<Index, ColFactor> m_colFactor;
};
/**
* \return an expression of the replication of \c *this
*
* Example: \include MatrixBase_replicate.cpp
* Output: \verbinclude MatrixBase_replicate.out
*
* \sa VectorwiseOp::replicate(), DenseBase::replicate(Index,Index), class Replicate
*/
template<typename Derived>
template<int RowFactor, int ColFactor>
const Replicate<Derived,RowFactor,ColFactor>
DenseBase<Derived>::replicate() const
{
return Replicate<Derived,RowFactor,ColFactor>(derived());
}
/**
* \return an expression of the replication of each column (or row) of \c *this
*
* Example: \include DirectionWise_replicate_int.cpp
* Output: \verbinclude DirectionWise_replicate_int.out
*
* \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate
*/
template<typename ExpressionType, int Direction>
const typename VectorwiseOp<ExpressionType,Direction>::ReplicateReturnType
VectorwiseOp<ExpressionType,Direction>::replicate(Index factor) const
{
return typename VectorwiseOp<ExpressionType,Direction>::ReplicateReturnType
(_expression(),Direction==Vertical?factor:1,Direction==Horizontal?factor:1);
}
} // end namespace Eigen
#endif // EIGEN_REPLICATE_H
| 5,595 | 38.132867 | 123 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Reverse.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
// Copyright (C) 2009 Ricard Marxer <[email protected]>
// Copyright (C) 2009-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REVERSE_H
#define EIGEN_REVERSE_H
namespace Eigen {
namespace internal {
template<typename MatrixType, int Direction>
struct traits<Reverse<MatrixType, Direction> >
: traits<MatrixType>
{
typedef typename MatrixType::Scalar Scalar;
typedef typename traits<MatrixType>::StorageKind StorageKind;
typedef typename traits<MatrixType>::XprKind XprKind;
typedef typename ref_selector<MatrixType>::type MatrixTypeNested;
typedef typename remove_reference<MatrixTypeNested>::type _MatrixTypeNested;
enum {
RowsAtCompileTime = MatrixType::RowsAtCompileTime,
ColsAtCompileTime = MatrixType::ColsAtCompileTime,
MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
Flags = _MatrixTypeNested::Flags & (RowMajorBit | LvalueBit)
};
};
template<typename PacketType, bool ReversePacket> struct reverse_packet_cond
{
static inline PacketType run(const PacketType& x) { return preverse(x); }
};
template<typename PacketType> struct reverse_packet_cond<PacketType,false>
{
static inline PacketType run(const PacketType& x) { return x; }
};
} // end namespace internal
/** \class Reverse
* \ingroup Core_Module
*
* \brief Expression of the reverse of a vector or matrix
*
* \tparam MatrixType the type of the object of which we are taking the reverse
* \tparam Direction defines the direction of the reverse operation, can be Vertical, Horizontal, or BothDirections
*
* This class represents an expression of the reverse of a vector.
* It is the return type of MatrixBase::reverse() and VectorwiseOp::reverse()
* and most of the time this is the only way it is used.
*
* \sa MatrixBase::reverse(), VectorwiseOp::reverse()
*/
template<typename MatrixType, int Direction> class Reverse
: public internal::dense_xpr_base< Reverse<MatrixType, Direction> >::type
{
public:
typedef typename internal::dense_xpr_base<Reverse>::type Base;
EIGEN_DENSE_PUBLIC_INTERFACE(Reverse)
typedef typename internal::remove_all<MatrixType>::type NestedExpression;
using Base::IsRowMajor;
protected:
enum {
PacketSize = internal::packet_traits<Scalar>::size,
IsColMajor = !IsRowMajor,
ReverseRow = (Direction == Vertical) || (Direction == BothDirections),
ReverseCol = (Direction == Horizontal) || (Direction == BothDirections),
OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1,
OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1,
ReversePacket = (Direction == BothDirections)
|| ((Direction == Vertical) && IsColMajor)
|| ((Direction == Horizontal) && IsRowMajor)
};
typedef internal::reverse_packet_cond<PacketScalar,ReversePacket> reverse_packet;
public:
EIGEN_DEVICE_FUNC explicit inline Reverse(const MatrixType& matrix) : m_matrix(matrix) { }
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reverse)
EIGEN_DEVICE_FUNC inline Index rows() const { return m_matrix.rows(); }
EIGEN_DEVICE_FUNC inline Index cols() const { return m_matrix.cols(); }
EIGEN_DEVICE_FUNC inline Index innerStride() const
{
return -m_matrix.innerStride();
}
EIGEN_DEVICE_FUNC const typename internal::remove_all<typename MatrixType::Nested>::type&
nestedExpression() const
{
return m_matrix;
}
protected:
typename MatrixType::Nested m_matrix;
};
/** \returns an expression of the reverse of *this.
*
* Example: \include MatrixBase_reverse.cpp
* Output: \verbinclude MatrixBase_reverse.out
*
*/
template<typename Derived>
inline typename DenseBase<Derived>::ReverseReturnType
DenseBase<Derived>::reverse()
{
return ReverseReturnType(derived());
}
//reverse const overload moved DenseBase.h due to a CUDA compiler bug
/** This is the "in place" version of reverse: it reverses \c *this.
*
* In most cases it is probably better to simply use the reversed expression
* of a matrix. However, when reversing the matrix data itself is really needed,
* then this "in-place" version is probably the right choice because it provides
* the following additional benefits:
* - less error prone: doing the same operation with .reverse() requires special care:
* \code m = m.reverse().eval(); \endcode
* - this API enables reverse operations without the need for a temporary
* - it allows future optimizations (cache friendliness, etc.)
*
* \sa VectorwiseOp::reverseInPlace(), reverse() */
template<typename Derived>
inline void DenseBase<Derived>::reverseInPlace()
{
if(cols()>rows())
{
Index half = cols()/2;
leftCols(half).swap(rightCols(half).reverse());
if((cols()%2)==1)
{
Index half2 = rows()/2;
col(half).head(half2).swap(col(half).tail(half2).reverse());
}
}
else
{
Index half = rows()/2;
topRows(half).swap(bottomRows(half).reverse());
if((rows()%2)==1)
{
Index half2 = cols()/2;
row(half).head(half2).swap(row(half).tail(half2).reverse());
}
}
}
namespace internal {
template<int Direction>
struct vectorwise_reverse_inplace_impl;
template<>
struct vectorwise_reverse_inplace_impl<Vertical>
{
template<typename ExpressionType>
static void run(ExpressionType &xpr)
{
Index half = xpr.rows()/2;
xpr.topRows(half).swap(xpr.bottomRows(half).colwise().reverse());
}
};
template<>
struct vectorwise_reverse_inplace_impl<Horizontal>
{
template<typename ExpressionType>
static void run(ExpressionType &xpr)
{
Index half = xpr.cols()/2;
xpr.leftCols(half).swap(xpr.rightCols(half).rowwise().reverse());
}
};
} // end namespace internal
/** This is the "in place" version of VectorwiseOp::reverse: it reverses each column or row of \c *this.
*
* In most cases it is probably better to simply use the reversed expression
* of a matrix. However, when reversing the matrix data itself is really needed,
* then this "in-place" version is probably the right choice because it provides
* the following additional benefits:
* - less error prone: doing the same operation with .reverse() requires special care:
* \code m = m.reverse().eval(); \endcode
* - this API enables reverse operations without the need for a temporary
*
* \sa DenseBase::reverseInPlace(), reverse() */
template<typename ExpressionType, int Direction>
void VectorwiseOp<ExpressionType,Direction>::reverseInPlace()
{
internal::vectorwise_reverse_inplace_impl<Direction>::run(_expression().const_cast_derived());
}
} // end namespace Eigen
#endif // EIGEN_REVERSE_H
| 7,073 | 32.367925 | 116 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Select.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELECT_H
#define EIGEN_SELECT_H
namespace Eigen {
/** \class Select
* \ingroup Core_Module
*
* \brief Expression of a coefficient wise version of the C++ ternary operator ?:
*
* \param ConditionMatrixType the type of the \em condition expression which must be a boolean matrix
* \param ThenMatrixType the type of the \em then expression
* \param ElseMatrixType the type of the \em else expression
*
* This class represents an expression of a coefficient wise version of the C++ ternary operator ?:.
* It is the return type of DenseBase::select() and most of the time this is the only way it is used.
*
* \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const
*/
namespace internal {
template<typename ConditionMatrixType, typename ThenMatrixType, typename ElseMatrixType>
struct traits<Select<ConditionMatrixType, ThenMatrixType, ElseMatrixType> >
: traits<ThenMatrixType>
{
typedef typename traits<ThenMatrixType>::Scalar Scalar;
typedef Dense StorageKind;
typedef typename traits<ThenMatrixType>::XprKind XprKind;
typedef typename ConditionMatrixType::Nested ConditionMatrixNested;
typedef typename ThenMatrixType::Nested ThenMatrixNested;
typedef typename ElseMatrixType::Nested ElseMatrixNested;
enum {
RowsAtCompileTime = ConditionMatrixType::RowsAtCompileTime,
ColsAtCompileTime = ConditionMatrixType::ColsAtCompileTime,
MaxRowsAtCompileTime = ConditionMatrixType::MaxRowsAtCompileTime,
MaxColsAtCompileTime = ConditionMatrixType::MaxColsAtCompileTime,
Flags = (unsigned int)ThenMatrixType::Flags & ElseMatrixType::Flags & RowMajorBit
};
};
}
template<typename ConditionMatrixType, typename ThenMatrixType, typename ElseMatrixType>
class Select : public internal::dense_xpr_base< Select<ConditionMatrixType, ThenMatrixType, ElseMatrixType> >::type,
internal::no_assignment_operator
{
public:
typedef typename internal::dense_xpr_base<Select>::type Base;
EIGEN_DENSE_PUBLIC_INTERFACE(Select)
inline EIGEN_DEVICE_FUNC
Select(const ConditionMatrixType& a_conditionMatrix,
const ThenMatrixType& a_thenMatrix,
const ElseMatrixType& a_elseMatrix)
: m_condition(a_conditionMatrix), m_then(a_thenMatrix), m_else(a_elseMatrix)
{
eigen_assert(m_condition.rows() == m_then.rows() && m_condition.rows() == m_else.rows());
eigen_assert(m_condition.cols() == m_then.cols() && m_condition.cols() == m_else.cols());
}
inline EIGEN_DEVICE_FUNC Index rows() const { return m_condition.rows(); }
inline EIGEN_DEVICE_FUNC Index cols() const { return m_condition.cols(); }
inline EIGEN_DEVICE_FUNC
const Scalar coeff(Index i, Index j) const
{
if (m_condition.coeff(i,j))
return m_then.coeff(i,j);
else
return m_else.coeff(i,j);
}
inline EIGEN_DEVICE_FUNC
const Scalar coeff(Index i) const
{
if (m_condition.coeff(i))
return m_then.coeff(i);
else
return m_else.coeff(i);
}
inline EIGEN_DEVICE_FUNC const ConditionMatrixType& conditionMatrix() const
{
return m_condition;
}
inline EIGEN_DEVICE_FUNC const ThenMatrixType& thenMatrix() const
{
return m_then;
}
inline EIGEN_DEVICE_FUNC const ElseMatrixType& elseMatrix() const
{
return m_else;
}
protected:
typename ConditionMatrixType::Nested m_condition;
typename ThenMatrixType::Nested m_then;
typename ElseMatrixType::Nested m_else;
};
/** \returns a matrix where each coefficient (i,j) is equal to \a thenMatrix(i,j)
* if \c *this(i,j), and \a elseMatrix(i,j) otherwise.
*
* Example: \include MatrixBase_select.cpp
* Output: \verbinclude MatrixBase_select.out
*
* \sa class Select
*/
template<typename Derived>
template<typename ThenDerived,typename ElseDerived>
inline const Select<Derived,ThenDerived,ElseDerived>
DenseBase<Derived>::select(const DenseBase<ThenDerived>& thenMatrix,
const DenseBase<ElseDerived>& elseMatrix) const
{
return Select<Derived,ThenDerived,ElseDerived>(derived(), thenMatrix.derived(), elseMatrix.derived());
}
/** Version of DenseBase::select(const DenseBase&, const DenseBase&) with
* the \em else expression being a scalar value.
*
* \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const, class Select
*/
template<typename Derived>
template<typename ThenDerived>
inline const Select<Derived,ThenDerived, typename ThenDerived::ConstantReturnType>
DenseBase<Derived>::select(const DenseBase<ThenDerived>& thenMatrix,
const typename ThenDerived::Scalar& elseScalar) const
{
return Select<Derived,ThenDerived,typename ThenDerived::ConstantReturnType>(
derived(), thenMatrix.derived(), ThenDerived::Constant(rows(),cols(),elseScalar));
}
/** Version of DenseBase::select(const DenseBase&, const DenseBase&) with
* the \em then expression being a scalar value.
*
* \sa DenseBase::select(const DenseBase<ThenDerived>&, const DenseBase<ElseDerived>&) const, class Select
*/
template<typename Derived>
template<typename ElseDerived>
inline const Select<Derived, typename ElseDerived::ConstantReturnType, ElseDerived >
DenseBase<Derived>::select(const typename ElseDerived::Scalar& thenScalar,
const DenseBase<ElseDerived>& elseMatrix) const
{
return Select<Derived,typename ElseDerived::ConstantReturnType,ElseDerived>(
derived(), ElseDerived::Constant(rows(),cols(),thenScalar), elseMatrix.derived());
}
} // end namespace Eigen
#endif // EIGEN_SELECT_H
| 6,020 | 35.93865 | 116 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/SelfCwiseBinaryOp.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SELFCWISEBINARYOP_H
#define EIGEN_SELFCWISEBINARYOP_H
namespace Eigen {
// TODO generalize the scalar type of 'other'
template<typename Derived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase<Derived>::operator*=(const Scalar& other)
{
internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::mul_assign_op<Scalar,Scalar>());
return derived();
}
template<typename Derived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase<Derived>::operator+=(const Scalar& other)
{
internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::add_assign_op<Scalar,Scalar>());
return derived();
}
template<typename Derived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& ArrayBase<Derived>::operator-=(const Scalar& other)
{
internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::sub_assign_op<Scalar,Scalar>());
return derived();
}
template<typename Derived>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase<Derived>::operator/=(const Scalar& other)
{
internal::call_assignment(this->derived(), PlainObject::Constant(rows(),cols(),other), internal::div_assign_op<Scalar,Scalar>());
return derived();
}
} // end namespace Eigen
#endif // EIGEN_SELFCWISEBINARYOP_H
| 1,697 | 34.375 | 131 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/SolverBase.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_SOLVERBASE_H
#define EIGEN_SOLVERBASE_H
namespace Eigen {
namespace internal {
} // end namespace internal
/** \class SolverBase
* \brief A base class for matrix decomposition and solvers
*
* \tparam Derived the actual type of the decomposition/solver.
*
* Any matrix decomposition inheriting this base class provide the following API:
*
* \code
* MatrixType A, b, x;
* DecompositionType dec(A);
* x = dec.solve(b); // solve A * x = b
* x = dec.transpose().solve(b); // solve A^T * x = b
* x = dec.adjoint().solve(b); // solve A' * x = b
* \endcode
*
* \warning Currently, any other usage of transpose() and adjoint() are not supported and will produce compilation errors.
*
* \sa class PartialPivLU, class FullPivLU
*/
template<typename Derived>
class SolverBase : public EigenBase<Derived>
{
public:
typedef EigenBase<Derived> Base;
typedef typename internal::traits<Derived>::Scalar Scalar;
typedef Scalar CoeffReturnType;
enum {
RowsAtCompileTime = internal::traits<Derived>::RowsAtCompileTime,
ColsAtCompileTime = internal::traits<Derived>::ColsAtCompileTime,
SizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::RowsAtCompileTime,
internal::traits<Derived>::ColsAtCompileTime>::ret),
MaxRowsAtCompileTime = internal::traits<Derived>::MaxRowsAtCompileTime,
MaxColsAtCompileTime = internal::traits<Derived>::MaxColsAtCompileTime,
MaxSizeAtCompileTime = (internal::size_at_compile_time<internal::traits<Derived>::MaxRowsAtCompileTime,
internal::traits<Derived>::MaxColsAtCompileTime>::ret),
IsVectorAtCompileTime = internal::traits<Derived>::MaxRowsAtCompileTime == 1
|| internal::traits<Derived>::MaxColsAtCompileTime == 1
};
/** Default constructor */
SolverBase()
{}
~SolverBase()
{}
using Base::derived;
/** \returns an expression of the solution x of \f$ A x = b \f$ using the current decomposition of A.
*/
template<typename Rhs>
inline const Solve<Derived, Rhs>
solve(const MatrixBase<Rhs>& b) const
{
eigen_assert(derived().rows()==b.rows() && "solve(): invalid number of rows of the right hand side matrix b");
return Solve<Derived, Rhs>(derived(), b.derived());
}
/** \internal the return type of transpose() */
typedef typename internal::add_const<Transpose<const Derived> >::type ConstTransposeReturnType;
/** \returns an expression of the transposed of the factored matrix.
*
* A typical usage is to solve for the transposed problem A^T x = b:
* \code x = dec.transpose().solve(b); \endcode
*
* \sa adjoint(), solve()
*/
inline ConstTransposeReturnType transpose() const
{
return ConstTransposeReturnType(derived());
}
/** \internal the return type of adjoint() */
typedef typename internal::conditional<NumTraits<Scalar>::IsComplex,
CwiseUnaryOp<internal::scalar_conjugate_op<Scalar>, ConstTransposeReturnType>,
ConstTransposeReturnType
>::type AdjointReturnType;
/** \returns an expression of the adjoint of the factored matrix
*
* A typical usage is to solve for the adjoint problem A' x = b:
* \code x = dec.adjoint().solve(b); \endcode
*
* For real scalar types, this function is equivalent to transpose().
*
* \sa transpose(), solve()
*/
inline AdjointReturnType adjoint() const
{
return AdjointReturnType(derived().transpose());
}
protected:
};
namespace internal {
template<typename Derived>
struct generic_xpr_base<Derived, MatrixXpr, SolverStorage>
{
typedef SolverBase<Derived> type;
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_SOLVERBASE_H
| 4,365 | 32.328244 | 123 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Stride.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STRIDE_H
#define EIGEN_STRIDE_H
namespace Eigen {
/** \class Stride
* \ingroup Core_Module
*
* \brief Holds strides information for Map
*
* This class holds the strides information for mapping arrays with strides with class Map.
*
* It holds two values: the inner stride and the outer stride.
*
* The inner stride is the pointer increment between two consecutive entries within a given row of a
* row-major matrix or within a given column of a column-major matrix.
*
* The outer stride is the pointer increment between two consecutive rows of a row-major matrix or
* between two consecutive columns of a column-major matrix.
*
* These two values can be passed either at compile-time as template parameters, or at runtime as
* arguments to the constructor.
*
* Indeed, this class takes two template parameters:
* \tparam _OuterStrideAtCompileTime the outer stride, or Dynamic if you want to specify it at runtime.
* \tparam _InnerStrideAtCompileTime the inner stride, or Dynamic if you want to specify it at runtime.
*
* Here is an example:
* \include Map_general_stride.cpp
* Output: \verbinclude Map_general_stride.out
*
* \sa class InnerStride, class OuterStride, \ref TopicStorageOrders
*/
template<int _OuterStrideAtCompileTime, int _InnerStrideAtCompileTime>
class Stride
{
public:
typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
enum {
InnerStrideAtCompileTime = _InnerStrideAtCompileTime,
OuterStrideAtCompileTime = _OuterStrideAtCompileTime
};
/** Default constructor, for use when strides are fixed at compile time */
EIGEN_DEVICE_FUNC
Stride()
: m_outer(OuterStrideAtCompileTime), m_inner(InnerStrideAtCompileTime)
{
eigen_assert(InnerStrideAtCompileTime != Dynamic && OuterStrideAtCompileTime != Dynamic);
}
/** Constructor allowing to pass the strides at runtime */
EIGEN_DEVICE_FUNC
Stride(Index outerStride, Index innerStride)
: m_outer(outerStride), m_inner(innerStride)
{
eigen_assert(innerStride>=0 && outerStride>=0);
}
/** Copy constructor */
EIGEN_DEVICE_FUNC
Stride(const Stride& other)
: m_outer(other.outer()), m_inner(other.inner())
{}
/** \returns the outer stride */
EIGEN_DEVICE_FUNC
inline Index outer() const { return m_outer.value(); }
/** \returns the inner stride */
EIGEN_DEVICE_FUNC
inline Index inner() const { return m_inner.value(); }
protected:
internal::variable_if_dynamic<Index, OuterStrideAtCompileTime> m_outer;
internal::variable_if_dynamic<Index, InnerStrideAtCompileTime> m_inner;
};
/** \brief Convenience specialization of Stride to specify only an inner stride
* See class Map for some examples */
template<int Value>
class InnerStride : public Stride<0, Value>
{
typedef Stride<0, Value> Base;
public:
EIGEN_DEVICE_FUNC InnerStride() : Base() {}
EIGEN_DEVICE_FUNC InnerStride(Index v) : Base(0, v) {} // FIXME making this explicit could break valid code
};
/** \brief Convenience specialization of Stride to specify only an outer stride
* See class Map for some examples */
template<int Value>
class OuterStride : public Stride<Value, 0>
{
typedef Stride<Value, 0> Base;
public:
EIGEN_DEVICE_FUNC OuterStride() : Base() {}
EIGEN_DEVICE_FUNC OuterStride(Index v) : Base(v,0) {} // FIXME making this explicit could break valid code
};
} // end namespace Eigen
#endif // EIGEN_STRIDE_H
| 3,865 | 33.517857 | 111 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/Transpose.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
// Copyright (C) 2009-2014 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRANSPOSE_H
#define EIGEN_TRANSPOSE_H
namespace Eigen {
namespace internal {
template<typename MatrixType>
struct traits<Transpose<MatrixType> > : public traits<MatrixType>
{
typedef typename ref_selector<MatrixType>::type MatrixTypeNested;
typedef typename remove_reference<MatrixTypeNested>::type MatrixTypeNestedPlain;
enum {
RowsAtCompileTime = MatrixType::ColsAtCompileTime,
ColsAtCompileTime = MatrixType::RowsAtCompileTime,
MaxRowsAtCompileTime = MatrixType::MaxColsAtCompileTime,
MaxColsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
FlagsLvalueBit = is_lvalue<MatrixType>::value ? LvalueBit : 0,
Flags0 = traits<MatrixTypeNestedPlain>::Flags & ~(LvalueBit | NestByRefBit),
Flags1 = Flags0 | FlagsLvalueBit,
Flags = Flags1 ^ RowMajorBit,
InnerStrideAtCompileTime = inner_stride_at_compile_time<MatrixType>::ret,
OuterStrideAtCompileTime = outer_stride_at_compile_time<MatrixType>::ret
};
};
}
template<typename MatrixType, typename StorageKind> class TransposeImpl;
/** \class Transpose
* \ingroup Core_Module
*
* \brief Expression of the transpose of a matrix
*
* \tparam MatrixType the type of the object of which we are taking the transpose
*
* This class represents an expression of the transpose of a matrix.
* It is the return type of MatrixBase::transpose() and MatrixBase::adjoint()
* and most of the time this is the only way it is used.
*
* \sa MatrixBase::transpose(), MatrixBase::adjoint()
*/
template<typename MatrixType> class Transpose
: public TransposeImpl<MatrixType,typename internal::traits<MatrixType>::StorageKind>
{
public:
typedef typename internal::ref_selector<MatrixType>::non_const_type MatrixTypeNested;
typedef typename TransposeImpl<MatrixType,typename internal::traits<MatrixType>::StorageKind>::Base Base;
EIGEN_GENERIC_PUBLIC_INTERFACE(Transpose)
typedef typename internal::remove_all<MatrixType>::type NestedExpression;
EIGEN_DEVICE_FUNC
explicit inline Transpose(MatrixType& matrix) : m_matrix(matrix) {}
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Transpose)
EIGEN_DEVICE_FUNC inline Index rows() const { return m_matrix.cols(); }
EIGEN_DEVICE_FUNC inline Index cols() const { return m_matrix.rows(); }
/** \returns the nested expression */
EIGEN_DEVICE_FUNC
const typename internal::remove_all<MatrixTypeNested>::type&
nestedExpression() const { return m_matrix; }
/** \returns the nested expression */
EIGEN_DEVICE_FUNC
typename internal::remove_reference<MatrixTypeNested>::type&
nestedExpression() { return m_matrix; }
/** \internal */
void resize(Index nrows, Index ncols) {
m_matrix.resize(ncols,nrows);
}
protected:
typename internal::ref_selector<MatrixType>::non_const_type m_matrix;
};
namespace internal {
template<typename MatrixType, bool HasDirectAccess = has_direct_access<MatrixType>::ret>
struct TransposeImpl_base
{
typedef typename dense_xpr_base<Transpose<MatrixType> >::type type;
};
template<typename MatrixType>
struct TransposeImpl_base<MatrixType, false>
{
typedef typename dense_xpr_base<Transpose<MatrixType> >::type type;
};
} // end namespace internal
// Generic API dispatcher
template<typename XprType, typename StorageKind>
class TransposeImpl
: public internal::generic_xpr_base<Transpose<XprType> >::type
{
public:
typedef typename internal::generic_xpr_base<Transpose<XprType> >::type Base;
};
template<typename MatrixType> class TransposeImpl<MatrixType,Dense>
: public internal::TransposeImpl_base<MatrixType>::type
{
public:
typedef typename internal::TransposeImpl_base<MatrixType>::type Base;
using Base::coeffRef;
EIGEN_DENSE_PUBLIC_INTERFACE(Transpose<MatrixType>)
EIGEN_INHERIT_ASSIGNMENT_OPERATORS(TransposeImpl)
EIGEN_DEVICE_FUNC inline Index innerStride() const { return derived().nestedExpression().innerStride(); }
EIGEN_DEVICE_FUNC inline Index outerStride() const { return derived().nestedExpression().outerStride(); }
typedef typename internal::conditional<
internal::is_lvalue<MatrixType>::value,
Scalar,
const Scalar
>::type ScalarWithConstIfNotLvalue;
EIGEN_DEVICE_FUNC inline ScalarWithConstIfNotLvalue* data() { return derived().nestedExpression().data(); }
EIGEN_DEVICE_FUNC inline const Scalar* data() const { return derived().nestedExpression().data(); }
// FIXME: shall we keep the const version of coeffRef?
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index rowId, Index colId) const
{
return derived().nestedExpression().coeffRef(colId, rowId);
}
EIGEN_DEVICE_FUNC
inline const Scalar& coeffRef(Index index) const
{
return derived().nestedExpression().coeffRef(index);
}
};
/** \returns an expression of the transpose of *this.
*
* Example: \include MatrixBase_transpose.cpp
* Output: \verbinclude MatrixBase_transpose.out
*
* \warning If you want to replace a matrix by its own transpose, do \b NOT do this:
* \code
* m = m.transpose(); // bug!!! caused by aliasing effect
* \endcode
* Instead, use the transposeInPlace() method:
* \code
* m.transposeInPlace();
* \endcode
* which gives Eigen good opportunities for optimization, or alternatively you can also do:
* \code
* m = m.transpose().eval();
* \endcode
*
* \sa transposeInPlace(), adjoint() */
template<typename Derived>
inline Transpose<Derived>
DenseBase<Derived>::transpose()
{
return TransposeReturnType(derived());
}
/** This is the const version of transpose().
*
* Make sure you read the warning for transpose() !
*
* \sa transposeInPlace(), adjoint() */
template<typename Derived>
inline typename DenseBase<Derived>::ConstTransposeReturnType
DenseBase<Derived>::transpose() const
{
return ConstTransposeReturnType(derived());
}
/** \returns an expression of the adjoint (i.e. conjugate transpose) of *this.
*
* Example: \include MatrixBase_adjoint.cpp
* Output: \verbinclude MatrixBase_adjoint.out
*
* \warning If you want to replace a matrix by its own adjoint, do \b NOT do this:
* \code
* m = m.adjoint(); // bug!!! caused by aliasing effect
* \endcode
* Instead, use the adjointInPlace() method:
* \code
* m.adjointInPlace();
* \endcode
* which gives Eigen good opportunities for optimization, or alternatively you can also do:
* \code
* m = m.adjoint().eval();
* \endcode
*
* \sa adjointInPlace(), transpose(), conjugate(), class Transpose, class internal::scalar_conjugate_op */
template<typename Derived>
inline const typename MatrixBase<Derived>::AdjointReturnType
MatrixBase<Derived>::adjoint() const
{
return AdjointReturnType(this->transpose());
}
/***************************************************************************
* "in place" transpose implementation
***************************************************************************/
namespace internal {
template<typename MatrixType,
bool IsSquare = (MatrixType::RowsAtCompileTime == MatrixType::ColsAtCompileTime) && MatrixType::RowsAtCompileTime!=Dynamic,
bool MatchPacketSize =
(int(MatrixType::RowsAtCompileTime) == int(internal::packet_traits<typename MatrixType::Scalar>::size))
&& (internal::evaluator<MatrixType>::Flags&PacketAccessBit) >
struct inplace_transpose_selector;
template<typename MatrixType>
struct inplace_transpose_selector<MatrixType,true,false> { // square matrix
static void run(MatrixType& m) {
m.matrix().template triangularView<StrictlyUpper>().swap(m.matrix().transpose());
}
};
// TODO: vectorized path is currently limited to LargestPacketSize x LargestPacketSize cases only.
template<typename MatrixType>
struct inplace_transpose_selector<MatrixType,true,true> { // PacketSize x PacketSize
static void run(MatrixType& m) {
typedef typename MatrixType::Scalar Scalar;
typedef typename internal::packet_traits<typename MatrixType::Scalar>::type Packet;
const Index PacketSize = internal::packet_traits<Scalar>::size;
const Index Alignment = internal::evaluator<MatrixType>::Alignment;
PacketBlock<Packet> A;
for (Index i=0; i<PacketSize; ++i)
A.packet[i] = m.template packetByOuterInner<Alignment>(i,0);
internal::ptranspose(A);
for (Index i=0; i<PacketSize; ++i)
m.template writePacket<Alignment>(m.rowIndexByOuterInner(i,0), m.colIndexByOuterInner(i,0), A.packet[i]);
}
};
template<typename MatrixType,bool MatchPacketSize>
struct inplace_transpose_selector<MatrixType,false,MatchPacketSize> { // non square matrix
static void run(MatrixType& m) {
if (m.rows()==m.cols())
m.matrix().template triangularView<StrictlyUpper>().swap(m.matrix().transpose());
else
m = m.transpose().eval();
}
};
} // end namespace internal
/** This is the "in place" version of transpose(): it replaces \c *this by its own transpose.
* Thus, doing
* \code
* m.transposeInPlace();
* \endcode
* has the same effect on m as doing
* \code
* m = m.transpose().eval();
* \endcode
* and is faster and also safer because in the latter line of code, forgetting the eval() results
* in a bug caused by \ref TopicAliasing "aliasing".
*
* Notice however that this method is only useful if you want to replace a matrix by its own transpose.
* If you just need the transpose of a matrix, use transpose().
*
* \note if the matrix is not square, then \c *this must be a resizable matrix.
* This excludes (non-square) fixed-size matrices, block-expressions and maps.
*
* \sa transpose(), adjoint(), adjointInPlace() */
template<typename Derived>
inline void DenseBase<Derived>::transposeInPlace()
{
eigen_assert((rows() == cols() || (RowsAtCompileTime == Dynamic && ColsAtCompileTime == Dynamic))
&& "transposeInPlace() called on a non-square non-resizable matrix");
internal::inplace_transpose_selector<Derived>::run(derived());
}
/***************************************************************************
* "in place" adjoint implementation
***************************************************************************/
/** This is the "in place" version of adjoint(): it replaces \c *this by its own transpose.
* Thus, doing
* \code
* m.adjointInPlace();
* \endcode
* has the same effect on m as doing
* \code
* m = m.adjoint().eval();
* \endcode
* and is faster and also safer because in the latter line of code, forgetting the eval() results
* in a bug caused by aliasing.
*
* Notice however that this method is only useful if you want to replace a matrix by its own adjoint.
* If you just need the adjoint of a matrix, use adjoint().
*
* \note if the matrix is not square, then \c *this must be a resizable matrix.
* This excludes (non-square) fixed-size matrices, block-expressions and maps.
*
* \sa transpose(), adjoint(), transposeInPlace() */
template<typename Derived>
inline void MatrixBase<Derived>::adjointInPlace()
{
derived() = adjoint().eval();
}
#ifndef EIGEN_NO_DEBUG
// The following is to detect aliasing problems in most common cases.
namespace internal {
template<bool DestIsTransposed, typename OtherDerived>
struct check_transpose_aliasing_compile_time_selector
{
enum { ret = bool(blas_traits<OtherDerived>::IsTransposed) != DestIsTransposed };
};
template<bool DestIsTransposed, typename BinOp, typename DerivedA, typename DerivedB>
struct check_transpose_aliasing_compile_time_selector<DestIsTransposed,CwiseBinaryOp<BinOp,DerivedA,DerivedB> >
{
enum { ret = bool(blas_traits<DerivedA>::IsTransposed) != DestIsTransposed
|| bool(blas_traits<DerivedB>::IsTransposed) != DestIsTransposed
};
};
template<typename Scalar, bool DestIsTransposed, typename OtherDerived>
struct check_transpose_aliasing_run_time_selector
{
static bool run(const Scalar* dest, const OtherDerived& src)
{
return (bool(blas_traits<OtherDerived>::IsTransposed) != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src));
}
};
template<typename Scalar, bool DestIsTransposed, typename BinOp, typename DerivedA, typename DerivedB>
struct check_transpose_aliasing_run_time_selector<Scalar,DestIsTransposed,CwiseBinaryOp<BinOp,DerivedA,DerivedB> >
{
static bool run(const Scalar* dest, const CwiseBinaryOp<BinOp,DerivedA,DerivedB>& src)
{
return ((blas_traits<DerivedA>::IsTransposed != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src.lhs())))
|| ((blas_traits<DerivedB>::IsTransposed != DestIsTransposed) && (dest!=0 && dest==(const Scalar*)extract_data(src.rhs())));
}
};
// the following selector, checkTransposeAliasing_impl, based on MightHaveTransposeAliasing,
// is because when the condition controlling the assert is known at compile time, ICC emits a warning.
// This is actually a good warning: in expressions that don't have any transposing, the condition is
// known at compile time to be false, and using that, we can avoid generating the code of the assert again
// and again for all these expressions that don't need it.
template<typename Derived, typename OtherDerived,
bool MightHaveTransposeAliasing
= check_transpose_aliasing_compile_time_selector
<blas_traits<Derived>::IsTransposed,OtherDerived>::ret
>
struct checkTransposeAliasing_impl
{
static void run(const Derived& dst, const OtherDerived& other)
{
eigen_assert((!check_transpose_aliasing_run_time_selector
<typename Derived::Scalar,blas_traits<Derived>::IsTransposed,OtherDerived>
::run(extract_data(dst), other))
&& "aliasing detected during transposition, use transposeInPlace() "
"or evaluate the rhs into a temporary using .eval()");
}
};
template<typename Derived, typename OtherDerived>
struct checkTransposeAliasing_impl<Derived, OtherDerived, false>
{
static void run(const Derived&, const OtherDerived&)
{
}
};
template<typename Dst, typename Src>
void check_for_aliasing(const Dst &dst, const Src &src)
{
internal::checkTransposeAliasing_impl<Dst, Src>::run(dst, src);
}
} // end namespace internal
#endif // EIGEN_NO_DEBUG
} // end namespace Eigen
#endif // EIGEN_TRANSPOSE_H
| 14,777 | 35.579208 | 134 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/VectorBlock.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_VECTORBLOCK_H
#define EIGEN_VECTORBLOCK_H
namespace Eigen {
namespace internal {
template<typename VectorType, int Size>
struct traits<VectorBlock<VectorType, Size> >
: public traits<Block<VectorType,
traits<VectorType>::Flags & RowMajorBit ? 1 : Size,
traits<VectorType>::Flags & RowMajorBit ? Size : 1> >
{
};
}
/** \class VectorBlock
* \ingroup Core_Module
*
* \brief Expression of a fixed-size or dynamic-size sub-vector
*
* \tparam VectorType the type of the object in which we are taking a sub-vector
* \tparam Size size of the sub-vector we are taking at compile time (optional)
*
* This class represents an expression of either a fixed-size or dynamic-size sub-vector.
* It is the return type of DenseBase::segment(Index,Index) and DenseBase::segment<int>(Index) and
* most of the time this is the only way it is used.
*
* However, if you want to directly maniputate sub-vector expressions,
* for instance if you want to write a function returning such an expression, you
* will need to use this class.
*
* Here is an example illustrating the dynamic case:
* \include class_VectorBlock.cpp
* Output: \verbinclude class_VectorBlock.out
*
* \note Even though this expression has dynamic size, in the case where \a VectorType
* has fixed size, this expression inherits a fixed maximal size which means that evaluating
* it does not cause a dynamic memory allocation.
*
* Here is an example illustrating the fixed-size case:
* \include class_FixedVectorBlock.cpp
* Output: \verbinclude class_FixedVectorBlock.out
*
* \sa class Block, DenseBase::segment(Index,Index,Index,Index), DenseBase::segment(Index,Index)
*/
template<typename VectorType, int Size> class VectorBlock
: public Block<VectorType,
internal::traits<VectorType>::Flags & RowMajorBit ? 1 : Size,
internal::traits<VectorType>::Flags & RowMajorBit ? Size : 1>
{
typedef Block<VectorType,
internal::traits<VectorType>::Flags & RowMajorBit ? 1 : Size,
internal::traits<VectorType>::Flags & RowMajorBit ? Size : 1> Base;
enum {
IsColVector = !(internal::traits<VectorType>::Flags & RowMajorBit)
};
public:
EIGEN_DENSE_PUBLIC_INTERFACE(VectorBlock)
using Base::operator=;
/** Dynamic-size constructor
*/
EIGEN_DEVICE_FUNC
inline VectorBlock(VectorType& vector, Index start, Index size)
: Base(vector,
IsColVector ? start : 0, IsColVector ? 0 : start,
IsColVector ? size : 1, IsColVector ? 1 : size)
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorBlock);
}
/** Fixed-size constructor
*/
EIGEN_DEVICE_FUNC
inline VectorBlock(VectorType& vector, Index start)
: Base(vector, IsColVector ? start : 0, IsColVector ? 0 : start)
{
EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorBlock);
}
};
} // end namespace Eigen
#endif // EIGEN_VECTORBLOCK_H
| 3,462 | 34.701031 | 99 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/AVX/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Pedro Gonnet ([email protected])
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATH_FUNCTIONS_AVX_H
#define EIGEN_MATH_FUNCTIONS_AVX_H
/* The sin, cos, exp, and log functions of this file are loosely derived from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
*/
namespace Eigen {
namespace internal {
inline Packet8i pshiftleft(Packet8i v, int n)
{
#ifdef EIGEN_VECTORIZE_AVX2
return _mm256_slli_epi32(v, n);
#else
__m128i lo = _mm_slli_epi32(_mm256_extractf128_si256(v, 0), n);
__m128i hi = _mm_slli_epi32(_mm256_extractf128_si256(v, 1), n);
return _mm256_insertf128_si256(_mm256_castsi128_si256(lo), (hi), 1);
#endif
}
inline Packet8f pshiftright(Packet8f v, int n)
{
#ifdef EIGEN_VECTORIZE_AVX2
return _mm256_cvtepi32_ps(_mm256_srli_epi32(_mm256_castps_si256(v), n));
#else
__m128i lo = _mm_srli_epi32(_mm256_extractf128_si256(_mm256_castps_si256(v), 0), n);
__m128i hi = _mm_srli_epi32(_mm256_extractf128_si256(_mm256_castps_si256(v), 1), n);
return _mm256_cvtepi32_ps(_mm256_insertf128_si256(_mm256_castsi128_si256(lo), (hi), 1));
#endif
}
// Sine function
// Computes sin(x) by wrapping x to the interval [-Pi/4,3*Pi/4] and
// evaluating interpolants in [-Pi/4,Pi/4] or [Pi/4,3*Pi/4]. The interpolants
// are (anti-)symmetric and thus have only odd/even coefficients
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8f
psin<Packet8f>(const Packet8f& _x) {
Packet8f x = _x;
// Some useful values.
_EIGEN_DECLARE_CONST_Packet8i(one, 1);
_EIGEN_DECLARE_CONST_Packet8f(one, 1.0f);
_EIGEN_DECLARE_CONST_Packet8f(two, 2.0f);
_EIGEN_DECLARE_CONST_Packet8f(one_over_four, 0.25f);
_EIGEN_DECLARE_CONST_Packet8f(one_over_pi, 3.183098861837907e-01f);
_EIGEN_DECLARE_CONST_Packet8f(neg_pi_first, -3.140625000000000e+00f);
_EIGEN_DECLARE_CONST_Packet8f(neg_pi_second, -9.670257568359375e-04f);
_EIGEN_DECLARE_CONST_Packet8f(neg_pi_third, -6.278329571784980e-07f);
_EIGEN_DECLARE_CONST_Packet8f(four_over_pi, 1.273239544735163e+00f);
// Map x from [-Pi/4,3*Pi/4] to z in [-1,3] and subtract the shifted period.
Packet8f z = pmul(x, p8f_one_over_pi);
Packet8f shift = _mm256_floor_ps(padd(z, p8f_one_over_four));
x = pmadd(shift, p8f_neg_pi_first, x);
x = pmadd(shift, p8f_neg_pi_second, x);
x = pmadd(shift, p8f_neg_pi_third, x);
z = pmul(x, p8f_four_over_pi);
// Make a mask for the entries that need flipping, i.e. wherever the shift
// is odd.
Packet8i shift_ints = _mm256_cvtps_epi32(shift);
Packet8i shift_isodd = _mm256_castps_si256(_mm256_and_ps(_mm256_castsi256_ps(shift_ints), _mm256_castsi256_ps(p8i_one)));
Packet8i sign_flip_mask = pshiftleft(shift_isodd, 31);
// Create a mask for which interpolant to use, i.e. if z > 1, then the mask
// is set to ones for that entry.
Packet8f ival_mask = _mm256_cmp_ps(z, p8f_one, _CMP_GT_OQ);
// Evaluate the polynomial for the interval [1,3] in z.
_EIGEN_DECLARE_CONST_Packet8f(coeff_right_0, 9.999999724233232e-01f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_right_2, -3.084242535619928e-01f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_right_4, 1.584991525700324e-02f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_right_6, -3.188805084631342e-04f);
Packet8f z_minus_two = psub(z, p8f_two);
Packet8f z_minus_two2 = pmul(z_minus_two, z_minus_two);
Packet8f right = pmadd(p8f_coeff_right_6, z_minus_two2, p8f_coeff_right_4);
right = pmadd(right, z_minus_two2, p8f_coeff_right_2);
right = pmadd(right, z_minus_two2, p8f_coeff_right_0);
// Evaluate the polynomial for the interval [-1,1] in z.
_EIGEN_DECLARE_CONST_Packet8f(coeff_left_1, 7.853981525427295e-01f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_left_3, -8.074536727092352e-02f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_left_5, 2.489871967827018e-03f);
_EIGEN_DECLARE_CONST_Packet8f(coeff_left_7, -3.587725841214251e-05f);
Packet8f z2 = pmul(z, z);
Packet8f left = pmadd(p8f_coeff_left_7, z2, p8f_coeff_left_5);
left = pmadd(left, z2, p8f_coeff_left_3);
left = pmadd(left, z2, p8f_coeff_left_1);
left = pmul(left, z);
// Assemble the results, i.e. select the left and right polynomials.
left = _mm256_andnot_ps(ival_mask, left);
right = _mm256_and_ps(ival_mask, right);
Packet8f res = _mm256_or_ps(left, right);
// Flip the sign on the odd intervals and return the result.
res = _mm256_xor_ps(res, _mm256_castsi256_ps(sign_flip_mask));
return res;
}
// Natural logarithm
// Computes log(x) as log(2^e * m) = C*e + log(m), where the constant C =log(2)
// and m is in the range [sqrt(1/2),sqrt(2)). In this range, the logarithm can
// be easily approximated by a polynomial centered on m=1 for stability.
// TODO(gonnet): Further reduce the interval allowing for lower-degree
// polynomial interpolants -> ... -> profit!
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8f
plog<Packet8f>(const Packet8f& _x) {
Packet8f x = _x;
_EIGEN_DECLARE_CONST_Packet8f(1, 1.0f);
_EIGEN_DECLARE_CONST_Packet8f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet8f(126f, 126.0f);
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(inv_mant_mask, ~0x7f800000);
// The smallest non denormalized float number.
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(min_norm_pos, 0x00800000);
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(minus_inf, 0xff800000);
// Polynomial coefficients.
_EIGEN_DECLARE_CONST_Packet8f(cephes_SQRTHF, 0.707106781186547524f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p0, 7.0376836292E-2f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p1, -1.1514610310E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p2, 1.1676998740E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p3, -1.2420140846E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p4, +1.4249322787E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p5, -1.6668057665E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p6, +2.0000714765E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p7, -2.4999993993E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_p8, +3.3333331174E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_q1, -2.12194440e-4f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_log_q2, 0.693359375f);
Packet8f invalid_mask = _mm256_cmp_ps(x, _mm256_setzero_ps(), _CMP_NGE_UQ); // not greater equal is true if x is NaN
Packet8f iszero_mask = _mm256_cmp_ps(x, _mm256_setzero_ps(), _CMP_EQ_OQ);
// Truncate input values to the minimum positive normal.
x = pmax(x, p8f_min_norm_pos);
Packet8f emm0 = pshiftright(x,23);
Packet8f e = _mm256_sub_ps(emm0, p8f_126f);
// Set the exponents to -1, i.e. x are in the range [0.5,1).
x = _mm256_and_ps(x, p8f_inv_mant_mask);
x = _mm256_or_ps(x, p8f_half);
// part2: Shift the inputs from the range [0.5,1) to [sqrt(1/2),sqrt(2))
// and shift by -1. The values are then centered around 0, which improves
// the stability of the polynomial evaluation.
// if( x < SQRTHF ) {
// e -= 1;
// x = x + x - 1.0;
// } else { x = x - 1.0; }
Packet8f mask = _mm256_cmp_ps(x, p8f_cephes_SQRTHF, _CMP_LT_OQ);
Packet8f tmp = _mm256_and_ps(x, mask);
x = psub(x, p8f_1);
e = psub(e, _mm256_and_ps(p8f_1, mask));
x = padd(x, tmp);
Packet8f x2 = pmul(x, x);
Packet8f x3 = pmul(x2, x);
// Evaluate the polynomial approximant of degree 8 in three parts, probably
// to improve instruction-level parallelism.
Packet8f y, y1, y2;
y = pmadd(p8f_cephes_log_p0, x, p8f_cephes_log_p1);
y1 = pmadd(p8f_cephes_log_p3, x, p8f_cephes_log_p4);
y2 = pmadd(p8f_cephes_log_p6, x, p8f_cephes_log_p7);
y = pmadd(y, x, p8f_cephes_log_p2);
y1 = pmadd(y1, x, p8f_cephes_log_p5);
y2 = pmadd(y2, x, p8f_cephes_log_p8);
y = pmadd(y, x3, y1);
y = pmadd(y, x3, y2);
y = pmul(y, x3);
// Add the logarithm of the exponent back to the result of the interpolation.
y1 = pmul(e, p8f_cephes_log_q1);
tmp = pmul(x2, p8f_half);
y = padd(y, y1);
x = psub(x, tmp);
y2 = pmul(e, p8f_cephes_log_q2);
x = padd(x, y);
x = padd(x, y2);
// Filter out invalid inputs, i.e. negative arg will be NAN, 0 will be -INF.
return _mm256_or_ps(
_mm256_andnot_ps(iszero_mask, _mm256_or_ps(x, invalid_mask)),
_mm256_and_ps(iszero_mask, p8f_minus_inf));
}
// Exponential function. Works by writing "x = m*log(2) + r" where
// "m = floor(x/log(2)+1/2)" and "r" is the remainder. The result is then
// "exp(x) = 2^m*exp(r)" where exp(r) is in the range [-1,1).
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8f
pexp<Packet8f>(const Packet8f& _x) {
_EIGEN_DECLARE_CONST_Packet8f(1, 1.0f);
_EIGEN_DECLARE_CONST_Packet8f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet8f(127, 127.0f);
_EIGEN_DECLARE_CONST_Packet8f(exp_hi, 88.3762626647950f);
_EIGEN_DECLARE_CONST_Packet8f(exp_lo, -88.3762626647949f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_LOG2EF, 1.44269504088896341f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p0, 1.9875691500E-4f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p1, 1.3981999507E-3f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p2, 8.3334519073E-3f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p3, 4.1665795894E-2f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p4, 1.6666665459E-1f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_p5, 5.0000001201E-1f);
// Clamp x.
Packet8f x = pmax(pmin(_x, p8f_exp_hi), p8f_exp_lo);
// Express exp(x) as exp(m*ln(2) + r), start by extracting
// m = floor(x/ln(2) + 0.5).
Packet8f m = _mm256_floor_ps(pmadd(x, p8f_cephes_LOG2EF, p8f_half));
// Get r = x - m*ln(2). If no FMA instructions are available, m*ln(2) is
// subtracted out in two parts, m*C1+m*C2 = m*ln(2), to avoid accumulating
// truncation errors. Note that we don't use the "pmadd" function here to
// ensure that a precision-preserving FMA instruction is used.
#ifdef EIGEN_VECTORIZE_FMA
_EIGEN_DECLARE_CONST_Packet8f(nln2, -0.6931471805599453f);
Packet8f r = _mm256_fmadd_ps(m, p8f_nln2, x);
#else
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_C1, 0.693359375f);
_EIGEN_DECLARE_CONST_Packet8f(cephes_exp_C2, -2.12194440e-4f);
Packet8f r = psub(x, pmul(m, p8f_cephes_exp_C1));
r = psub(r, pmul(m, p8f_cephes_exp_C2));
#endif
Packet8f r2 = pmul(r, r);
// TODO(gonnet): Split into odd/even polynomials and try to exploit
// instruction-level parallelism.
Packet8f y = p8f_cephes_exp_p0;
y = pmadd(y, r, p8f_cephes_exp_p1);
y = pmadd(y, r, p8f_cephes_exp_p2);
y = pmadd(y, r, p8f_cephes_exp_p3);
y = pmadd(y, r, p8f_cephes_exp_p4);
y = pmadd(y, r, p8f_cephes_exp_p5);
y = pmadd(y, r2, r);
y = padd(y, p8f_1);
// Build emm0 = 2^m.
Packet8i emm0 = _mm256_cvttps_epi32(padd(m, p8f_127));
emm0 = pshiftleft(emm0, 23);
// Return 2^m * exp(r).
return pmax(pmul(y, _mm256_castsi256_ps(emm0)), _x);
}
// Hyperbolic Tangent function.
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8f
ptanh<Packet8f>(const Packet8f& x) {
return internal::generic_fast_tanh_float(x);
}
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet4d
pexp<Packet4d>(const Packet4d& _x) {
Packet4d x = _x;
_EIGEN_DECLARE_CONST_Packet4d(1, 1.0);
_EIGEN_DECLARE_CONST_Packet4d(2, 2.0);
_EIGEN_DECLARE_CONST_Packet4d(half, 0.5);
_EIGEN_DECLARE_CONST_Packet4d(exp_hi, 709.437);
_EIGEN_DECLARE_CONST_Packet4d(exp_lo, -709.436139303);
_EIGEN_DECLARE_CONST_Packet4d(cephes_LOG2EF, 1.4426950408889634073599);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_p0, 1.26177193074810590878e-4);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_p1, 3.02994407707441961300e-2);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_p2, 9.99999999999999999910e-1);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_q0, 3.00198505138664455042e-6);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_q1, 2.52448340349684104192e-3);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_q2, 2.27265548208155028766e-1);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_q3, 2.00000000000000000009e0);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_C1, 0.693145751953125);
_EIGEN_DECLARE_CONST_Packet4d(cephes_exp_C2, 1.42860682030941723212e-6);
_EIGEN_DECLARE_CONST_Packet4i(1023, 1023);
Packet4d tmp, fx;
// clamp x
x = pmax(pmin(x, p4d_exp_hi), p4d_exp_lo);
// Express exp(x) as exp(g + n*log(2)).
fx = pmadd(p4d_cephes_LOG2EF, x, p4d_half);
// Get the integer modulus of log(2), i.e. the "n" described above.
fx = _mm256_floor_pd(fx);
// Get the remainder modulo log(2), i.e. the "g" described above. Subtract
// n*log(2) out in two steps, i.e. n*C1 + n*C2, C1+C2=log2 to get the last
// digits right.
tmp = pmul(fx, p4d_cephes_exp_C1);
Packet4d z = pmul(fx, p4d_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
Packet4d x2 = pmul(x, x);
// Evaluate the numerator polynomial of the rational interpolant.
Packet4d px = p4d_cephes_exp_p0;
px = pmadd(px, x2, p4d_cephes_exp_p1);
px = pmadd(px, x2, p4d_cephes_exp_p2);
px = pmul(px, x);
// Evaluate the denominator polynomial of the rational interpolant.
Packet4d qx = p4d_cephes_exp_q0;
qx = pmadd(qx, x2, p4d_cephes_exp_q1);
qx = pmadd(qx, x2, p4d_cephes_exp_q2);
qx = pmadd(qx, x2, p4d_cephes_exp_q3);
// I don't really get this bit, copied from the SSE2 routines, so...
// TODO(gonnet): Figure out what is going on here, perhaps find a better
// rational interpolant?
x = _mm256_div_pd(px, psub(qx, px));
x = pmadd(p4d_2, x, p4d_1);
// Build e=2^n by constructing the exponents in a 128-bit vector and
// shifting them to where they belong in double-precision values.
__m128i emm0 = _mm256_cvtpd_epi32(fx);
emm0 = _mm_add_epi32(emm0, p4i_1023);
emm0 = _mm_shuffle_epi32(emm0, _MM_SHUFFLE(3, 1, 2, 0));
__m128i lo = _mm_slli_epi64(emm0, 52);
__m128i hi = _mm_slli_epi64(_mm_srli_epi64(emm0, 32), 52);
__m256i e = _mm256_insertf128_si256(_mm256_setzero_si256(), lo, 0);
e = _mm256_insertf128_si256(e, hi, 1);
// Construct the result 2^n * exp(g) = e * x. The max is used to catch
// non-finite values in the input.
return pmax(pmul(x, _mm256_castsi256_pd(e)), _x);
}
// Functions for sqrt.
// The EIGEN_FAST_MATH version uses the _mm_rsqrt_ps approximation and one step
// of Newton's method, at a cost of 1-2 bits of precision as opposed to the
// exact solution. It does not handle +inf, or denormalized numbers correctly.
// The main advantage of this approach is not just speed, but also the fact that
// it can be inlined and pipelined with other computations, further reducing its
// effective latency. This is similar to Quake3's fast inverse square root.
// For detail see here: http://www.beyond3d.com/content/articles/8/
#if EIGEN_FAST_MATH
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8f
psqrt<Packet8f>(const Packet8f& _x) {
Packet8f half = pmul(_x, pset1<Packet8f>(.5f));
Packet8f denormal_mask = _mm256_and_ps(
_mm256_cmp_ps(_x, pset1<Packet8f>((std::numeric_limits<float>::min)()),
_CMP_LT_OQ),
_mm256_cmp_ps(_x, _mm256_setzero_ps(), _CMP_GE_OQ));
// Compute approximate reciprocal sqrt.
Packet8f x = _mm256_rsqrt_ps(_x);
// Do a single step of Newton's iteration.
x = pmul(x, psub(pset1<Packet8f>(1.5f), pmul(half, pmul(x,x))));
// Flush results for denormals to zero.
return _mm256_andnot_ps(denormal_mask, pmul(_x,x));
}
#else
template <> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet8f psqrt<Packet8f>(const Packet8f& x) {
return _mm256_sqrt_ps(x);
}
#endif
template <> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4d psqrt<Packet4d>(const Packet4d& x) {
return _mm256_sqrt_pd(x);
}
#if EIGEN_FAST_MATH
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet8f prsqrt<Packet8f>(const Packet8f& _x) {
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(inf, 0x7f800000);
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(nan, 0x7fc00000);
_EIGEN_DECLARE_CONST_Packet8f(one_point_five, 1.5f);
_EIGEN_DECLARE_CONST_Packet8f(minus_half, -0.5f);
_EIGEN_DECLARE_CONST_Packet8f_FROM_INT(flt_min, 0x00800000);
Packet8f neg_half = pmul(_x, p8f_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
Packet8f le_zero_mask = _mm256_cmp_ps(_x, p8f_flt_min, _CMP_LT_OQ);
Packet8f x = _mm256_andnot_ps(le_zero_mask, _mm256_rsqrt_ps(_x));
// Fill in NaNs and Infs for the negative/zero entries.
Packet8f neg_mask = _mm256_cmp_ps(_x, _mm256_setzero_ps(), _CMP_LT_OQ);
Packet8f zero_mask = _mm256_andnot_ps(neg_mask, le_zero_mask);
Packet8f infs_and_nans = _mm256_or_ps(_mm256_and_ps(neg_mask, p8f_nan),
_mm256_and_ps(zero_mask, p8f_inf));
// Do a single step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p8f_one_point_five));
// Insert NaNs and Infs in all the right places.
return _mm256_or_ps(x, infs_and_nans);
}
#else
template <> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet8f prsqrt<Packet8f>(const Packet8f& x) {
_EIGEN_DECLARE_CONST_Packet8f(one, 1.0f);
return _mm256_div_ps(p8f_one, _mm256_sqrt_ps(x));
}
#endif
template <> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4d prsqrt<Packet4d>(const Packet4d& x) {
_EIGEN_DECLARE_CONST_Packet4d(one, 1.0);
return _mm256_div_pd(p4d_one, _mm256_sqrt_pd(x));
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_AVX_H
| 17,776 | 39.402273 | 123 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/AVX/TypeCasting.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TYPE_CASTING_AVX_H
#define EIGEN_TYPE_CASTING_AVX_H
namespace Eigen {
namespace internal {
// For now we use SSE to handle integers, so we can't use AVX instructions to cast
// from int to float
template <>
struct type_casting_traits<float, int> {
enum {
VectorizedCast = 0,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template <>
struct type_casting_traits<int, float> {
enum {
VectorizedCast = 0,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet8i pcast<Packet8f, Packet8i>(const Packet8f& a) {
return _mm256_cvtps_epi32(a);
}
template<> EIGEN_STRONG_INLINE Packet8f pcast<Packet8i, Packet8f>(const Packet8i& a) {
return _mm256_cvtepi32_ps(a);
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TYPE_CASTING_AVX_H
| 1,194 | 21.980769 | 86 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/AVX512/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Pedro Gonnet ([email protected])
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef THIRD_PARTY_EIGEN3_EIGEN_SRC_CORE_ARCH_AVX512_MATHFUNCTIONS_H_
#define THIRD_PARTY_EIGEN3_EIGEN_SRC_CORE_ARCH_AVX512_MATHFUNCTIONS_H_
namespace Eigen {
namespace internal {
// Disable the code for older versions of gcc that don't support many of the required avx512 instrinsics.
#if EIGEN_GNUC_AT_LEAST(5, 3)
#define _EIGEN_DECLARE_CONST_Packet16f(NAME, X) \
const Packet16f p16f_##NAME = pset1<Packet16f>(X)
#define _EIGEN_DECLARE_CONST_Packet16f_FROM_INT(NAME, X) \
const Packet16f p16f_##NAME = (__m512)pset1<Packet16i>(X)
#define _EIGEN_DECLARE_CONST_Packet8d(NAME, X) \
const Packet8d p8d_##NAME = pset1<Packet8d>(X)
#define _EIGEN_DECLARE_CONST_Packet8d_FROM_INT64(NAME, X) \
const Packet8d p8d_##NAME = _mm512_castsi512_pd(_mm512_set1_epi64(X))
// Natural logarithm
// Computes log(x) as log(2^e * m) = C*e + log(m), where the constant C =log(2)
// and m is in the range [sqrt(1/2),sqrt(2)). In this range, the logarithm can
// be easily approximated by a polynomial centered on m=1 for stability.
#if defined(EIGEN_VECTORIZE_AVX512DQ)
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet16f
plog<Packet16f>(const Packet16f& _x) {
Packet16f x = _x;
_EIGEN_DECLARE_CONST_Packet16f(1, 1.0f);
_EIGEN_DECLARE_CONST_Packet16f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet16f(126f, 126.0f);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(inv_mant_mask, ~0x7f800000);
// The smallest non denormalized float number.
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(min_norm_pos, 0x00800000);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(minus_inf, 0xff800000);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(nan, 0x7fc00000);
// Polynomial coefficients.
_EIGEN_DECLARE_CONST_Packet16f(cephes_SQRTHF, 0.707106781186547524f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p0, 7.0376836292E-2f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p1, -1.1514610310E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p2, 1.1676998740E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p3, -1.2420140846E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p4, +1.4249322787E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p5, -1.6668057665E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p6, +2.0000714765E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p7, -2.4999993993E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_p8, +3.3333331174E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_q1, -2.12194440e-4f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_log_q2, 0.693359375f);
// invalid_mask is set to true when x is NaN
__mmask16 invalid_mask =
_mm512_cmp_ps_mask(x, _mm512_setzero_ps(), _CMP_NGE_UQ);
__mmask16 iszero_mask =
_mm512_cmp_ps_mask(x, _mm512_setzero_ps(), _CMP_EQ_UQ);
// Truncate input values to the minimum positive normal.
x = pmax(x, p16f_min_norm_pos);
// Extract the shifted exponents.
Packet16f emm0 = _mm512_cvtepi32_ps(_mm512_srli_epi32((__m512i)x, 23));
Packet16f e = _mm512_sub_ps(emm0, p16f_126f);
// Set the exponents to -1, i.e. x are in the range [0.5,1).
x = _mm512_and_ps(x, p16f_inv_mant_mask);
x = _mm512_or_ps(x, p16f_half);
// part2: Shift the inputs from the range [0.5,1) to [sqrt(1/2),sqrt(2))
// and shift by -1. The values are then centered around 0, which improves
// the stability of the polynomial evaluation.
// if( x < SQRTHF ) {
// e -= 1;
// x = x + x - 1.0;
// } else { x = x - 1.0; }
__mmask16 mask = _mm512_cmp_ps_mask(x, p16f_cephes_SQRTHF, _CMP_LT_OQ);
Packet16f tmp = _mm512_mask_blend_ps(mask, _mm512_setzero_ps(), x);
x = psub(x, p16f_1);
e = psub(e, _mm512_mask_blend_ps(mask, _mm512_setzero_ps(), p16f_1));
x = padd(x, tmp);
Packet16f x2 = pmul(x, x);
Packet16f x3 = pmul(x2, x);
// Evaluate the polynomial approximant of degree 8 in three parts, probably
// to improve instruction-level parallelism.
Packet16f y, y1, y2;
y = pmadd(p16f_cephes_log_p0, x, p16f_cephes_log_p1);
y1 = pmadd(p16f_cephes_log_p3, x, p16f_cephes_log_p4);
y2 = pmadd(p16f_cephes_log_p6, x, p16f_cephes_log_p7);
y = pmadd(y, x, p16f_cephes_log_p2);
y1 = pmadd(y1, x, p16f_cephes_log_p5);
y2 = pmadd(y2, x, p16f_cephes_log_p8);
y = pmadd(y, x3, y1);
y = pmadd(y, x3, y2);
y = pmul(y, x3);
// Add the logarithm of the exponent back to the result of the interpolation.
y1 = pmul(e, p16f_cephes_log_q1);
tmp = pmul(x2, p16f_half);
y = padd(y, y1);
x = psub(x, tmp);
y2 = pmul(e, p16f_cephes_log_q2);
x = padd(x, y);
x = padd(x, y2);
// Filter out invalid inputs, i.e. negative arg will be NAN, 0 will be -INF.
return _mm512_mask_blend_ps(iszero_mask,
_mm512_mask_blend_ps(invalid_mask, x, p16f_nan),
p16f_minus_inf);
}
#endif
// Exponential function. Works by writing "x = m*log(2) + r" where
// "m = floor(x/log(2)+1/2)" and "r" is the remainder. The result is then
// "exp(x) = 2^m*exp(r)" where exp(r) is in the range [-1,1).
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet16f
pexp<Packet16f>(const Packet16f& _x) {
_EIGEN_DECLARE_CONST_Packet16f(1, 1.0f);
_EIGEN_DECLARE_CONST_Packet16f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet16f(127, 127.0f);
_EIGEN_DECLARE_CONST_Packet16f(exp_hi, 88.3762626647950f);
_EIGEN_DECLARE_CONST_Packet16f(exp_lo, -88.3762626647949f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_LOG2EF, 1.44269504088896341f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p0, 1.9875691500E-4f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p1, 1.3981999507E-3f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p2, 8.3334519073E-3f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p3, 4.1665795894E-2f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p4, 1.6666665459E-1f);
_EIGEN_DECLARE_CONST_Packet16f(cephes_exp_p5, 5.0000001201E-1f);
// Clamp x.
Packet16f x = pmax(pmin(_x, p16f_exp_hi), p16f_exp_lo);
// Express exp(x) as exp(m*ln(2) + r), start by extracting
// m = floor(x/ln(2) + 0.5).
Packet16f m = _mm512_floor_ps(pmadd(x, p16f_cephes_LOG2EF, p16f_half));
// Get r = x - m*ln(2). Note that we can do this without losing more than one
// ulp precision due to the FMA instruction.
_EIGEN_DECLARE_CONST_Packet16f(nln2, -0.6931471805599453f);
Packet16f r = _mm512_fmadd_ps(m, p16f_nln2, x);
Packet16f r2 = pmul(r, r);
// TODO(gonnet): Split into odd/even polynomials and try to exploit
// instruction-level parallelism.
Packet16f y = p16f_cephes_exp_p0;
y = pmadd(y, r, p16f_cephes_exp_p1);
y = pmadd(y, r, p16f_cephes_exp_p2);
y = pmadd(y, r, p16f_cephes_exp_p3);
y = pmadd(y, r, p16f_cephes_exp_p4);
y = pmadd(y, r, p16f_cephes_exp_p5);
y = pmadd(y, r2, r);
y = padd(y, p16f_1);
// Build emm0 = 2^m.
Packet16i emm0 = _mm512_cvttps_epi32(padd(m, p16f_127));
emm0 = _mm512_slli_epi32(emm0, 23);
// Return 2^m * exp(r).
return pmax(pmul(y, _mm512_castsi512_ps(emm0)), _x);
}
/*template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8d
pexp<Packet8d>(const Packet8d& _x) {
Packet8d x = _x;
_EIGEN_DECLARE_CONST_Packet8d(1, 1.0);
_EIGEN_DECLARE_CONST_Packet8d(2, 2.0);
_EIGEN_DECLARE_CONST_Packet8d(exp_hi, 709.437);
_EIGEN_DECLARE_CONST_Packet8d(exp_lo, -709.436139303);
_EIGEN_DECLARE_CONST_Packet8d(cephes_LOG2EF, 1.4426950408889634073599);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_p0, 1.26177193074810590878e-4);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_p1, 3.02994407707441961300e-2);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_p2, 9.99999999999999999910e-1);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_q0, 3.00198505138664455042e-6);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_q1, 2.52448340349684104192e-3);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_q2, 2.27265548208155028766e-1);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_q3, 2.00000000000000000009e0);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_C1, 0.693145751953125);
_EIGEN_DECLARE_CONST_Packet8d(cephes_exp_C2, 1.42860682030941723212e-6);
// clamp x
x = pmax(pmin(x, p8d_exp_hi), p8d_exp_lo);
// Express exp(x) as exp(g + n*log(2)).
const Packet8d n =
_mm512_mul_round_pd(p8d_cephes_LOG2EF, x, _MM_FROUND_TO_NEAREST_INT);
// Get the remainder modulo log(2), i.e. the "g" described above. Subtract
// n*log(2) out in two steps, i.e. n*C1 + n*C2, C1+C2=log2 to get the last
// digits right.
const Packet8d nC1 = pmul(n, p8d_cephes_exp_C1);
const Packet8d nC2 = pmul(n, p8d_cephes_exp_C2);
x = psub(x, nC1);
x = psub(x, nC2);
const Packet8d x2 = pmul(x, x);
// Evaluate the numerator polynomial of the rational interpolant.
Packet8d px = p8d_cephes_exp_p0;
px = pmadd(px, x2, p8d_cephes_exp_p1);
px = pmadd(px, x2, p8d_cephes_exp_p2);
px = pmul(px, x);
// Evaluate the denominator polynomial of the rational interpolant.
Packet8d qx = p8d_cephes_exp_q0;
qx = pmadd(qx, x2, p8d_cephes_exp_q1);
qx = pmadd(qx, x2, p8d_cephes_exp_q2);
qx = pmadd(qx, x2, p8d_cephes_exp_q3);
// I don't really get this bit, copied from the SSE2 routines, so...
// TODO(gonnet): Figure out what is going on here, perhaps find a better
// rational interpolant?
x = _mm512_div_pd(px, psub(qx, px));
x = pmadd(p8d_2, x, p8d_1);
// Build e=2^n.
const Packet8d e = _mm512_castsi512_pd(_mm512_slli_epi64(
_mm512_add_epi64(_mm512_cvtpd_epi64(n), _mm512_set1_epi64(1023)), 52));
// Construct the result 2^n * exp(g) = e * x. The max is used to catch
// non-finite values in the input.
return pmax(pmul(x, e), _x);
}*/
// Functions for sqrt.
// The EIGEN_FAST_MATH version uses the _mm_rsqrt_ps approximation and one step
// of Newton's method, at a cost of 1-2 bits of precision as opposed to the
// exact solution. The main advantage of this approach is not just speed, but
// also the fact that it can be inlined and pipelined with other computations,
// further reducing its effective latency.
#if EIGEN_FAST_MATH
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet16f
psqrt<Packet16f>(const Packet16f& _x) {
_EIGEN_DECLARE_CONST_Packet16f(one_point_five, 1.5f);
_EIGEN_DECLARE_CONST_Packet16f(minus_half, -0.5f);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(flt_min, 0x00800000);
Packet16f neg_half = pmul(_x, p16f_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
__mmask16 non_zero_mask = _mm512_cmp_ps_mask(_x, p16f_flt_min, _CMP_GE_OQ);
Packet16f x = _mm512_mask_blend_ps(non_zero_mask, _mm512_setzero_ps(), _mm512_rsqrt14_ps(_x));
// Do a single step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p16f_one_point_five));
// Multiply the original _x by it's reciprocal square root to extract the
// square root.
return pmul(_x, x);
}
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8d
psqrt<Packet8d>(const Packet8d& _x) {
_EIGEN_DECLARE_CONST_Packet8d(one_point_five, 1.5);
_EIGEN_DECLARE_CONST_Packet8d(minus_half, -0.5);
_EIGEN_DECLARE_CONST_Packet8d_FROM_INT64(dbl_min, 0x0010000000000000LL);
Packet8d neg_half = pmul(_x, p8d_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
__mmask8 non_zero_mask = _mm512_cmp_pd_mask(_x, p8d_dbl_min, _CMP_GE_OQ);
Packet8d x = _mm512_mask_blend_pd(non_zero_mask, _mm512_setzero_pd(), _mm512_rsqrt14_pd(_x));
// Do a first step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p8d_one_point_five));
// Do a second step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p8d_one_point_five));
// Multiply the original _x by it's reciprocal square root to extract the
// square root.
return pmul(_x, x);
}
#else
template <>
EIGEN_STRONG_INLINE Packet16f psqrt<Packet16f>(const Packet16f& x) {
return _mm512_sqrt_ps(x);
}
template <>
EIGEN_STRONG_INLINE Packet8d psqrt<Packet8d>(const Packet8d& x) {
return _mm512_sqrt_pd(x);
}
#endif
// Functions for rsqrt.
// Almost identical to the sqrt routine, just leave out the last multiplication
// and fill in NaN/Inf where needed. Note that this function only exists as an
// iterative version for doubles since there is no instruction for diretly
// computing the reciprocal square root in AVX-512.
#ifdef EIGEN_FAST_MATH
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet16f
prsqrt<Packet16f>(const Packet16f& _x) {
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(inf, 0x7f800000);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(nan, 0x7fc00000);
_EIGEN_DECLARE_CONST_Packet16f(one_point_five, 1.5f);
_EIGEN_DECLARE_CONST_Packet16f(minus_half, -0.5f);
_EIGEN_DECLARE_CONST_Packet16f_FROM_INT(flt_min, 0x00800000);
Packet16f neg_half = pmul(_x, p16f_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
__mmask16 le_zero_mask = _mm512_cmp_ps_mask(_x, p16f_flt_min, _CMP_LT_OQ);
Packet16f x = _mm512_mask_blend_ps(le_zero_mask, _mm512_rsqrt14_ps(_x), _mm512_setzero_ps());
// Fill in NaNs and Infs for the negative/zero entries.
__mmask16 neg_mask = _mm512_cmp_ps_mask(_x, _mm512_setzero_ps(), _CMP_LT_OQ);
Packet16f infs_and_nans = _mm512_mask_blend_ps(
neg_mask, _mm512_mask_blend_ps(le_zero_mask, _mm512_setzero_ps(), p16f_inf), p16f_nan);
// Do a single step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p16f_one_point_five));
// Insert NaNs and Infs in all the right places.
return _mm512_mask_blend_ps(le_zero_mask, x, infs_and_nans);
}
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet8d
prsqrt<Packet8d>(const Packet8d& _x) {
_EIGEN_DECLARE_CONST_Packet8d_FROM_INT64(inf, 0x7ff0000000000000LL);
_EIGEN_DECLARE_CONST_Packet8d_FROM_INT64(nan, 0x7ff1000000000000LL);
_EIGEN_DECLARE_CONST_Packet8d(one_point_five, 1.5);
_EIGEN_DECLARE_CONST_Packet8d(minus_half, -0.5);
_EIGEN_DECLARE_CONST_Packet8d_FROM_INT64(dbl_min, 0x0010000000000000LL);
Packet8d neg_half = pmul(_x, p8d_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
__mmask8 le_zero_mask = _mm512_cmp_pd_mask(_x, p8d_dbl_min, _CMP_LT_OQ);
Packet8d x = _mm512_mask_blend_pd(le_zero_mask, _mm512_rsqrt14_pd(_x), _mm512_setzero_pd());
// Fill in NaNs and Infs for the negative/zero entries.
__mmask8 neg_mask = _mm512_cmp_pd_mask(_x, _mm512_setzero_pd(), _CMP_LT_OQ);
Packet8d infs_and_nans = _mm512_mask_blend_pd(
neg_mask, _mm512_mask_blend_pd(le_zero_mask, _mm512_setzero_pd(), p8d_inf), p8d_nan);
// Do a first step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p8d_one_point_five));
// Do a second step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p8d_one_point_five));
// Insert NaNs and Infs in all the right places.
return _mm512_mask_blend_pd(le_zero_mask, x, infs_and_nans);
}
#elif defined(EIGEN_VECTORIZE_AVX512ER)
template <>
EIGEN_STRONG_INLINE Packet16f prsqrt<Packet16f>(const Packet16f& x) {
return _mm512_rsqrt28_ps(x);
}
#endif
#endif
} // end namespace internal
} // end namespace Eigen
#endif // THIRD_PARTY_EIGEN3_EIGEN_SRC_CORE_ARCH_AVX512_MATHFUNCTIONS_H_
| 15,733 | 39.137755 | 105 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/AltiVec/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2007 Julien Pommier
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
// Copyright (C) 2016 Konstantinos Margaritis <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* The sin, cos, exp, and log functions of this file come from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
*/
#ifndef EIGEN_MATH_FUNCTIONS_ALTIVEC_H
#define EIGEN_MATH_FUNCTIONS_ALTIVEC_H
namespace Eigen {
namespace internal {
static _EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
static _EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
static _EIGEN_DECLARE_CONST_Packet4i(0x7f, 0x7f);
static _EIGEN_DECLARE_CONST_Packet4i(23, 23);
static _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(inv_mant_mask, ~0x7f800000);
/* the smallest non denormalized float number */
static _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(min_norm_pos, 0x00800000);
static _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(minus_inf, 0xff800000); // -1.f/0.f
static _EIGEN_DECLARE_CONST_Packet4f_FROM_INT(minus_nan, 0xffffffff);
/* natural logarithm computed for 4 simultaneous float
return NaN for x <= 0
*/
static _EIGEN_DECLARE_CONST_Packet4f(cephes_SQRTHF, 0.707106781186547524f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p0, 7.0376836292E-2f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p1, - 1.1514610310E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p2, 1.1676998740E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p3, - 1.2420140846E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p4, + 1.4249322787E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p5, - 1.6668057665E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p6, + 2.0000714765E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p7, - 2.4999993993E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_p8, + 3.3333331174E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_q1, -2.12194440e-4f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_log_q2, 0.693359375f);
static _EIGEN_DECLARE_CONST_Packet4f(exp_hi, 88.3762626647950f);
static _EIGEN_DECLARE_CONST_Packet4f(exp_lo, -88.3762626647949f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_LOG2EF, 1.44269504088896341f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C1, 0.693359375f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C2, -2.12194440e-4f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p0, 1.9875691500E-4f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p1, 1.3981999507E-3f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p2, 8.3334519073E-3f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p3, 4.1665795894E-2f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p4, 1.6666665459E-1f);
static _EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p5, 5.0000001201E-1f);
#ifdef __VSX__
static _EIGEN_DECLARE_CONST_Packet2d(1 , 1.0);
static _EIGEN_DECLARE_CONST_Packet2d(2 , 2.0);
static _EIGEN_DECLARE_CONST_Packet2d(half, 0.5);
static _EIGEN_DECLARE_CONST_Packet2d(exp_hi, 709.437);
static _EIGEN_DECLARE_CONST_Packet2d(exp_lo, -709.436139303);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_LOG2EF, 1.4426950408889634073599);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p0, 1.26177193074810590878e-4);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p1, 3.02994407707441961300e-2);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p2, 9.99999999999999999910e-1);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q0, 3.00198505138664455042e-6);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q1, 2.52448340349684104192e-3);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q2, 2.27265548208155028766e-1);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q3, 2.00000000000000000009e0);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C1, 0.693145751953125);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C2, 1.42860682030941723212e-6);
#ifdef __POWER8_VECTOR__
static Packet2l p2l_1023 = { 1023, 1023 };
static Packet2ul p2ul_52 = { 52, 52 };
#endif
#endif
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f plog<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
Packet4i emm0;
/* isvalid_mask is 0 if x < 0 or x is NaN. */
Packet4ui isvalid_mask = reinterpret_cast<Packet4ui>(vec_cmpge(x, p4f_ZERO));
Packet4ui iszero_mask = reinterpret_cast<Packet4ui>(vec_cmpeq(x, p4f_ZERO));
x = pmax(x, p4f_min_norm_pos); /* cut off denormalized stuff */
emm0 = vec_sr(reinterpret_cast<Packet4i>(x),
reinterpret_cast<Packet4ui>(p4i_23));
/* keep only the fractional part */
x = pand(x, p4f_inv_mant_mask);
x = por(x, p4f_half);
emm0 = psub(emm0, p4i_0x7f);
Packet4f e = padd(vec_ctf(emm0, 0), p4f_1);
/* part2:
if( x < SQRTHF ) {
e -= 1;
x = x + x - 1.0;
} else { x = x - 1.0; }
*/
Packet4f mask = reinterpret_cast<Packet4f>(vec_cmplt(x, p4f_cephes_SQRTHF));
Packet4f tmp = pand(x, mask);
x = psub(x, p4f_1);
e = psub(e, pand(p4f_1, mask));
x = padd(x, tmp);
Packet4f x2 = pmul(x,x);
Packet4f x3 = pmul(x2,x);
Packet4f y, y1, y2;
y = pmadd(p4f_cephes_log_p0, x, p4f_cephes_log_p1);
y1 = pmadd(p4f_cephes_log_p3, x, p4f_cephes_log_p4);
y2 = pmadd(p4f_cephes_log_p6, x, p4f_cephes_log_p7);
y = pmadd(y , x, p4f_cephes_log_p2);
y1 = pmadd(y1, x, p4f_cephes_log_p5);
y2 = pmadd(y2, x, p4f_cephes_log_p8);
y = pmadd(y, x3, y1);
y = pmadd(y, x3, y2);
y = pmul(y, x3);
y1 = pmul(e, p4f_cephes_log_q1);
tmp = pmul(x2, p4f_half);
y = padd(y, y1);
x = psub(x, tmp);
y2 = pmul(e, p4f_cephes_log_q2);
x = padd(x, y);
x = padd(x, y2);
// negative arg will be NAN, 0 will be -INF
x = vec_sel(x, p4f_minus_inf, iszero_mask);
x = vec_sel(p4f_minus_nan, x, isvalid_mask);
return x;
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f pexp<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
Packet4f tmp, fx;
Packet4i emm0;
// clamp x
x = pmax(pmin(x, p4f_exp_hi), p4f_exp_lo);
// express exp(x) as exp(g + n*log(2))
fx = pmadd(x, p4f_cephes_LOG2EF, p4f_half);
fx = pfloor(fx);
tmp = pmul(fx, p4f_cephes_exp_C1);
Packet4f z = pmul(fx, p4f_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
z = pmul(x,x);
Packet4f y = p4f_cephes_exp_p0;
y = pmadd(y, x, p4f_cephes_exp_p1);
y = pmadd(y, x, p4f_cephes_exp_p2);
y = pmadd(y, x, p4f_cephes_exp_p3);
y = pmadd(y, x, p4f_cephes_exp_p4);
y = pmadd(y, x, p4f_cephes_exp_p5);
y = pmadd(y, z, x);
y = padd(y, p4f_1);
// build 2^n
emm0 = vec_cts(fx, 0);
emm0 = vec_add(emm0, p4i_0x7f);
emm0 = vec_sl(emm0, reinterpret_cast<Packet4ui>(p4i_23));
// Altivec's max & min operators just drop silent NaNs. Check NaNs in
// inputs and return them unmodified.
Packet4ui isnumber_mask = reinterpret_cast<Packet4ui>(vec_cmpeq(_x, _x));
return vec_sel(_x, pmax(pmul(y, reinterpret_cast<Packet4f>(emm0)), _x),
isnumber_mask);
}
#ifndef EIGEN_COMP_CLANG
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f prsqrt<Packet4f>(const Packet4f& x)
{
return vec_rsqrt(x);
}
#endif
#ifdef __VSX__
#ifndef EIGEN_COMP_CLANG
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d prsqrt<Packet2d>(const Packet2d& x)
{
return vec_rsqrt(x);
}
#endif
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f psqrt<Packet4f>(const Packet4f& x)
{
return vec_sqrt(x);
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d psqrt<Packet2d>(const Packet2d& x)
{
return vec_sqrt(x);
}
// VSX support varies between different compilers and even different
// versions of the same compiler. For gcc version >= 4.9.3, we can use
// vec_cts to efficiently convert Packet2d to Packet2l. Otherwise, use
// a slow version that works with older compilers.
// Update: apparently vec_cts/vec_ctf intrinsics for 64-bit doubles
// are buggy, https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70963
static inline Packet2l ConvertToPacket2l(const Packet2d& x) {
#if EIGEN_GNUC_AT_LEAST(5, 4) || \
(EIGEN_GNUC_AT(6, 1) && __GNUC_PATCHLEVEL__ >= 1)
return vec_cts(x, 0); // TODO: check clang version.
#else
double tmp[2];
memcpy(tmp, &x, sizeof(tmp));
Packet2l l = { static_cast<long long>(tmp[0]),
static_cast<long long>(tmp[1]) };
return l;
#endif
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d pexp<Packet2d>(const Packet2d& _x)
{
Packet2d x = _x;
Packet2d tmp, fx;
Packet2l emm0;
// clamp x
x = pmax(pmin(x, p2d_exp_hi), p2d_exp_lo);
/* express exp(x) as exp(g + n*log(2)) */
fx = pmadd(x, p2d_cephes_LOG2EF, p2d_half);
fx = pfloor(fx);
tmp = pmul(fx, p2d_cephes_exp_C1);
Packet2d z = pmul(fx, p2d_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
Packet2d x2 = pmul(x,x);
Packet2d px = p2d_cephes_exp_p0;
px = pmadd(px, x2, p2d_cephes_exp_p1);
px = pmadd(px, x2, p2d_cephes_exp_p2);
px = pmul (px, x);
Packet2d qx = p2d_cephes_exp_q0;
qx = pmadd(qx, x2, p2d_cephes_exp_q1);
qx = pmadd(qx, x2, p2d_cephes_exp_q2);
qx = pmadd(qx, x2, p2d_cephes_exp_q3);
x = pdiv(px,psub(qx,px));
x = pmadd(p2d_2,x,p2d_1);
// build 2^n
emm0 = ConvertToPacket2l(fx);
#ifdef __POWER8_VECTOR__
emm0 = vec_add(emm0, p2l_1023);
emm0 = vec_sl(emm0, p2ul_52);
#else
// Code is a bit complex for POWER7. There is actually a
// vec_xxsldi intrinsic but it is not supported by some gcc versions.
// So we shift (52-32) bits and do a word swap with zeros.
_EIGEN_DECLARE_CONST_Packet4i(1023, 1023);
_EIGEN_DECLARE_CONST_Packet4i(20, 20); // 52 - 32
Packet4i emm04i = reinterpret_cast<Packet4i>(emm0);
emm04i = vec_add(emm04i, p4i_1023);
emm04i = vec_sl(emm04i, reinterpret_cast<Packet4ui>(p4i_20));
static const Packet16uc perm = {
0x14, 0x15, 0x16, 0x17, 0x00, 0x01, 0x02, 0x03,
0x1c, 0x1d, 0x1e, 0x1f, 0x08, 0x09, 0x0a, 0x0b };
#ifdef _BIG_ENDIAN
emm0 = reinterpret_cast<Packet2l>(vec_perm(p4i_ZERO, emm04i, perm));
#else
emm0 = reinterpret_cast<Packet2l>(vec_perm(emm04i, p4i_ZERO, perm));
#endif
#endif
// Altivec's max & min operators just drop silent NaNs. Check NaNs in
// inputs and return them unmodified.
Packet2ul isnumber_mask = reinterpret_cast<Packet2ul>(vec_cmpeq(_x, _x));
return vec_sel(_x, pmax(pmul(x, reinterpret_cast<Packet2d>(emm0)), _x),
isnumber_mask);
}
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_ALTIVEC_H
| 10,797 | 32.430341 | 85 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/CUDA/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATH_FUNCTIONS_CUDA_H
#define EIGEN_MATH_FUNCTIONS_CUDA_H
namespace Eigen {
namespace internal {
// Make sure this is only available when targeting a GPU: we don't want to
// introduce conflicts between these packet_traits definitions and the ones
// we'll use on the host side (SSE, AVX, ...)
#if defined(__CUDACC__) && defined(EIGEN_USE_GPU)
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 plog<float4>(const float4& a)
{
return make_float4(logf(a.x), logf(a.y), logf(a.z), logf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 plog<double2>(const double2& a)
{
using ::log;
return make_double2(log(a.x), log(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 plog1p<float4>(const float4& a)
{
return make_float4(log1pf(a.x), log1pf(a.y), log1pf(a.z), log1pf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 plog1p<double2>(const double2& a)
{
return make_double2(log1p(a.x), log1p(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 pexp<float4>(const float4& a)
{
return make_float4(expf(a.x), expf(a.y), expf(a.z), expf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 pexp<double2>(const double2& a)
{
using ::exp;
return make_double2(exp(a.x), exp(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 psqrt<float4>(const float4& a)
{
return make_float4(sqrtf(a.x), sqrtf(a.y), sqrtf(a.z), sqrtf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 psqrt<double2>(const double2& a)
{
using ::sqrt;
return make_double2(sqrt(a.x), sqrt(a.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
float4 prsqrt<float4>(const float4& a)
{
return make_float4(rsqrtf(a.x), rsqrtf(a.y), rsqrtf(a.z), rsqrtf(a.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
double2 prsqrt<double2>(const double2& a)
{
return make_double2(rsqrt(a.x), rsqrt(a.y));
}
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_CUDA_H
| 2,387 | 24.956522 | 75 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/CUDA/PacketMath.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PACKET_MATH_CUDA_H
#define EIGEN_PACKET_MATH_CUDA_H
namespace Eigen {
namespace internal {
// Make sure this is only available when targeting a GPU: we don't want to
// introduce conflicts between these packet_traits definitions and the ones
// we'll use on the host side (SSE, AVX, ...)
#if defined(__CUDACC__) && defined(EIGEN_USE_GPU)
template<> struct is_arithmetic<float4> { enum { value = true }; };
template<> struct is_arithmetic<double2> { enum { value = true }; };
template<> struct packet_traits<float> : default_packet_traits
{
typedef float4 type;
typedef float4 half;
enum {
Vectorizable = 1,
AlignedOnScalar = 1,
size=4,
HasHalfPacket = 0,
HasDiv = 1,
HasSin = 0,
HasCos = 0,
HasLog = 1,
HasExp = 1,
HasSqrt = 1,
HasRsqrt = 1,
HasLGamma = 1,
HasDiGamma = 1,
HasZeta = 1,
HasPolygamma = 1,
HasErf = 1,
HasErfc = 1,
HasIGamma = 1,
HasIGammac = 1,
HasBetaInc = 1,
HasBlend = 0,
};
};
template<> struct packet_traits<double> : default_packet_traits
{
typedef double2 type;
typedef double2 half;
enum {
Vectorizable = 1,
AlignedOnScalar = 1,
size=2,
HasHalfPacket = 0,
HasDiv = 1,
HasLog = 1,
HasExp = 1,
HasSqrt = 1,
HasRsqrt = 1,
HasLGamma = 1,
HasDiGamma = 1,
HasZeta = 1,
HasPolygamma = 1,
HasErf = 1,
HasErfc = 1,
HasIGamma = 1,
HasIGammac = 1,
HasBetaInc = 1,
HasBlend = 0,
};
};
template<> struct unpacket_traits<float4> { typedef float type; enum {size=4, alignment=Aligned16}; typedef float4 half; };
template<> struct unpacket_traits<double2> { typedef double type; enum {size=2, alignment=Aligned16}; typedef double2 half; };
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pset1<float4>(const float& from) {
return make_float4(from, from, from, from);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pset1<double2>(const double& from) {
return make_double2(from, from);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 plset<float4>(const float& a) {
return make_float4(a, a+1, a+2, a+3);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 plset<double2>(const double& a) {
return make_double2(a, a+1);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 padd<float4>(const float4& a, const float4& b) {
return make_float4(a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 padd<double2>(const double2& a, const double2& b) {
return make_double2(a.x+b.x, a.y+b.y);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 psub<float4>(const float4& a, const float4& b) {
return make_float4(a.x-b.x, a.y-b.y, a.z-b.z, a.w-b.w);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 psub<double2>(const double2& a, const double2& b) {
return make_double2(a.x-b.x, a.y-b.y);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pnegate(const float4& a) {
return make_float4(-a.x, -a.y, -a.z, -a.w);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pnegate(const double2& a) {
return make_double2(-a.x, -a.y);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pconj(const float4& a) { return a; }
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pconj(const double2& a) { return a; }
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pmul<float4>(const float4& a, const float4& b) {
return make_float4(a.x*b.x, a.y*b.y, a.z*b.z, a.w*b.w);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pmul<double2>(const double2& a, const double2& b) {
return make_double2(a.x*b.x, a.y*b.y);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pdiv<float4>(const float4& a, const float4& b) {
return make_float4(a.x/b.x, a.y/b.y, a.z/b.z, a.w/b.w);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pdiv<double2>(const double2& a, const double2& b) {
return make_double2(a.x/b.x, a.y/b.y);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pmin<float4>(const float4& a, const float4& b) {
return make_float4(fminf(a.x, b.x), fminf(a.y, b.y), fminf(a.z, b.z), fminf(a.w, b.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pmin<double2>(const double2& a, const double2& b) {
return make_double2(fmin(a.x, b.x), fmin(a.y, b.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pmax<float4>(const float4& a, const float4& b) {
return make_float4(fmaxf(a.x, b.x), fmaxf(a.y, b.y), fmaxf(a.z, b.z), fmaxf(a.w, b.w));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pmax<double2>(const double2& a, const double2& b) {
return make_double2(fmax(a.x, b.x), fmax(a.y, b.y));
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pload<float4>(const float* from) {
return *reinterpret_cast<const float4*>(from);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 pload<double2>(const double* from) {
return *reinterpret_cast<const double2*>(from);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 ploadu<float4>(const float* from) {
return make_float4(from[0], from[1], from[2], from[3]);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE double2 ploadu<double2>(const double* from) {
return make_double2(from[0], from[1]);
}
template<> EIGEN_STRONG_INLINE float4 ploaddup<float4>(const float* from) {
return make_float4(from[0], from[0], from[1], from[1]);
}
template<> EIGEN_STRONG_INLINE double2 ploaddup<double2>(const double* from) {
return make_double2(from[0], from[0]);
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void pstore<float>(float* to, const float4& from) {
*reinterpret_cast<float4*>(to) = from;
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void pstore<double>(double* to, const double2& from) {
*reinterpret_cast<double2*>(to) = from;
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void pstoreu<float>(float* to, const float4& from) {
to[0] = from.x;
to[1] = from.y;
to[2] = from.z;
to[3] = from.w;
}
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void pstoreu<double>(double* to, const double2& from) {
to[0] = from.x;
to[1] = from.y;
}
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float4 ploadt_ro<float4, Aligned>(const float* from) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350
return __ldg((const float4*)from);
#else
return make_float4(from[0], from[1], from[2], from[3]);
#endif
}
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double2 ploadt_ro<double2, Aligned>(const double* from) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350
return __ldg((const double2*)from);
#else
return make_double2(from[0], from[1]);
#endif
}
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float4 ploadt_ro<float4, Unaligned>(const float* from) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350
return make_float4(__ldg(from+0), __ldg(from+1), __ldg(from+2), __ldg(from+3));
#else
return make_float4(from[0], from[1], from[2], from[3]);
#endif
}
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double2 ploadt_ro<double2, Unaligned>(const double* from) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 350
return make_double2(__ldg(from+0), __ldg(from+1));
#else
return make_double2(from[0], from[1]);
#endif
}
template<> EIGEN_DEVICE_FUNC inline float4 pgather<float, float4>(const float* from, Index stride) {
return make_float4(from[0*stride], from[1*stride], from[2*stride], from[3*stride]);
}
template<> EIGEN_DEVICE_FUNC inline double2 pgather<double, double2>(const double* from, Index stride) {
return make_double2(from[0*stride], from[1*stride]);
}
template<> EIGEN_DEVICE_FUNC inline void pscatter<float, float4>(float* to, const float4& from, Index stride) {
to[stride*0] = from.x;
to[stride*1] = from.y;
to[stride*2] = from.z;
to[stride*3] = from.w;
}
template<> EIGEN_DEVICE_FUNC inline void pscatter<double, double2>(double* to, const double2& from, Index stride) {
to[stride*0] = from.x;
to[stride*1] = from.y;
}
template<> EIGEN_DEVICE_FUNC inline float pfirst<float4>(const float4& a) {
return a.x;
}
template<> EIGEN_DEVICE_FUNC inline double pfirst<double2>(const double2& a) {
return a.x;
}
template<> EIGEN_DEVICE_FUNC inline float predux<float4>(const float4& a) {
return a.x + a.y + a.z + a.w;
}
template<> EIGEN_DEVICE_FUNC inline double predux<double2>(const double2& a) {
return a.x + a.y;
}
template<> EIGEN_DEVICE_FUNC inline float predux_max<float4>(const float4& a) {
return fmaxf(fmaxf(a.x, a.y), fmaxf(a.z, a.w));
}
template<> EIGEN_DEVICE_FUNC inline double predux_max<double2>(const double2& a) {
return fmax(a.x, a.y);
}
template<> EIGEN_DEVICE_FUNC inline float predux_min<float4>(const float4& a) {
return fminf(fminf(a.x, a.y), fminf(a.z, a.w));
}
template<> EIGEN_DEVICE_FUNC inline double predux_min<double2>(const double2& a) {
return fmin(a.x, a.y);
}
template<> EIGEN_DEVICE_FUNC inline float predux_mul<float4>(const float4& a) {
return a.x * a.y * a.z * a.w;
}
template<> EIGEN_DEVICE_FUNC inline double predux_mul<double2>(const double2& a) {
return a.x * a.y;
}
template<> EIGEN_DEVICE_FUNC inline float4 pabs<float4>(const float4& a) {
return make_float4(fabsf(a.x), fabsf(a.y), fabsf(a.z), fabsf(a.w));
}
template<> EIGEN_DEVICE_FUNC inline double2 pabs<double2>(const double2& a) {
return make_double2(fabs(a.x), fabs(a.y));
}
EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<float4,4>& kernel) {
float tmp = kernel.packet[0].y;
kernel.packet[0].y = kernel.packet[1].x;
kernel.packet[1].x = tmp;
tmp = kernel.packet[0].z;
kernel.packet[0].z = kernel.packet[2].x;
kernel.packet[2].x = tmp;
tmp = kernel.packet[0].w;
kernel.packet[0].w = kernel.packet[3].x;
kernel.packet[3].x = tmp;
tmp = kernel.packet[1].z;
kernel.packet[1].z = kernel.packet[2].y;
kernel.packet[2].y = tmp;
tmp = kernel.packet[1].w;
kernel.packet[1].w = kernel.packet[3].y;
kernel.packet[3].y = tmp;
tmp = kernel.packet[2].w;
kernel.packet[2].w = kernel.packet[3].z;
kernel.packet[3].z = tmp;
}
EIGEN_DEVICE_FUNC inline void
ptranspose(PacketBlock<double2,2>& kernel) {
double tmp = kernel.packet[0].y;
kernel.packet[0].y = kernel.packet[1].x;
kernel.packet[1].x = tmp;
}
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_PACKET_MATH_CUDA_H
| 10,744 | 31.170659 | 126 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/CUDA/TypeCasting.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TYPE_CASTING_CUDA_H
#define EIGEN_TYPE_CASTING_CUDA_H
namespace Eigen {
namespace internal {
template<>
struct scalar_cast_op<float, Eigen::half> {
EIGEN_EMPTY_STRUCT_CTOR(scalar_cast_op)
typedef Eigen::half result_type;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Eigen::half operator() (const float& a) const {
#if defined(EIGEN_HAS_CUDA_FP16) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300
return __float2half(a);
#else
return Eigen::half(a);
#endif
}
};
template<>
struct functor_traits<scalar_cast_op<float, Eigen::half> >
{ enum { Cost = NumTraits<float>::AddCost, PacketAccess = false }; };
template<>
struct scalar_cast_op<int, Eigen::half> {
EIGEN_EMPTY_STRUCT_CTOR(scalar_cast_op)
typedef Eigen::half result_type;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Eigen::half operator() (const int& a) const {
#if defined(EIGEN_HAS_CUDA_FP16) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300
return __float2half(static_cast<float>(a));
#else
return Eigen::half(static_cast<float>(a));
#endif
}
};
template<>
struct functor_traits<scalar_cast_op<int, Eigen::half> >
{ enum { Cost = NumTraits<float>::AddCost, PacketAccess = false }; };
template<>
struct scalar_cast_op<Eigen::half, float> {
EIGEN_EMPTY_STRUCT_CTOR(scalar_cast_op)
typedef float result_type;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float operator() (const Eigen::half& a) const {
#if defined(EIGEN_HAS_CUDA_FP16) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300
return __half2float(a);
#else
return static_cast<float>(a);
#endif
}
};
template<>
struct functor_traits<scalar_cast_op<Eigen::half, float> >
{ enum { Cost = NumTraits<float>::AddCost, PacketAccess = false }; };
#if defined(EIGEN_HAS_CUDA_FP16) && defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 300
template <>
struct type_casting_traits<Eigen::half, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 2,
TgtCoeffRatio = 1
};
};
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE float4 pcast<half2, float4>(const half2& a, const half2& b) {
float2 r1 = __half22float2(a);
float2 r2 = __half22float2(b);
return make_float4(r1.x, r1.y, r2.x, r2.y);
}
template <>
struct type_casting_traits<float, Eigen::half> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 2
};
};
template<> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE half2 pcast<float4, half2>(const float4& a) {
// Simply discard the second half of the input
return __floats2half2_rn(a.x, a.y);
}
#elif defined EIGEN_VECTORIZE_AVX512
template <>
struct type_casting_traits<half, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet16f pcast<Packet16h, Packet16f>(const Packet16h& a) {
return half2float(a);
}
template <>
struct type_casting_traits<float, half> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet16h pcast<Packet16f, Packet16h>(const Packet16f& a) {
return float2half(a);
}
#elif defined EIGEN_VECTORIZE_AVX
template <>
struct type_casting_traits<Eigen::half, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet8f pcast<Packet8h, Packet8f>(const Packet8h& a) {
return half2float(a);
}
template <>
struct type_casting_traits<float, Eigen::half> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet8h pcast<Packet8f, Packet8h>(const Packet8f& a) {
return float2half(a);
}
// Disable the following code since it's broken on too many platforms / compilers.
//#elif defined(EIGEN_VECTORIZE_SSE) && (!EIGEN_ARCH_x86_64) && (!EIGEN_COMP_MSVC)
#elif 0
template <>
struct type_casting_traits<Eigen::half, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet4f pcast<Packet4h, Packet4f>(const Packet4h& a) {
__int64_t a64 = _mm_cvtm64_si64(a.x);
Eigen::half h = raw_uint16_to_half(static_cast<unsigned short>(a64));
float f1 = static_cast<float>(h);
h = raw_uint16_to_half(static_cast<unsigned short>(a64 >> 16));
float f2 = static_cast<float>(h);
h = raw_uint16_to_half(static_cast<unsigned short>(a64 >> 32));
float f3 = static_cast<float>(h);
h = raw_uint16_to_half(static_cast<unsigned short>(a64 >> 48));
float f4 = static_cast<float>(h);
return _mm_set_ps(f4, f3, f2, f1);
}
template <>
struct type_casting_traits<float, Eigen::half> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template<> EIGEN_STRONG_INLINE Packet4h pcast<Packet4f, Packet4h>(const Packet4f& a) {
EIGEN_ALIGN16 float aux[4];
pstore(aux, a);
Eigen::half h0(aux[0]);
Eigen::half h1(aux[1]);
Eigen::half h2(aux[2]);
Eigen::half h3(aux[3]);
Packet4h result;
result.x = _mm_set_pi16(h3.x, h2.x, h1.x, h0.x);
return result;
}
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TYPE_CASTING_CUDA_H
| 5,509 | 24.868545 | 110 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/Default/ConjHelper.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2017 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_ARCH_CONJ_HELPER_H
#define EIGEN_ARCH_CONJ_HELPER_H
#define EIGEN_MAKE_CONJ_HELPER_CPLX_REAL(PACKET_CPLX, PACKET_REAL) \
template<> struct conj_helper<PACKET_REAL, PACKET_CPLX, false,false> { \
EIGEN_STRONG_INLINE PACKET_CPLX pmadd(const PACKET_REAL& x, const PACKET_CPLX& y, const PACKET_CPLX& c) const \
{ return padd(c, pmul(x,y)); } \
EIGEN_STRONG_INLINE PACKET_CPLX pmul(const PACKET_REAL& x, const PACKET_CPLX& y) const \
{ return PACKET_CPLX(Eigen::internal::pmul<PACKET_REAL>(x, y.v)); } \
}; \
\
template<> struct conj_helper<PACKET_CPLX, PACKET_REAL, false,false> { \
EIGEN_STRONG_INLINE PACKET_CPLX pmadd(const PACKET_CPLX& x, const PACKET_REAL& y, const PACKET_CPLX& c) const \
{ return padd(c, pmul(x,y)); } \
EIGEN_STRONG_INLINE PACKET_CPLX pmul(const PACKET_CPLX& x, const PACKET_REAL& y) const \
{ return PACKET_CPLX(Eigen::internal::pmul<PACKET_REAL>(x.v, y)); } \
};
#endif // EIGEN_ARCH_CONJ_HELPER_H
| 1,989 | 65.333333 | 125 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/Default/Settings.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* All the parameters defined in this file can be specialized in the
* architecture specific files, and/or by the user.
* More to come... */
#ifndef EIGEN_DEFAULT_SETTINGS_H
#define EIGEN_DEFAULT_SETTINGS_H
/** Defines the maximal loop size to enable meta unrolling of loops.
* Note that the value here is expressed in Eigen's own notion of "number of FLOPS",
* it does not correspond to the number of iterations or the number of instructions
*/
#ifndef EIGEN_UNROLLING_LIMIT
#define EIGEN_UNROLLING_LIMIT 100
#endif
/** Defines the threshold between a "small" and a "large" matrix.
* This threshold is mainly used to select the proper product implementation.
*/
#ifndef EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD
#define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 8
#endif
/** Defines the maximal width of the blocks used in the triangular product and solver
* for vectors (level 2 blas xTRMV and xTRSV). The default is 8.
*/
#ifndef EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH
#define EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH 8
#endif
/** Defines the default number of registers available for that architecture.
* Currently it must be 8 or 16. Other values will fail.
*/
#ifndef EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS
#define EIGEN_ARCH_DEFAULT_NUMBER_OF_REGISTERS 8
#endif
#endif // EIGEN_DEFAULT_SETTINGS_H
| 1,746 | 33.94 | 85 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/NEON/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* The sin, cos, exp, and log functions of this file come from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
*/
#ifndef EIGEN_MATH_FUNCTIONS_NEON_H
#define EIGEN_MATH_FUNCTIONS_NEON_H
namespace Eigen {
namespace internal {
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f pexp<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
Packet4f tmp, fx;
_EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
_EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet4i(0x7f, 0x7f);
_EIGEN_DECLARE_CONST_Packet4f(exp_hi, 88.3762626647950f);
_EIGEN_DECLARE_CONST_Packet4f(exp_lo, -88.3762626647949f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_LOG2EF, 1.44269504088896341f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C1, 0.693359375f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C2, -2.12194440e-4f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p0, 1.9875691500E-4f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p1, 1.3981999507E-3f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p2, 8.3334519073E-3f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p3, 4.1665795894E-2f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p4, 1.6666665459E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p5, 5.0000001201E-1f);
x = vminq_f32(x, p4f_exp_hi);
x = vmaxq_f32(x, p4f_exp_lo);
/* express exp(x) as exp(g + n*log(2)) */
fx = vmlaq_f32(p4f_half, x, p4f_cephes_LOG2EF);
/* perform a floorf */
tmp = vcvtq_f32_s32(vcvtq_s32_f32(fx));
/* if greater, substract 1 */
Packet4ui mask = vcgtq_f32(tmp, fx);
mask = vandq_u32(mask, vreinterpretq_u32_f32(p4f_1));
fx = vsubq_f32(tmp, vreinterpretq_f32_u32(mask));
tmp = vmulq_f32(fx, p4f_cephes_exp_C1);
Packet4f z = vmulq_f32(fx, p4f_cephes_exp_C2);
x = vsubq_f32(x, tmp);
x = vsubq_f32(x, z);
Packet4f y = vmulq_f32(p4f_cephes_exp_p0, x);
z = vmulq_f32(x, x);
y = vaddq_f32(y, p4f_cephes_exp_p1);
y = vmulq_f32(y, x);
y = vaddq_f32(y, p4f_cephes_exp_p2);
y = vmulq_f32(y, x);
y = vaddq_f32(y, p4f_cephes_exp_p3);
y = vmulq_f32(y, x);
y = vaddq_f32(y, p4f_cephes_exp_p4);
y = vmulq_f32(y, x);
y = vaddq_f32(y, p4f_cephes_exp_p5);
y = vmulq_f32(y, z);
y = vaddq_f32(y, x);
y = vaddq_f32(y, p4f_1);
/* build 2^n */
int32x4_t mm;
mm = vcvtq_s32_f32(fx);
mm = vaddq_s32(mm, p4i_0x7f);
mm = vshlq_n_s32(mm, 23);
Packet4f pow2n = vreinterpretq_f32_s32(mm);
y = vmulq_f32(y, pow2n);
return y;
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_NEON_H
| 2,846 | 29.945652 | 75 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/SSE/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2007 Julien Pommier
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* The sin, cos, exp, and log functions of this file come from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
*/
#ifndef EIGEN_MATH_FUNCTIONS_SSE_H
#define EIGEN_MATH_FUNCTIONS_SSE_H
namespace Eigen {
namespace internal {
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f plog<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
_EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
_EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet4i(0x7f, 0x7f);
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(inv_mant_mask, ~0x7f800000);
/* the smallest non denormalized float number */
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(min_norm_pos, 0x00800000);
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(minus_inf, 0xff800000);//-1.f/0.f);
/* natural logarithm computed for 4 simultaneous float
return NaN for x <= 0
*/
_EIGEN_DECLARE_CONST_Packet4f(cephes_SQRTHF, 0.707106781186547524f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p0, 7.0376836292E-2f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p1, - 1.1514610310E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p2, 1.1676998740E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p3, - 1.2420140846E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p4, + 1.4249322787E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p5, - 1.6668057665E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p6, + 2.0000714765E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p7, - 2.4999993993E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_p8, + 3.3333331174E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_q1, -2.12194440e-4f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_log_q2, 0.693359375f);
Packet4i emm0;
Packet4f invalid_mask = _mm_cmpnge_ps(x, _mm_setzero_ps()); // not greater equal is true if x is NaN
Packet4f iszero_mask = _mm_cmpeq_ps(x, _mm_setzero_ps());
x = pmax(x, p4f_min_norm_pos); /* cut off denormalized stuff */
emm0 = _mm_srli_epi32(_mm_castps_si128(x), 23);
/* keep only the fractional part */
x = _mm_and_ps(x, p4f_inv_mant_mask);
x = _mm_or_ps(x, p4f_half);
emm0 = _mm_sub_epi32(emm0, p4i_0x7f);
Packet4f e = padd(Packet4f(_mm_cvtepi32_ps(emm0)), p4f_1);
/* part2:
if( x < SQRTHF ) {
e -= 1;
x = x + x - 1.0;
} else { x = x - 1.0; }
*/
Packet4f mask = _mm_cmplt_ps(x, p4f_cephes_SQRTHF);
Packet4f tmp = pand(x, mask);
x = psub(x, p4f_1);
e = psub(e, pand(p4f_1, mask));
x = padd(x, tmp);
Packet4f x2 = pmul(x,x);
Packet4f x3 = pmul(x2,x);
Packet4f y, y1, y2;
y = pmadd(p4f_cephes_log_p0, x, p4f_cephes_log_p1);
y1 = pmadd(p4f_cephes_log_p3, x, p4f_cephes_log_p4);
y2 = pmadd(p4f_cephes_log_p6, x, p4f_cephes_log_p7);
y = pmadd(y , x, p4f_cephes_log_p2);
y1 = pmadd(y1, x, p4f_cephes_log_p5);
y2 = pmadd(y2, x, p4f_cephes_log_p8);
y = pmadd(y, x3, y1);
y = pmadd(y, x3, y2);
y = pmul(y, x3);
y1 = pmul(e, p4f_cephes_log_q1);
tmp = pmul(x2, p4f_half);
y = padd(y, y1);
x = psub(x, tmp);
y2 = pmul(e, p4f_cephes_log_q2);
x = padd(x, y);
x = padd(x, y2);
// negative arg will be NAN, 0 will be -INF
return _mm_or_ps(_mm_andnot_ps(iszero_mask, _mm_or_ps(x, invalid_mask)),
_mm_and_ps(iszero_mask, p4f_minus_inf));
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f pexp<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
_EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
_EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet4i(0x7f, 0x7f);
_EIGEN_DECLARE_CONST_Packet4f(exp_hi, 88.3762626647950f);
_EIGEN_DECLARE_CONST_Packet4f(exp_lo, -88.3762626647949f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_LOG2EF, 1.44269504088896341f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C1, 0.693359375f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_C2, -2.12194440e-4f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p0, 1.9875691500E-4f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p1, 1.3981999507E-3f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p2, 8.3334519073E-3f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p3, 4.1665795894E-2f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p4, 1.6666665459E-1f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_exp_p5, 5.0000001201E-1f);
Packet4f tmp, fx;
Packet4i emm0;
// clamp x
x = pmax(pmin(x, p4f_exp_hi), p4f_exp_lo);
/* express exp(x) as exp(g + n*log(2)) */
fx = pmadd(x, p4f_cephes_LOG2EF, p4f_half);
#ifdef EIGEN_VECTORIZE_SSE4_1
fx = _mm_floor_ps(fx);
#else
emm0 = _mm_cvttps_epi32(fx);
tmp = _mm_cvtepi32_ps(emm0);
/* if greater, substract 1 */
Packet4f mask = _mm_cmpgt_ps(tmp, fx);
mask = _mm_and_ps(mask, p4f_1);
fx = psub(tmp, mask);
#endif
tmp = pmul(fx, p4f_cephes_exp_C1);
Packet4f z = pmul(fx, p4f_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
z = pmul(x,x);
Packet4f y = p4f_cephes_exp_p0;
y = pmadd(y, x, p4f_cephes_exp_p1);
y = pmadd(y, x, p4f_cephes_exp_p2);
y = pmadd(y, x, p4f_cephes_exp_p3);
y = pmadd(y, x, p4f_cephes_exp_p4);
y = pmadd(y, x, p4f_cephes_exp_p5);
y = pmadd(y, z, x);
y = padd(y, p4f_1);
// build 2^n
emm0 = _mm_cvttps_epi32(fx);
emm0 = _mm_add_epi32(emm0, p4i_0x7f);
emm0 = _mm_slli_epi32(emm0, 23);
return pmax(pmul(y, Packet4f(_mm_castsi128_ps(emm0))), _x);
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d pexp<Packet2d>(const Packet2d& _x)
{
Packet2d x = _x;
_EIGEN_DECLARE_CONST_Packet2d(1 , 1.0);
_EIGEN_DECLARE_CONST_Packet2d(2 , 2.0);
_EIGEN_DECLARE_CONST_Packet2d(half, 0.5);
_EIGEN_DECLARE_CONST_Packet2d(exp_hi, 709.437);
_EIGEN_DECLARE_CONST_Packet2d(exp_lo, -709.436139303);
_EIGEN_DECLARE_CONST_Packet2d(cephes_LOG2EF, 1.4426950408889634073599);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p0, 1.26177193074810590878e-4);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p1, 3.02994407707441961300e-2);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p2, 9.99999999999999999910e-1);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q0, 3.00198505138664455042e-6);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q1, 2.52448340349684104192e-3);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q2, 2.27265548208155028766e-1);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q3, 2.00000000000000000009e0);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C1, 0.693145751953125);
_EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C2, 1.42860682030941723212e-6);
static const __m128i p4i_1023_0 = _mm_setr_epi32(1023, 1023, 0, 0);
Packet2d tmp, fx;
Packet4i emm0;
// clamp x
x = pmax(pmin(x, p2d_exp_hi), p2d_exp_lo);
/* express exp(x) as exp(g + n*log(2)) */
fx = pmadd(p2d_cephes_LOG2EF, x, p2d_half);
#ifdef EIGEN_VECTORIZE_SSE4_1
fx = _mm_floor_pd(fx);
#else
emm0 = _mm_cvttpd_epi32(fx);
tmp = _mm_cvtepi32_pd(emm0);
/* if greater, substract 1 */
Packet2d mask = _mm_cmpgt_pd(tmp, fx);
mask = _mm_and_pd(mask, p2d_1);
fx = psub(tmp, mask);
#endif
tmp = pmul(fx, p2d_cephes_exp_C1);
Packet2d z = pmul(fx, p2d_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
Packet2d x2 = pmul(x,x);
Packet2d px = p2d_cephes_exp_p0;
px = pmadd(px, x2, p2d_cephes_exp_p1);
px = pmadd(px, x2, p2d_cephes_exp_p2);
px = pmul (px, x);
Packet2d qx = p2d_cephes_exp_q0;
qx = pmadd(qx, x2, p2d_cephes_exp_q1);
qx = pmadd(qx, x2, p2d_cephes_exp_q2);
qx = pmadd(qx, x2, p2d_cephes_exp_q3);
x = pdiv(px,psub(qx,px));
x = pmadd(p2d_2,x,p2d_1);
// build 2^n
emm0 = _mm_cvttpd_epi32(fx);
emm0 = _mm_add_epi32(emm0, p4i_1023_0);
emm0 = _mm_slli_epi32(emm0, 20);
emm0 = _mm_shuffle_epi32(emm0, _MM_SHUFFLE(1,2,0,3));
return pmax(pmul(x, Packet2d(_mm_castsi128_pd(emm0))), _x);
}
/* evaluation of 4 sines at onces, using SSE2 intrinsics.
The code is the exact rewriting of the cephes sinf function.
Precision is excellent as long as x < 8192 (I did not bother to
take into account the special handling they have for greater values
-- it does not return garbage for arguments over 8192, though, but
the extra precision is missing).
Note that it is such that sinf((float)M_PI) = 8.74e-8, which is the
surprising but correct result.
*/
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f psin<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
_EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
_EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet4i(1, 1);
_EIGEN_DECLARE_CONST_Packet4i(not1, ~1);
_EIGEN_DECLARE_CONST_Packet4i(2, 2);
_EIGEN_DECLARE_CONST_Packet4i(4, 4);
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(sign_mask, 0x80000000);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP1,-0.78515625f);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP2, -2.4187564849853515625e-4f);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP3, -3.77489497744594108e-8f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p0, -1.9515295891E-4f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p1, 8.3321608736E-3f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p2, -1.6666654611E-1f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p0, 2.443315711809948E-005f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p1, -1.388731625493765E-003f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p2, 4.166664568298827E-002f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_FOPI, 1.27323954473516f); // 4 / M_PI
Packet4f xmm1, xmm2, xmm3, sign_bit, y;
Packet4i emm0, emm2;
sign_bit = x;
/* take the absolute value */
x = pabs(x);
/* take the modulo */
/* extract the sign bit (upper one) */
sign_bit = _mm_and_ps(sign_bit, p4f_sign_mask);
/* scale by 4/Pi */
y = pmul(x, p4f_cephes_FOPI);
/* store the integer part of y in mm0 */
emm2 = _mm_cvttps_epi32(y);
/* j=(j+1) & (~1) (see the cephes sources) */
emm2 = _mm_add_epi32(emm2, p4i_1);
emm2 = _mm_and_si128(emm2, p4i_not1);
y = _mm_cvtepi32_ps(emm2);
/* get the swap sign flag */
emm0 = _mm_and_si128(emm2, p4i_4);
emm0 = _mm_slli_epi32(emm0, 29);
/* get the polynom selection mask
there is one polynom for 0 <= x <= Pi/4
and another one for Pi/4<x<=Pi/2
Both branches will be computed.
*/
emm2 = _mm_and_si128(emm2, p4i_2);
emm2 = _mm_cmpeq_epi32(emm2, _mm_setzero_si128());
Packet4f swap_sign_bit = _mm_castsi128_ps(emm0);
Packet4f poly_mask = _mm_castsi128_ps(emm2);
sign_bit = _mm_xor_ps(sign_bit, swap_sign_bit);
/* The magic pass: "Extended precision modular arithmetic"
x = ((x - y * DP1) - y * DP2) - y * DP3; */
xmm1 = pmul(y, p4f_minus_cephes_DP1);
xmm2 = pmul(y, p4f_minus_cephes_DP2);
xmm3 = pmul(y, p4f_minus_cephes_DP3);
x = padd(x, xmm1);
x = padd(x, xmm2);
x = padd(x, xmm3);
/* Evaluate the first polynom (0 <= x <= Pi/4) */
y = p4f_coscof_p0;
Packet4f z = _mm_mul_ps(x,x);
y = pmadd(y, z, p4f_coscof_p1);
y = pmadd(y, z, p4f_coscof_p2);
y = pmul(y, z);
y = pmul(y, z);
Packet4f tmp = pmul(z, p4f_half);
y = psub(y, tmp);
y = padd(y, p4f_1);
/* Evaluate the second polynom (Pi/4 <= x <= 0) */
Packet4f y2 = p4f_sincof_p0;
y2 = pmadd(y2, z, p4f_sincof_p1);
y2 = pmadd(y2, z, p4f_sincof_p2);
y2 = pmul(y2, z);
y2 = pmul(y2, x);
y2 = padd(y2, x);
/* select the correct result from the two polynoms */
y2 = _mm_and_ps(poly_mask, y2);
y = _mm_andnot_ps(poly_mask, y);
y = _mm_or_ps(y,y2);
/* update the sign */
return _mm_xor_ps(y, sign_bit);
}
/* almost the same as psin */
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f pcos<Packet4f>(const Packet4f& _x)
{
Packet4f x = _x;
_EIGEN_DECLARE_CONST_Packet4f(1 , 1.0f);
_EIGEN_DECLARE_CONST_Packet4f(half, 0.5f);
_EIGEN_DECLARE_CONST_Packet4i(1, 1);
_EIGEN_DECLARE_CONST_Packet4i(not1, ~1);
_EIGEN_DECLARE_CONST_Packet4i(2, 2);
_EIGEN_DECLARE_CONST_Packet4i(4, 4);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP1,-0.78515625f);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP2, -2.4187564849853515625e-4f);
_EIGEN_DECLARE_CONST_Packet4f(minus_cephes_DP3, -3.77489497744594108e-8f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p0, -1.9515295891E-4f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p1, 8.3321608736E-3f);
_EIGEN_DECLARE_CONST_Packet4f(sincof_p2, -1.6666654611E-1f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p0, 2.443315711809948E-005f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p1, -1.388731625493765E-003f);
_EIGEN_DECLARE_CONST_Packet4f(coscof_p2, 4.166664568298827E-002f);
_EIGEN_DECLARE_CONST_Packet4f(cephes_FOPI, 1.27323954473516f); // 4 / M_PI
Packet4f xmm1, xmm2, xmm3, y;
Packet4i emm0, emm2;
x = pabs(x);
/* scale by 4/Pi */
y = pmul(x, p4f_cephes_FOPI);
/* get the integer part of y */
emm2 = _mm_cvttps_epi32(y);
/* j=(j+1) & (~1) (see the cephes sources) */
emm2 = _mm_add_epi32(emm2, p4i_1);
emm2 = _mm_and_si128(emm2, p4i_not1);
y = _mm_cvtepi32_ps(emm2);
emm2 = _mm_sub_epi32(emm2, p4i_2);
/* get the swap sign flag */
emm0 = _mm_andnot_si128(emm2, p4i_4);
emm0 = _mm_slli_epi32(emm0, 29);
/* get the polynom selection mask */
emm2 = _mm_and_si128(emm2, p4i_2);
emm2 = _mm_cmpeq_epi32(emm2, _mm_setzero_si128());
Packet4f sign_bit = _mm_castsi128_ps(emm0);
Packet4f poly_mask = _mm_castsi128_ps(emm2);
/* The magic pass: "Extended precision modular arithmetic"
x = ((x - y * DP1) - y * DP2) - y * DP3; */
xmm1 = pmul(y, p4f_minus_cephes_DP1);
xmm2 = pmul(y, p4f_minus_cephes_DP2);
xmm3 = pmul(y, p4f_minus_cephes_DP3);
x = padd(x, xmm1);
x = padd(x, xmm2);
x = padd(x, xmm3);
/* Evaluate the first polynom (0 <= x <= Pi/4) */
y = p4f_coscof_p0;
Packet4f z = pmul(x,x);
y = pmadd(y,z,p4f_coscof_p1);
y = pmadd(y,z,p4f_coscof_p2);
y = pmul(y, z);
y = pmul(y, z);
Packet4f tmp = _mm_mul_ps(z, p4f_half);
y = psub(y, tmp);
y = padd(y, p4f_1);
/* Evaluate the second polynom (Pi/4 <= x <= 0) */
Packet4f y2 = p4f_sincof_p0;
y2 = pmadd(y2, z, p4f_sincof_p1);
y2 = pmadd(y2, z, p4f_sincof_p2);
y2 = pmul(y2, z);
y2 = pmadd(y2, x, x);
/* select the correct result from the two polynoms */
y2 = _mm_and_ps(poly_mask, y2);
y = _mm_andnot_ps(poly_mask, y);
y = _mm_or_ps(y,y2);
/* update the sign */
return _mm_xor_ps(y, sign_bit);
}
#if EIGEN_FAST_MATH
// Functions for sqrt.
// The EIGEN_FAST_MATH version uses the _mm_rsqrt_ps approximation and one step
// of Newton's method, at a cost of 1-2 bits of precision as opposed to the
// exact solution. It does not handle +inf, or denormalized numbers correctly.
// The main advantage of this approach is not just speed, but also the fact that
// it can be inlined and pipelined with other computations, further reducing its
// effective latency. This is similar to Quake3's fast inverse square root.
// For detail see here: http://www.beyond3d.com/content/articles/8/
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f psqrt<Packet4f>(const Packet4f& _x)
{
Packet4f half = pmul(_x, pset1<Packet4f>(.5f));
Packet4f denormal_mask = _mm_and_ps(
_mm_cmpge_ps(_x, _mm_setzero_ps()),
_mm_cmplt_ps(_x, pset1<Packet4f>((std::numeric_limits<float>::min)())));
// Compute approximate reciprocal sqrt.
Packet4f x = _mm_rsqrt_ps(_x);
// Do a single step of Newton's iteration.
x = pmul(x, psub(pset1<Packet4f>(1.5f), pmul(half, pmul(x,x))));
// Flush results for denormals to zero.
return _mm_andnot_ps(denormal_mask, pmul(_x,x));
}
#else
template<>EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f psqrt<Packet4f>(const Packet4f& x) { return _mm_sqrt_ps(x); }
#endif
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d psqrt<Packet2d>(const Packet2d& x) { return _mm_sqrt_pd(x); }
#if EIGEN_FAST_MATH
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f prsqrt<Packet4f>(const Packet4f& _x) {
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(inf, 0x7f800000);
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(nan, 0x7fc00000);
_EIGEN_DECLARE_CONST_Packet4f(one_point_five, 1.5f);
_EIGEN_DECLARE_CONST_Packet4f(minus_half, -0.5f);
_EIGEN_DECLARE_CONST_Packet4f_FROM_INT(flt_min, 0x00800000);
Packet4f neg_half = pmul(_x, p4f_minus_half);
// select only the inverse sqrt of positive normal inputs (denormals are
// flushed to zero and cause infs as well).
Packet4f le_zero_mask = _mm_cmple_ps(_x, p4f_flt_min);
Packet4f x = _mm_andnot_ps(le_zero_mask, _mm_rsqrt_ps(_x));
// Fill in NaNs and Infs for the negative/zero entries.
Packet4f neg_mask = _mm_cmplt_ps(_x, _mm_setzero_ps());
Packet4f zero_mask = _mm_andnot_ps(neg_mask, le_zero_mask);
Packet4f infs_and_nans = _mm_or_ps(_mm_and_ps(neg_mask, p4f_nan),
_mm_and_ps(zero_mask, p4f_inf));
// Do a single step of Newton's iteration.
x = pmul(x, pmadd(neg_half, pmul(x, x), p4f_one_point_five));
// Insert NaNs and Infs in all the right places.
return _mm_or_ps(x, infs_and_nans);
}
#else
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f prsqrt<Packet4f>(const Packet4f& x) {
// Unfortunately we can't use the much faster mm_rqsrt_ps since it only provides an approximation.
return _mm_div_ps(pset1<Packet4f>(1.0f), _mm_sqrt_ps(x));
}
#endif
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d prsqrt<Packet2d>(const Packet2d& x) {
// Unfortunately we can't use the much faster mm_rqsrt_pd since it only provides an approximation.
return _mm_div_pd(pset1<Packet2d>(1.0), _mm_sqrt_pd(x));
}
// Hyperbolic Tangent function.
template <>
EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED Packet4f
ptanh<Packet4f>(const Packet4f& x) {
return internal::generic_fast_tanh_float(x);
}
} // end namespace internal
namespace numext {
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
float sqrt(const float &x)
{
return internal::pfirst(internal::Packet4f(_mm_sqrt_ss(_mm_set_ss(x))));
}
template<>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
double sqrt(const double &x)
{
#if EIGEN_COMP_GNUC_STRICT
// This works around a GCC bug generating poor code for _mm_sqrt_pd
// See https://bitbucket.org/eigen/eigen/commits/14f468dba4d350d7c19c9b93072e19f7b3df563b
return internal::pfirst(internal::Packet2d(__builtin_ia32_sqrtsd(_mm_set_sd(x))));
#else
return internal::pfirst(internal::Packet2d(_mm_sqrt_pd(_mm_set_sd(x))));
#endif
}
} // end namespace numex
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_SSE_H
| 18,888 | 32.550622 | 102 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/SSE/TypeCasting.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Benoit Steiner <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TYPE_CASTING_SSE_H
#define EIGEN_TYPE_CASTING_SSE_H
namespace Eigen {
namespace internal {
#ifndef EIGEN_VECTORIZE_AVX
template <>
struct type_casting_traits<float, int> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template <>
struct type_casting_traits<int, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 1
};
};
template <>
struct type_casting_traits<double, float> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 2,
TgtCoeffRatio = 1
};
};
template <>
struct type_casting_traits<float, double> {
enum {
VectorizedCast = 1,
SrcCoeffRatio = 1,
TgtCoeffRatio = 2
};
};
#endif
template<> EIGEN_STRONG_INLINE Packet4i pcast<Packet4f, Packet4i>(const Packet4f& a) {
return _mm_cvttps_epi32(a);
}
template<> EIGEN_STRONG_INLINE Packet4f pcast<Packet4i, Packet4f>(const Packet4i& a) {
return _mm_cvtepi32_ps(a);
}
template<> EIGEN_STRONG_INLINE Packet4f pcast<Packet2d, Packet4f>(const Packet2d& a, const Packet2d& b) {
return _mm_shuffle_ps(_mm_cvtpd_ps(a), _mm_cvtpd_ps(b), (1 << 2) | (1 << 6));
}
template<> EIGEN_STRONG_INLINE Packet2d pcast<Packet4f, Packet2d>(const Packet4f& a) {
// Simply discard the second half of the input
return _mm_cvtps_pd(a);
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TYPE_CASTING_SSE_H
| 1,759 | 21.564103 | 105 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/arch/ZVector/MathFunctions.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2007 Julien Pommier
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
// Copyright (C) 2016 Konstantinos Margaritis <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* The sin, cos, exp, and log functions of this file come from
* Julien Pommier's sse math library: http://gruntthepeon.free.fr/ssemath/
*/
#ifndef EIGEN_MATH_FUNCTIONS_ALTIVEC_H
#define EIGEN_MATH_FUNCTIONS_ALTIVEC_H
namespace Eigen {
namespace internal {
static _EIGEN_DECLARE_CONST_Packet2d(1 , 1.0);
static _EIGEN_DECLARE_CONST_Packet2d(2 , 2.0);
static _EIGEN_DECLARE_CONST_Packet2d(half, 0.5);
static _EIGEN_DECLARE_CONST_Packet2d(exp_hi, 709.437);
static _EIGEN_DECLARE_CONST_Packet2d(exp_lo, -709.436139303);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_LOG2EF, 1.4426950408889634073599);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p0, 1.26177193074810590878e-4);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p1, 3.02994407707441961300e-2);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_p2, 9.99999999999999999910e-1);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q0, 3.00198505138664455042e-6);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q1, 2.52448340349684104192e-3);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q2, 2.27265548208155028766e-1);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_q3, 2.00000000000000000009e0);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C1, 0.693145751953125);
static _EIGEN_DECLARE_CONST_Packet2d(cephes_exp_C2, 1.42860682030941723212e-6);
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d pexp<Packet2d>(const Packet2d& _x)
{
Packet2d x = _x;
Packet2d tmp, fx;
Packet2l emm0;
// clamp x
x = pmax(pmin(x, p2d_exp_hi), p2d_exp_lo);
/* express exp(x) as exp(g + n*log(2)) */
fx = pmadd(p2d_cephes_LOG2EF, x, p2d_half);
fx = vec_floor(fx);
tmp = pmul(fx, p2d_cephes_exp_C1);
Packet2d z = pmul(fx, p2d_cephes_exp_C2);
x = psub(x, tmp);
x = psub(x, z);
Packet2d x2 = pmul(x,x);
Packet2d px = p2d_cephes_exp_p0;
px = pmadd(px, x2, p2d_cephes_exp_p1);
px = pmadd(px, x2, p2d_cephes_exp_p2);
px = pmul (px, x);
Packet2d qx = p2d_cephes_exp_q0;
qx = pmadd(qx, x2, p2d_cephes_exp_q1);
qx = pmadd(qx, x2, p2d_cephes_exp_q2);
qx = pmadd(qx, x2, p2d_cephes_exp_q3);
x = pdiv(px,psub(qx,px));
x = pmadd(p2d_2,x,p2d_1);
// build 2^n
emm0 = vec_ctsl(fx, 0);
static const Packet2l p2l_1023 = { 1023, 1023 };
static const Packet2ul p2ul_52 = { 52, 52 };
emm0 = emm0 + p2l_1023;
emm0 = emm0 << reinterpret_cast<Packet2l>(p2ul_52);
// Altivec's max & min operators just drop silent NaNs. Check NaNs in
// inputs and return them unmodified.
Packet2ul isnumber_mask = reinterpret_cast<Packet2ul>(vec_cmpeq(_x, _x));
return vec_sel(_x, pmax(pmul(x, reinterpret_cast<Packet2d>(emm0)), _x),
isnumber_mask);
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f pexp<Packet4f>(const Packet4f& x)
{
Packet4f res;
res.v4f[0] = pexp<Packet2d>(x.v4f[0]);
res.v4f[1] = pexp<Packet2d>(x.v4f[1]);
return res;
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d psqrt<Packet2d>(const Packet2d& x)
{
return __builtin_s390_vfsqdb(x);
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f psqrt<Packet4f>(const Packet4f& x)
{
Packet4f res;
res.v4f[0] = psqrt<Packet2d>(x.v4f[0]);
res.v4f[1] = psqrt<Packet2d>(x.v4f[1]);
return res;
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet2d prsqrt<Packet2d>(const Packet2d& x) {
// Unfortunately we can't use the much faster mm_rqsrt_pd since it only provides an approximation.
return pset1<Packet2d>(1.0) / psqrt<Packet2d>(x);
}
template<> EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS EIGEN_UNUSED
Packet4f prsqrt<Packet4f>(const Packet4f& x) {
Packet4f res;
res.v4f[0] = prsqrt<Packet2d>(x.v4f[0]);
res.v4f[1] = prsqrt<Packet2d>(x.v4f[1]);
return res;
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_MATH_FUNCTIONS_ALTIVEC_H
| 4,418 | 31.021739 | 100 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/functors/StlFunctors.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_STL_FUNCTORS_H
#define EIGEN_STL_FUNCTORS_H
namespace Eigen {
namespace internal {
// default functor traits for STL functors:
template<typename T>
struct functor_traits<std::multiplies<T> >
{ enum { Cost = NumTraits<T>::MulCost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::divides<T> >
{ enum { Cost = NumTraits<T>::MulCost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::plus<T> >
{ enum { Cost = NumTraits<T>::AddCost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::minus<T> >
{ enum { Cost = NumTraits<T>::AddCost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::negate<T> >
{ enum { Cost = NumTraits<T>::AddCost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::logical_or<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::logical_and<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::logical_not<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::greater<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::less<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::greater_equal<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::less_equal<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::equal_to<T> >
{ enum { Cost = 1, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::not_equal_to<T> >
{ enum { Cost = 1, PacketAccess = false }; };
#if (__cplusplus < 201103L) && (EIGEN_COMP_MSVC <= 1900)
// std::binder* are deprecated since c++11 and will be removed in c++17
template<typename T>
struct functor_traits<std::binder2nd<T> >
{ enum { Cost = functor_traits<T>::Cost, PacketAccess = false }; };
template<typename T>
struct functor_traits<std::binder1st<T> >
{ enum { Cost = functor_traits<T>::Cost, PacketAccess = false }; };
#endif
#if (__cplusplus < 201703L) && (EIGEN_COMP_MSVC < 1910)
// std::unary_negate is deprecated since c++17 and will be removed in c++20
template<typename T>
struct functor_traits<std::unary_negate<T> >
{ enum { Cost = 1 + functor_traits<T>::Cost, PacketAccess = false }; };
// std::binary_negate is deprecated since c++17 and will be removed in c++20
template<typename T>
struct functor_traits<std::binary_negate<T> >
{ enum { Cost = 1 + functor_traits<T>::Cost, PacketAccess = false }; };
#endif
#ifdef EIGEN_STDEXT_SUPPORT
template<typename T0,typename T1>
struct functor_traits<std::project1st<T0,T1> >
{ enum { Cost = 0, PacketAccess = false }; };
template<typename T0,typename T1>
struct functor_traits<std::project2nd<T0,T1> >
{ enum { Cost = 0, PacketAccess = false }; };
template<typename T0,typename T1>
struct functor_traits<std::select2nd<std::pair<T0,T1> > >
{ enum { Cost = 0, PacketAccess = false }; };
template<typename T0,typename T1>
struct functor_traits<std::select1st<std::pair<T0,T1> > >
{ enum { Cost = 0, PacketAccess = false }; };
template<typename T0,typename T1>
struct functor_traits<std::unary_compose<T0,T1> >
{ enum { Cost = functor_traits<T0>::Cost + functor_traits<T1>::Cost, PacketAccess = false }; };
template<typename T0,typename T1,typename T2>
struct functor_traits<std::binary_compose<T0,T1,T2> >
{ enum { Cost = functor_traits<T0>::Cost + functor_traits<T1>::Cost + functor_traits<T2>::Cost, PacketAccess = false }; };
#endif // EIGEN_STDEXT_SUPPORT
// allow to add new functors and specializations of functor_traits from outside Eigen.
// this macro is really needed because functor_traits must be specialized after it is declared but before it is used...
#ifdef EIGEN_FUNCTORS_PLUGIN
#include EIGEN_FUNCTORS_PLUGIN
#endif
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_STL_FUNCTORS_H
| 4,400 | 31.124088 | 122 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/functors/TernaryFunctors.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Eugene Brevdo <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TERNARY_FUNCTORS_H
#define EIGEN_TERNARY_FUNCTORS_H
namespace Eigen {
namespace internal {
//---------- associative ternary functors ----------
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TERNARY_FUNCTORS_H
| 607 | 22.384615 | 69 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/products/Parallelizer.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_PARALLELIZER_H
#define EIGEN_PARALLELIZER_H
namespace Eigen {
namespace internal {
/** \internal */
inline void manage_multi_threading(Action action, int* v)
{
static EIGEN_UNUSED int m_maxThreads = -1;
if(action==SetAction)
{
eigen_internal_assert(v!=0);
m_maxThreads = *v;
}
else if(action==GetAction)
{
eigen_internal_assert(v!=0);
#ifdef EIGEN_HAS_OPENMP
if(m_maxThreads>0)
*v = m_maxThreads;
else
*v = omp_get_max_threads();
#else
*v = 1;
#endif
}
else
{
eigen_internal_assert(false);
}
}
}
/** Must be call first when calling Eigen from multiple threads */
inline void initParallel()
{
int nbt;
internal::manage_multi_threading(GetAction, &nbt);
std::ptrdiff_t l1, l2, l3;
internal::manage_caching_sizes(GetAction, &l1, &l2, &l3);
}
/** \returns the max number of threads reserved for Eigen
* \sa setNbThreads */
inline int nbThreads()
{
int ret;
internal::manage_multi_threading(GetAction, &ret);
return ret;
}
/** Sets the max number of threads reserved for Eigen
* \sa nbThreads */
inline void setNbThreads(int v)
{
internal::manage_multi_threading(SetAction, &v);
}
namespace internal {
template<typename Index> struct GemmParallelInfo
{
GemmParallelInfo() : sync(-1), users(0), lhs_start(0), lhs_length(0) {}
Index volatile sync;
int volatile users;
Index lhs_start;
Index lhs_length;
};
template<bool Condition, typename Functor, typename Index>
void parallelize_gemm(const Functor& func, Index rows, Index cols, Index depth, bool transpose)
{
// TODO when EIGEN_USE_BLAS is defined,
// we should still enable OMP for other scalar types
#if !(defined (EIGEN_HAS_OPENMP)) || defined (EIGEN_USE_BLAS)
// FIXME the transpose variable is only needed to properly split
// the matrix product when multithreading is enabled. This is a temporary
// fix to support row-major destination matrices. This whole
// parallelizer mechanism has to be redisigned anyway.
EIGEN_UNUSED_VARIABLE(depth);
EIGEN_UNUSED_VARIABLE(transpose);
func(0,rows, 0,cols);
#else
// Dynamically check whether we should enable or disable OpenMP.
// The conditions are:
// - the max number of threads we can create is greater than 1
// - we are not already in a parallel code
// - the sizes are large enough
// compute the maximal number of threads from the size of the product:
// This first heuristic takes into account that the product kernel is fully optimized when working with nr columns at once.
Index size = transpose ? rows : cols;
Index pb_max_threads = std::max<Index>(1,size / Functor::Traits::nr);
// compute the maximal number of threads from the total amount of work:
double work = static_cast<double>(rows) * static_cast<double>(cols) *
static_cast<double>(depth);
double kMinTaskSize = 50000; // FIXME improve this heuristic.
pb_max_threads = std::max<Index>(1, std::min<Index>(pb_max_threads, work / kMinTaskSize));
// compute the number of threads we are going to use
Index threads = std::min<Index>(nbThreads(), pb_max_threads);
// if multi-threading is explicitely disabled, not useful, or if we already are in a parallel session,
// then abort multi-threading
// FIXME omp_get_num_threads()>1 only works for openmp, what if the user does not use openmp?
if((!Condition) || (threads==1) || (omp_get_num_threads()>1))
return func(0,rows, 0,cols);
Eigen::initParallel();
func.initParallelSession(threads);
if(transpose)
std::swap(rows,cols);
ei_declare_aligned_stack_constructed_variable(GemmParallelInfo<Index>,info,threads,0);
#pragma omp parallel num_threads(threads)
{
Index i = omp_get_thread_num();
// Note that the actual number of threads might be lower than the number of request ones.
Index actual_threads = omp_get_num_threads();
Index blockCols = (cols / actual_threads) & ~Index(0x3);
Index blockRows = (rows / actual_threads);
blockRows = (blockRows/Functor::Traits::mr)*Functor::Traits::mr;
Index r0 = i*blockRows;
Index actualBlockRows = (i+1==actual_threads) ? rows-r0 : blockRows;
Index c0 = i*blockCols;
Index actualBlockCols = (i+1==actual_threads) ? cols-c0 : blockCols;
info[i].lhs_start = r0;
info[i].lhs_length = actualBlockRows;
if(transpose) func(c0, actualBlockCols, 0, rows, info);
else func(0, rows, c0, actualBlockCols, info);
}
#endif
}
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_PARALLELIZER_H
| 4,905 | 28.914634 | 125 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/products/TriangularMatrixMatrix.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_MATRIX_MATRIX_H
#define EIGEN_TRIANGULAR_MATRIX_MATRIX_H
namespace Eigen {
namespace internal {
// template<typename Scalar, int mr, int StorageOrder, bool Conjugate, int Mode>
// struct gemm_pack_lhs_triangular
// {
// Matrix<Scalar,mr,mr,
// void operator()(Scalar* blockA, const EIGEN_RESTRICT Scalar* _lhs, int lhsStride, int depth, int rows)
// {
// conj_if<NumTraits<Scalar>::IsComplex && Conjugate> cj;
// const_blas_data_mapper<Scalar, StorageOrder> lhs(_lhs,lhsStride);
// int count = 0;
// const int peeled_mc = (rows/mr)*mr;
// for(int i=0; i<peeled_mc; i+=mr)
// {
// for(int k=0; k<depth; k++)
// for(int w=0; w<mr; w++)
// blockA[count++] = cj(lhs(i+w, k));
// }
// for(int i=peeled_mc; i<rows; i++)
// {
// for(int k=0; k<depth; k++)
// blockA[count++] = cj(lhs(i, k));
// }
// }
// };
/* Optimized triangular matrix * matrix (_TRMM++) product built on top of
* the general matrix matrix product.
*/
template <typename Scalar, typename Index,
int Mode, bool LhsIsTriangular,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs,
int ResStorageOrder, int Version = Specialized>
struct product_triangular_matrix_matrix;
template <typename Scalar, typename Index,
int Mode, bool LhsIsTriangular,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,LhsIsTriangular,
LhsStorageOrder,ConjugateLhs,
RhsStorageOrder,ConjugateRhs,RowMajor,Version>
{
static EIGEN_STRONG_INLINE void run(
Index rows, Index cols, Index depth,
const Scalar* lhs, Index lhsStride,
const Scalar* rhs, Index rhsStride,
Scalar* res, Index resStride,
const Scalar& alpha, level3_blocking<Scalar,Scalar>& blocking)
{
product_triangular_matrix_matrix<Scalar, Index,
(Mode&(UnitDiag|ZeroDiag)) | ((Mode&Upper) ? Lower : Upper),
(!LhsIsTriangular),
RhsStorageOrder==RowMajor ? ColMajor : RowMajor,
ConjugateRhs,
LhsStorageOrder==RowMajor ? ColMajor : RowMajor,
ConjugateLhs,
ColMajor>
::run(cols, rows, depth, rhs, rhsStride, lhs, lhsStride, res, resStride, alpha, blocking);
}
};
// implements col-major += alpha * op(triangular) * op(general)
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,true,
LhsStorageOrder,ConjugateLhs,
RhsStorageOrder,ConjugateRhs,ColMajor,Version>
{
typedef gebp_traits<Scalar,Scalar> Traits;
enum {
SmallPanelWidth = 2 * EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
IsLower = (Mode&Lower) == Lower,
SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1
};
static EIGEN_DONT_INLINE void run(
Index _rows, Index _cols, Index _depth,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* res, Index resStride,
const Scalar& alpha, level3_blocking<Scalar,Scalar>& blocking);
};
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs, int Version>
EIGEN_DONT_INLINE void product_triangular_matrix_matrix<Scalar,Index,Mode,true,
LhsStorageOrder,ConjugateLhs,
RhsStorageOrder,ConjugateRhs,ColMajor,Version>::run(
Index _rows, Index _cols, Index _depth,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* _res, Index resStride,
const Scalar& alpha, level3_blocking<Scalar,Scalar>& blocking)
{
// strip zeros
Index diagSize = (std::min)(_rows,_depth);
Index rows = IsLower ? _rows : diagSize;
Index depth = IsLower ? diagSize : _depth;
Index cols = _cols;
typedef const_blas_data_mapper<Scalar, Index, LhsStorageOrder> LhsMapper;
typedef const_blas_data_mapper<Scalar, Index, RhsStorageOrder> RhsMapper;
typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor> ResMapper;
LhsMapper lhs(_lhs,lhsStride);
RhsMapper rhs(_rhs,rhsStride);
ResMapper res(_res, resStride);
Index kc = blocking.kc(); // cache block size along the K direction
Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
// The small panel size must not be larger than blocking size.
// Usually this should never be the case because SmallPanelWidth^2 is very small
// compared to L2 cache size, but let's be safe:
Index panelWidth = (std::min)(Index(SmallPanelWidth),(std::min)(kc,mc));
std::size_t sizeA = kc*mc;
std::size_t sizeB = kc*cols;
ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
// To work around an "error: member reference base type 'Matrix<...>
// (Eigen::internal::constructor_without_unaligned_array_assert (*)())' is
// not a structure or union" compilation error in nvcc (tested V8.0.61),
// create a dummy internal::constructor_without_unaligned_array_assert
// object to pass to the Matrix constructor.
internal::constructor_without_unaligned_array_assert a;
Matrix<Scalar,SmallPanelWidth,SmallPanelWidth,LhsStorageOrder> triangularBuffer(a);
triangularBuffer.setZero();
if((Mode&ZeroDiag)==ZeroDiag)
triangularBuffer.diagonal().setZero();
else
triangularBuffer.diagonal().setOnes();
gebp_kernel<Scalar, Scalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp_kernel;
gemm_pack_lhs<Scalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, LhsStorageOrder> pack_lhs;
gemm_pack_rhs<Scalar, Index, RhsMapper, Traits::nr,RhsStorageOrder> pack_rhs;
for(Index k2=IsLower ? depth : 0;
IsLower ? k2>0 : k2<depth;
IsLower ? k2-=kc : k2+=kc)
{
Index actual_kc = (std::min)(IsLower ? k2 : depth-k2, kc);
Index actual_k2 = IsLower ? k2-actual_kc : k2;
// align blocks with the end of the triangular part for trapezoidal lhs
if((!IsLower)&&(k2<rows)&&(k2+actual_kc>rows))
{
actual_kc = rows-k2;
k2 = k2+actual_kc-kc;
}
pack_rhs(blockB, rhs.getSubMapper(actual_k2,0), actual_kc, cols);
// the selected lhs's panel has to be split in three different parts:
// 1 - the part which is zero => skip it
// 2 - the diagonal block => special kernel
// 3 - the dense panel below (lower case) or above (upper case) the diagonal block => GEPP
// the block diagonal, if any:
if(IsLower || actual_k2<rows)
{
// for each small vertical panels of lhs
for (Index k1=0; k1<actual_kc; k1+=panelWidth)
{
Index actualPanelWidth = std::min<Index>(actual_kc-k1, panelWidth);
Index lengthTarget = IsLower ? actual_kc-k1-actualPanelWidth : k1;
Index startBlock = actual_k2+k1;
Index blockBOffset = k1;
// => GEBP with the micro triangular block
// The trick is to pack this micro block while filling the opposite triangular part with zeros.
// To this end we do an extra triangular copy to a small temporary buffer
for (Index k=0;k<actualPanelWidth;++k)
{
if (SetDiag)
triangularBuffer.coeffRef(k,k) = lhs(startBlock+k,startBlock+k);
for (Index i=IsLower ? k+1 : 0; IsLower ? i<actualPanelWidth : i<k; ++i)
triangularBuffer.coeffRef(i,k) = lhs(startBlock+i,startBlock+k);
}
pack_lhs(blockA, LhsMapper(triangularBuffer.data(), triangularBuffer.outerStride()), actualPanelWidth, actualPanelWidth);
gebp_kernel(res.getSubMapper(startBlock, 0), blockA, blockB,
actualPanelWidth, actualPanelWidth, cols, alpha,
actualPanelWidth, actual_kc, 0, blockBOffset);
// GEBP with remaining micro panel
if (lengthTarget>0)
{
Index startTarget = IsLower ? actual_k2+k1+actualPanelWidth : actual_k2;
pack_lhs(blockA, lhs.getSubMapper(startTarget,startBlock), actualPanelWidth, lengthTarget);
gebp_kernel(res.getSubMapper(startTarget, 0), blockA, blockB,
lengthTarget, actualPanelWidth, cols, alpha,
actualPanelWidth, actual_kc, 0, blockBOffset);
}
}
}
// the part below (lower case) or above (upper case) the diagonal => GEPP
{
Index start = IsLower ? k2 : 0;
Index end = IsLower ? rows : (std::min)(actual_k2,rows);
for(Index i2=start; i2<end; i2+=mc)
{
const Index actual_mc = (std::min)(i2+mc,end)-i2;
gemm_pack_lhs<Scalar, Index, LhsMapper, Traits::mr,Traits::LhsProgress, LhsStorageOrder,false>()
(blockA, lhs.getSubMapper(i2, actual_k2), actual_kc, actual_mc);
gebp_kernel(res.getSubMapper(i2, 0), blockA, blockB, actual_mc,
actual_kc, cols, alpha, -1, -1, 0, 0);
}
}
}
}
// implements col-major += alpha * op(general) * op(triangular)
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs, int Version>
struct product_triangular_matrix_matrix<Scalar,Index,Mode,false,
LhsStorageOrder,ConjugateLhs,
RhsStorageOrder,ConjugateRhs,ColMajor,Version>
{
typedef gebp_traits<Scalar,Scalar> Traits;
enum {
SmallPanelWidth = EIGEN_PLAIN_ENUM_MAX(Traits::mr,Traits::nr),
IsLower = (Mode&Lower) == Lower,
SetDiag = (Mode&(ZeroDiag|UnitDiag)) ? 0 : 1
};
static EIGEN_DONT_INLINE void run(
Index _rows, Index _cols, Index _depth,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* res, Index resStride,
const Scalar& alpha, level3_blocking<Scalar,Scalar>& blocking);
};
template <typename Scalar, typename Index, int Mode,
int LhsStorageOrder, bool ConjugateLhs,
int RhsStorageOrder, bool ConjugateRhs, int Version>
EIGEN_DONT_INLINE void product_triangular_matrix_matrix<Scalar,Index,Mode,false,
LhsStorageOrder,ConjugateLhs,
RhsStorageOrder,ConjugateRhs,ColMajor,Version>::run(
Index _rows, Index _cols, Index _depth,
const Scalar* _lhs, Index lhsStride,
const Scalar* _rhs, Index rhsStride,
Scalar* _res, Index resStride,
const Scalar& alpha, level3_blocking<Scalar,Scalar>& blocking)
{
const Index PacketBytes = packet_traits<Scalar>::size*sizeof(Scalar);
// strip zeros
Index diagSize = (std::min)(_cols,_depth);
Index rows = _rows;
Index depth = IsLower ? _depth : diagSize;
Index cols = IsLower ? diagSize : _cols;
typedef const_blas_data_mapper<Scalar, Index, LhsStorageOrder> LhsMapper;
typedef const_blas_data_mapper<Scalar, Index, RhsStorageOrder> RhsMapper;
typedef blas_data_mapper<typename Traits::ResScalar, Index, ColMajor> ResMapper;
LhsMapper lhs(_lhs,lhsStride);
RhsMapper rhs(_rhs,rhsStride);
ResMapper res(_res, resStride);
Index kc = blocking.kc(); // cache block size along the K direction
Index mc = (std::min)(rows,blocking.mc()); // cache block size along the M direction
std::size_t sizeA = kc*mc;
std::size_t sizeB = kc*cols+EIGEN_MAX_ALIGN_BYTES/sizeof(Scalar);
ei_declare_aligned_stack_constructed_variable(Scalar, blockA, sizeA, blocking.blockA());
ei_declare_aligned_stack_constructed_variable(Scalar, blockB, sizeB, blocking.blockB());
internal::constructor_without_unaligned_array_assert a;
Matrix<Scalar,SmallPanelWidth,SmallPanelWidth,RhsStorageOrder> triangularBuffer(a);
triangularBuffer.setZero();
if((Mode&ZeroDiag)==ZeroDiag)
triangularBuffer.diagonal().setZero();
else
triangularBuffer.diagonal().setOnes();
gebp_kernel<Scalar, Scalar, Index, ResMapper, Traits::mr, Traits::nr, ConjugateLhs, ConjugateRhs> gebp_kernel;
gemm_pack_lhs<Scalar, Index, LhsMapper, Traits::mr, Traits::LhsProgress, LhsStorageOrder> pack_lhs;
gemm_pack_rhs<Scalar, Index, RhsMapper, Traits::nr,RhsStorageOrder> pack_rhs;
gemm_pack_rhs<Scalar, Index, RhsMapper, Traits::nr,RhsStorageOrder,false,true> pack_rhs_panel;
for(Index k2=IsLower ? 0 : depth;
IsLower ? k2<depth : k2>0;
IsLower ? k2+=kc : k2-=kc)
{
Index actual_kc = (std::min)(IsLower ? depth-k2 : k2, kc);
Index actual_k2 = IsLower ? k2 : k2-actual_kc;
// align blocks with the end of the triangular part for trapezoidal rhs
if(IsLower && (k2<cols) && (actual_k2+actual_kc>cols))
{
actual_kc = cols-k2;
k2 = actual_k2 + actual_kc - kc;
}
// remaining size
Index rs = IsLower ? (std::min)(cols,actual_k2) : cols - k2;
// size of the triangular part
Index ts = (IsLower && actual_k2>=cols) ? 0 : actual_kc;
Scalar* geb = blockB+ts*ts;
geb = geb + internal::first_aligned<PacketBytes>(geb,PacketBytes/sizeof(Scalar));
pack_rhs(geb, rhs.getSubMapper(actual_k2,IsLower ? 0 : k2), actual_kc, rs);
// pack the triangular part of the rhs padding the unrolled blocks with zeros
if(ts>0)
{
for (Index j2=0; j2<actual_kc; j2+=SmallPanelWidth)
{
Index actualPanelWidth = std::min<Index>(actual_kc-j2, SmallPanelWidth);
Index actual_j2 = actual_k2 + j2;
Index panelOffset = IsLower ? j2+actualPanelWidth : 0;
Index panelLength = IsLower ? actual_kc-j2-actualPanelWidth : j2;
// general part
pack_rhs_panel(blockB+j2*actual_kc,
rhs.getSubMapper(actual_k2+panelOffset, actual_j2),
panelLength, actualPanelWidth,
actual_kc, panelOffset);
// append the triangular part via a temporary buffer
for (Index j=0;j<actualPanelWidth;++j)
{
if (SetDiag)
triangularBuffer.coeffRef(j,j) = rhs(actual_j2+j,actual_j2+j);
for (Index k=IsLower ? j+1 : 0; IsLower ? k<actualPanelWidth : k<j; ++k)
triangularBuffer.coeffRef(k,j) = rhs(actual_j2+k,actual_j2+j);
}
pack_rhs_panel(blockB+j2*actual_kc,
RhsMapper(triangularBuffer.data(), triangularBuffer.outerStride()),
actualPanelWidth, actualPanelWidth,
actual_kc, j2);
}
}
for (Index i2=0; i2<rows; i2+=mc)
{
const Index actual_mc = (std::min)(mc,rows-i2);
pack_lhs(blockA, lhs.getSubMapper(i2, actual_k2), actual_kc, actual_mc);
// triangular kernel
if(ts>0)
{
for (Index j2=0; j2<actual_kc; j2+=SmallPanelWidth)
{
Index actualPanelWidth = std::min<Index>(actual_kc-j2, SmallPanelWidth);
Index panelLength = IsLower ? actual_kc-j2 : j2+actualPanelWidth;
Index blockOffset = IsLower ? j2 : 0;
gebp_kernel(res.getSubMapper(i2, actual_k2 + j2),
blockA, blockB+j2*actual_kc,
actual_mc, panelLength, actualPanelWidth,
alpha,
actual_kc, actual_kc, // strides
blockOffset, blockOffset);// offsets
}
}
gebp_kernel(res.getSubMapper(i2, IsLower ? 0 : k2),
blockA, geb, actual_mc, actual_kc, rs,
alpha,
-1, -1, 0, 0);
}
}
}
/***************************************************************************
* Wrapper to product_triangular_matrix_matrix
***************************************************************************/
} // end namespace internal
namespace internal {
template<int Mode, bool LhsIsTriangular, typename Lhs, typename Rhs>
struct triangular_product_impl<Mode,LhsIsTriangular,Lhs,false,Rhs,false>
{
template<typename Dest> static void run(Dest& dst, const Lhs &a_lhs, const Rhs &a_rhs, const typename Dest::Scalar& alpha)
{
typedef typename Lhs::Scalar LhsScalar;
typedef typename Rhs::Scalar RhsScalar;
typedef typename Dest::Scalar Scalar;
typedef internal::blas_traits<Lhs> LhsBlasTraits;
typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType;
typedef typename internal::remove_all<ActualLhsType>::type ActualLhsTypeCleaned;
typedef internal::blas_traits<Rhs> RhsBlasTraits;
typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType;
typedef typename internal::remove_all<ActualRhsType>::type ActualRhsTypeCleaned;
typename internal::add_const_on_value_type<ActualLhsType>::type lhs = LhsBlasTraits::extract(a_lhs);
typename internal::add_const_on_value_type<ActualRhsType>::type rhs = RhsBlasTraits::extract(a_rhs);
LhsScalar lhs_alpha = LhsBlasTraits::extractScalarFactor(a_lhs);
RhsScalar rhs_alpha = RhsBlasTraits::extractScalarFactor(a_rhs);
Scalar actualAlpha = alpha * lhs_alpha * rhs_alpha;
typedef internal::gemm_blocking_space<(Dest::Flags&RowMajorBit) ? RowMajor : ColMajor,Scalar,Scalar,
Lhs::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime, Lhs::MaxColsAtCompileTime,4> BlockingType;
enum { IsLower = (Mode&Lower) == Lower };
Index stripedRows = ((!LhsIsTriangular) || (IsLower)) ? lhs.rows() : (std::min)(lhs.rows(),lhs.cols());
Index stripedCols = ((LhsIsTriangular) || (!IsLower)) ? rhs.cols() : (std::min)(rhs.cols(),rhs.rows());
Index stripedDepth = LhsIsTriangular ? ((!IsLower) ? lhs.cols() : (std::min)(lhs.cols(),lhs.rows()))
: ((IsLower) ? rhs.rows() : (std::min)(rhs.rows(),rhs.cols()));
BlockingType blocking(stripedRows, stripedCols, stripedDepth, 1, false);
internal::product_triangular_matrix_matrix<Scalar, Index,
Mode, LhsIsTriangular,
(internal::traits<ActualLhsTypeCleaned>::Flags&RowMajorBit) ? RowMajor : ColMajor, LhsBlasTraits::NeedToConjugate,
(internal::traits<ActualRhsTypeCleaned>::Flags&RowMajorBit) ? RowMajor : ColMajor, RhsBlasTraits::NeedToConjugate,
(internal::traits<Dest >::Flags&RowMajorBit) ? RowMajor : ColMajor>
::run(
stripedRows, stripedCols, stripedDepth, // sizes
&lhs.coeffRef(0,0), lhs.outerStride(), // lhs info
&rhs.coeffRef(0,0), rhs.outerStride(), // rhs info
&dst.coeffRef(0,0), dst.outerStride(), // result info
actualAlpha, blocking
);
// Apply correction if the diagonal is unit and a scalar factor was nested:
if ((Mode&UnitDiag)==UnitDiag)
{
if (LhsIsTriangular && lhs_alpha!=LhsScalar(1))
{
Index diagSize = (std::min)(lhs.rows(),lhs.cols());
dst.topRows(diagSize) -= ((lhs_alpha-LhsScalar(1))*a_rhs).topRows(diagSize);
}
else if ((!LhsIsTriangular) && rhs_alpha!=RhsScalar(1))
{
Index diagSize = (std::min)(rhs.rows(),rhs.cols());
dst.leftCols(diagSize) -= (rhs_alpha-RhsScalar(1))*a_lhs.leftCols(diagSize);
}
}
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TRIANGULAR_MATRIX_MATRIX_H
| 20,403 | 42.691649 | 131 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/products/TriangularSolverVector.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_TRIANGULAR_SOLVER_VECTOR_H
#define EIGEN_TRIANGULAR_SOLVER_VECTOR_H
namespace Eigen {
namespace internal {
template<typename LhsScalar, typename RhsScalar, typename Index, int Mode, bool Conjugate, int StorageOrder>
struct triangular_solve_vector<LhsScalar, RhsScalar, Index, OnTheRight, Mode, Conjugate, StorageOrder>
{
static void run(Index size, const LhsScalar* _lhs, Index lhsStride, RhsScalar* rhs)
{
triangular_solve_vector<LhsScalar,RhsScalar,Index,OnTheLeft,
((Mode&Upper)==Upper ? Lower : Upper) | (Mode&UnitDiag),
Conjugate,StorageOrder==RowMajor?ColMajor:RowMajor
>::run(size, _lhs, lhsStride, rhs);
}
};
// forward and backward substitution, row-major, rhs is a vector
template<typename LhsScalar, typename RhsScalar, typename Index, int Mode, bool Conjugate>
struct triangular_solve_vector<LhsScalar, RhsScalar, Index, OnTheLeft, Mode, Conjugate, RowMajor>
{
enum {
IsLower = ((Mode&Lower)==Lower)
};
static void run(Index size, const LhsScalar* _lhs, Index lhsStride, RhsScalar* rhs)
{
typedef Map<const Matrix<LhsScalar,Dynamic,Dynamic,RowMajor>, 0, OuterStride<> > LhsMap;
const LhsMap lhs(_lhs,size,size,OuterStride<>(lhsStride));
typedef const_blas_data_mapper<LhsScalar,Index,RowMajor> LhsMapper;
typedef const_blas_data_mapper<RhsScalar,Index,ColMajor> RhsMapper;
typename internal::conditional<
Conjugate,
const CwiseUnaryOp<typename internal::scalar_conjugate_op<LhsScalar>,LhsMap>,
const LhsMap&>
::type cjLhs(lhs);
static const Index PanelWidth = EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH;
for(Index pi=IsLower ? 0 : size;
IsLower ? pi<size : pi>0;
IsLower ? pi+=PanelWidth : pi-=PanelWidth)
{
Index actualPanelWidth = (std::min)(IsLower ? size - pi : pi, PanelWidth);
Index r = IsLower ? pi : size - pi; // remaining size
if (r > 0)
{
// let's directly call the low level product function because:
// 1 - it is faster to compile
// 2 - it is slighlty faster at runtime
Index startRow = IsLower ? pi : pi-actualPanelWidth;
Index startCol = IsLower ? 0 : pi;
general_matrix_vector_product<Index,LhsScalar,LhsMapper,RowMajor,Conjugate,RhsScalar,RhsMapper,false>::run(
actualPanelWidth, r,
LhsMapper(&lhs.coeffRef(startRow,startCol), lhsStride),
RhsMapper(rhs + startCol, 1),
rhs + startRow, 1,
RhsScalar(-1));
}
for(Index k=0; k<actualPanelWidth; ++k)
{
Index i = IsLower ? pi+k : pi-k-1;
Index s = IsLower ? pi : i+1;
if (k>0)
rhs[i] -= (cjLhs.row(i).segment(s,k).transpose().cwiseProduct(Map<const Matrix<RhsScalar,Dynamic,1> >(rhs+s,k))).sum();
if(!(Mode & UnitDiag))
rhs[i] /= cjLhs(i,i);
}
}
}
};
// forward and backward substitution, column-major, rhs is a vector
template<typename LhsScalar, typename RhsScalar, typename Index, int Mode, bool Conjugate>
struct triangular_solve_vector<LhsScalar, RhsScalar, Index, OnTheLeft, Mode, Conjugate, ColMajor>
{
enum {
IsLower = ((Mode&Lower)==Lower)
};
static void run(Index size, const LhsScalar* _lhs, Index lhsStride, RhsScalar* rhs)
{
typedef Map<const Matrix<LhsScalar,Dynamic,Dynamic,ColMajor>, 0, OuterStride<> > LhsMap;
const LhsMap lhs(_lhs,size,size,OuterStride<>(lhsStride));
typedef const_blas_data_mapper<LhsScalar,Index,ColMajor> LhsMapper;
typedef const_blas_data_mapper<RhsScalar,Index,ColMajor> RhsMapper;
typename internal::conditional<Conjugate,
const CwiseUnaryOp<typename internal::scalar_conjugate_op<LhsScalar>,LhsMap>,
const LhsMap&
>::type cjLhs(lhs);
static const Index PanelWidth = EIGEN_TUNE_TRIANGULAR_PANEL_WIDTH;
for(Index pi=IsLower ? 0 : size;
IsLower ? pi<size : pi>0;
IsLower ? pi+=PanelWidth : pi-=PanelWidth)
{
Index actualPanelWidth = (std::min)(IsLower ? size - pi : pi, PanelWidth);
Index startBlock = IsLower ? pi : pi-actualPanelWidth;
Index endBlock = IsLower ? pi + actualPanelWidth : 0;
for(Index k=0; k<actualPanelWidth; ++k)
{
Index i = IsLower ? pi+k : pi-k-1;
if(!(Mode & UnitDiag))
rhs[i] /= cjLhs.coeff(i,i);
Index r = actualPanelWidth - k - 1; // remaining size
Index s = IsLower ? i+1 : i-r;
if (r>0)
Map<Matrix<RhsScalar,Dynamic,1> >(rhs+s,r) -= rhs[i] * cjLhs.col(i).segment(s,r);
}
Index r = IsLower ? size - endBlock : startBlock; // remaining size
if (r > 0)
{
// let's directly call the low level product function because:
// 1 - it is faster to compile
// 2 - it is slighlty faster at runtime
general_matrix_vector_product<Index,LhsScalar,LhsMapper,ColMajor,Conjugate,RhsScalar,RhsMapper,false>::run(
r, actualPanelWidth,
LhsMapper(&lhs.coeffRef(endBlock,startBlock), lhsStride),
RhsMapper(rhs+startBlock, 1),
rhs+endBlock, 1, RhsScalar(-1));
}
}
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_TRIANGULAR_SOLVER_VECTOR_H
| 5,741 | 38.328767 | 129 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/util/MKL_support.h
|
/*
Copyright (c) 2011, Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************
* Content : Eigen bindings to Intel(R) MKL
* Include file with common MKL declarations
********************************************************************************
*/
#ifndef EIGEN_MKL_SUPPORT_H
#define EIGEN_MKL_SUPPORT_H
#ifdef EIGEN_USE_MKL_ALL
#ifndef EIGEN_USE_BLAS
#define EIGEN_USE_BLAS
#endif
#ifndef EIGEN_USE_LAPACKE
#define EIGEN_USE_LAPACKE
#endif
#ifndef EIGEN_USE_MKL_VML
#define EIGEN_USE_MKL_VML
#endif
#endif
#ifdef EIGEN_USE_LAPACKE_STRICT
#define EIGEN_USE_LAPACKE
#endif
#if defined(EIGEN_USE_MKL_VML) && !defined(EIGEN_USE_MKL)
#define EIGEN_USE_MKL
#endif
#if defined EIGEN_USE_MKL
# include <mkl.h>
/*Check IMKL version for compatibility: < 10.3 is not usable with Eigen*/
# ifndef INTEL_MKL_VERSION
# undef EIGEN_USE_MKL /* INTEL_MKL_VERSION is not even defined on older versions */
# elif INTEL_MKL_VERSION < 100305 /* the intel-mkl-103-release-notes say this was when the lapacke.h interface was added*/
# undef EIGEN_USE_MKL
# endif
# ifndef EIGEN_USE_MKL
/*If the MKL version is too old, undef everything*/
# undef EIGEN_USE_MKL_ALL
# undef EIGEN_USE_LAPACKE
# undef EIGEN_USE_MKL_VML
# undef EIGEN_USE_LAPACKE_STRICT
# undef EIGEN_USE_LAPACKE
# endif
#endif
#if defined EIGEN_USE_MKL
#define EIGEN_MKL_VML_THRESHOLD 128
/* MKL_DOMAIN_BLAS, etc are defined only in 10.3 update 7 */
/* MKL_BLAS, etc are not defined in 11.2 */
#ifdef MKL_DOMAIN_ALL
#define EIGEN_MKL_DOMAIN_ALL MKL_DOMAIN_ALL
#else
#define EIGEN_MKL_DOMAIN_ALL MKL_ALL
#endif
#ifdef MKL_DOMAIN_BLAS
#define EIGEN_MKL_DOMAIN_BLAS MKL_DOMAIN_BLAS
#else
#define EIGEN_MKL_DOMAIN_BLAS MKL_BLAS
#endif
#ifdef MKL_DOMAIN_FFT
#define EIGEN_MKL_DOMAIN_FFT MKL_DOMAIN_FFT
#else
#define EIGEN_MKL_DOMAIN_FFT MKL_FFT
#endif
#ifdef MKL_DOMAIN_VML
#define EIGEN_MKL_DOMAIN_VML MKL_DOMAIN_VML
#else
#define EIGEN_MKL_DOMAIN_VML MKL_VML
#endif
#ifdef MKL_DOMAIN_PARDISO
#define EIGEN_MKL_DOMAIN_PARDISO MKL_DOMAIN_PARDISO
#else
#define EIGEN_MKL_DOMAIN_PARDISO MKL_PARDISO
#endif
#endif
#if defined(EIGEN_USE_BLAS) && !defined(EIGEN_USE_MKL)
#include "../../misc/blas.h"
#endif
namespace Eigen {
typedef std::complex<double> dcomplex;
typedef std::complex<float> scomplex;
#if defined(EIGEN_USE_MKL)
typedef MKL_INT BlasIndex;
#else
typedef int BlasIndex;
#endif
} // end namespace Eigen
#endif // EIGEN_MKL_SUPPORT_H
| 4,026 | 29.740458 | 127 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Core/util/ReenableStupidWarnings.h
|
#ifdef EIGEN_WARNINGS_DISABLED
#undef EIGEN_WARNINGS_DISABLED
#ifndef EIGEN_PERMANENTLY_DISABLE_STUPID_WARNINGS
#ifdef _MSC_VER
#pragma warning( pop )
#elif defined __INTEL_COMPILER
#pragma warning pop
#elif defined __clang__
#pragma clang diagnostic pop
#elif defined __GNUC__ && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
#pragma GCC diagnostic pop
#endif
#if defined __NVCC__
// Don't reenable the diagnostic messages, as it turns out these messages need
// to be disabled at the point of the template instantiation (i.e the user code)
// otherwise they'll be triggered by nvcc.
// #pragma diag_default code_is_unreachable
// #pragma diag_default initialization_not_reachable
// #pragma diag_default 2651
// #pragma diag_default 2653
#endif
#endif
#endif // EIGEN_WARNINGS_DISABLED
| 856 | 29.607143 | 86 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2010 Gael Guennebaud <[email protected]>
// Copyright (C) 2010 Jitse Niesen <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
#define EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
#include "./Tridiagonalization.h"
namespace Eigen {
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
* \class GeneralizedSelfAdjointEigenSolver
*
* \brief Computes eigenvalues and eigenvectors of the generalized selfadjoint eigen problem
*
* \tparam _MatrixType the type of the matrix of which we are computing the
* eigendecomposition; this is expected to be an instantiation of the Matrix
* class template.
*
* This class solves the generalized eigenvalue problem
* \f$ Av = \lambda Bv \f$. In this case, the matrix \f$ A \f$ should be
* selfadjoint and the matrix \f$ B \f$ should be positive definite.
*
* Only the \b lower \b triangular \b part of the input matrix is referenced.
*
* Call the function compute() to compute the eigenvalues and eigenvectors of
* a given matrix. Alternatively, you can use the
* GeneralizedSelfAdjointEigenSolver(const MatrixType&, const MatrixType&, int)
* constructor which computes the eigenvalues and eigenvectors at construction time.
* Once the eigenvalue and eigenvectors are computed, they can be retrieved with the eigenvalues()
* and eigenvectors() functions.
*
* The documentation for GeneralizedSelfAdjointEigenSolver(const MatrixType&, const MatrixType&, int)
* contains an example of the typical use of this class.
*
* \sa class SelfAdjointEigenSolver, class EigenSolver, class ComplexEigenSolver
*/
template<typename _MatrixType>
class GeneralizedSelfAdjointEigenSolver : public SelfAdjointEigenSolver<_MatrixType>
{
typedef SelfAdjointEigenSolver<_MatrixType> Base;
public:
typedef _MatrixType MatrixType;
/** \brief Default constructor for fixed-size matrices.
*
* The default constructor is useful in cases in which the user intends to
* perform decompositions via compute(). This constructor
* can only be used if \p _MatrixType is a fixed-size matrix; use
* GeneralizedSelfAdjointEigenSolver(Index) for dynamic-size matrices.
*/
GeneralizedSelfAdjointEigenSolver() : Base() {}
/** \brief Constructor, pre-allocates memory for dynamic-size matrices.
*
* \param [in] size Positive integer, size of the matrix whose
* eigenvalues and eigenvectors will be computed.
*
* This constructor is useful for dynamic-size matrices, when the user
* intends to perform decompositions via compute(). The \p size
* parameter is only used as a hint. It is not an error to give a wrong
* \p size, but it may impair performance.
*
* \sa compute() for an example
*/
explicit GeneralizedSelfAdjointEigenSolver(Index size)
: Base(size)
{}
/** \brief Constructor; computes generalized eigendecomposition of given matrix pencil.
*
* \param[in] matA Selfadjoint matrix in matrix pencil.
* Only the lower triangular part of the matrix is referenced.
* \param[in] matB Positive-definite matrix in matrix pencil.
* Only the lower triangular part of the matrix is referenced.
* \param[in] options A or-ed set of flags {#ComputeEigenvectors,#EigenvaluesOnly} | {#Ax_lBx,#ABx_lx,#BAx_lx}.
* Default is #ComputeEigenvectors|#Ax_lBx.
*
* This constructor calls compute(const MatrixType&, const MatrixType&, int)
* to compute the eigenvalues and (if requested) the eigenvectors of the
* generalized eigenproblem \f$ Ax = \lambda B x \f$ with \a matA the
* selfadjoint matrix \f$ A \f$ and \a matB the positive definite matrix
* \f$ B \f$. Each eigenvector \f$ x \f$ satisfies the property
* \f$ x^* B x = 1 \f$. The eigenvectors are computed if
* \a options contains ComputeEigenvectors.
*
* In addition, the two following variants can be solved via \p options:
* - \c ABx_lx: \f$ ABx = \lambda x \f$
* - \c BAx_lx: \f$ BAx = \lambda x \f$
*
* Example: \include SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType2.cpp
* Output: \verbinclude SelfAdjointEigenSolver_SelfAdjointEigenSolver_MatrixType2.out
*
* \sa compute(const MatrixType&, const MatrixType&, int)
*/
GeneralizedSelfAdjointEigenSolver(const MatrixType& matA, const MatrixType& matB,
int options = ComputeEigenvectors|Ax_lBx)
: Base(matA.cols())
{
compute(matA, matB, options);
}
/** \brief Computes generalized eigendecomposition of given matrix pencil.
*
* \param[in] matA Selfadjoint matrix in matrix pencil.
* Only the lower triangular part of the matrix is referenced.
* \param[in] matB Positive-definite matrix in matrix pencil.
* Only the lower triangular part of the matrix is referenced.
* \param[in] options A or-ed set of flags {#ComputeEigenvectors,#EigenvaluesOnly} | {#Ax_lBx,#ABx_lx,#BAx_lx}.
* Default is #ComputeEigenvectors|#Ax_lBx.
*
* \returns Reference to \c *this
*
* Accoring to \p options, this function computes eigenvalues and (if requested)
* the eigenvectors of one of the following three generalized eigenproblems:
* - \c Ax_lBx: \f$ Ax = \lambda B x \f$
* - \c ABx_lx: \f$ ABx = \lambda x \f$
* - \c BAx_lx: \f$ BAx = \lambda x \f$
* with \a matA the selfadjoint matrix \f$ A \f$ and \a matB the positive definite
* matrix \f$ B \f$.
* In addition, each eigenvector \f$ x \f$ satisfies the property \f$ x^* B x = 1 \f$.
*
* The eigenvalues() function can be used to retrieve
* the eigenvalues. If \p options contains ComputeEigenvectors, then the
* eigenvectors are also computed and can be retrieved by calling
* eigenvectors().
*
* The implementation uses LLT to compute the Cholesky decomposition
* \f$ B = LL^* \f$ and computes the classical eigendecomposition
* of the selfadjoint matrix \f$ L^{-1} A (L^*)^{-1} \f$ if \p options contains Ax_lBx
* and of \f$ L^{*} A L \f$ otherwise. This solves the
* generalized eigenproblem, because any solution of the generalized
* eigenproblem \f$ Ax = \lambda B x \f$ corresponds to a solution
* \f$ L^{-1} A (L^*)^{-1} (L^* x) = \lambda (L^* x) \f$ of the
* eigenproblem for \f$ L^{-1} A (L^*)^{-1} \f$. Similar statements
* can be made for the two other variants.
*
* Example: \include SelfAdjointEigenSolver_compute_MatrixType2.cpp
* Output: \verbinclude SelfAdjointEigenSolver_compute_MatrixType2.out
*
* \sa GeneralizedSelfAdjointEigenSolver(const MatrixType&, const MatrixType&, int)
*/
GeneralizedSelfAdjointEigenSolver& compute(const MatrixType& matA, const MatrixType& matB,
int options = ComputeEigenvectors|Ax_lBx);
protected:
};
template<typename MatrixType>
GeneralizedSelfAdjointEigenSolver<MatrixType>& GeneralizedSelfAdjointEigenSolver<MatrixType>::
compute(const MatrixType& matA, const MatrixType& matB, int options)
{
eigen_assert(matA.cols()==matA.rows() && matB.rows()==matA.rows() && matB.cols()==matB.rows());
eigen_assert((options&~(EigVecMask|GenEigMask))==0
&& (options&EigVecMask)!=EigVecMask
&& ((options&GenEigMask)==0 || (options&GenEigMask)==Ax_lBx
|| (options&GenEigMask)==ABx_lx || (options&GenEigMask)==BAx_lx)
&& "invalid option parameter");
bool computeEigVecs = ((options&EigVecMask)==0) || ((options&EigVecMask)==ComputeEigenvectors);
// Compute the cholesky decomposition of matB = L L' = U'U
LLT<MatrixType> cholB(matB);
int type = (options&GenEigMask);
if(type==0)
type = Ax_lBx;
if(type==Ax_lBx)
{
// compute C = inv(L) A inv(L')
MatrixType matC = matA.template selfadjointView<Lower>();
cholB.matrixL().template solveInPlace<OnTheLeft>(matC);
cholB.matrixU().template solveInPlace<OnTheRight>(matC);
Base::compute(matC, computeEigVecs ? ComputeEigenvectors : EigenvaluesOnly );
// transform back the eigen vectors: evecs = inv(U) * evecs
if(computeEigVecs)
cholB.matrixU().solveInPlace(Base::m_eivec);
}
else if(type==ABx_lx)
{
// compute C = L' A L
MatrixType matC = matA.template selfadjointView<Lower>();
matC = matC * cholB.matrixL();
matC = cholB.matrixU() * matC;
Base::compute(matC, computeEigVecs ? ComputeEigenvectors : EigenvaluesOnly);
// transform back the eigen vectors: evecs = inv(U) * evecs
if(computeEigVecs)
cholB.matrixU().solveInPlace(Base::m_eivec);
}
else if(type==BAx_lx)
{
// compute C = L' A L
MatrixType matC = matA.template selfadjointView<Lower>();
matC = matC * cholB.matrixL();
matC = cholB.matrixU() * matC;
Base::compute(matC, computeEigVecs ? ComputeEigenvectors : EigenvaluesOnly);
// transform back the eigen vectors: evecs = L * evecs
if(computeEigVecs)
Base::m_eivec = cholB.matrixL() * Base::m_eivec;
}
return *this;
}
} // end namespace Eigen
#endif // EIGEN_GENERALIZEDSELFADJOINTEIGENSOLVER_H
| 9,715 | 41.801762 | 117 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
// Copyright (C) 2010 Jitse Niesen <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MATRIXBASEEIGENVALUES_H
#define EIGEN_MATRIXBASEEIGENVALUES_H
namespace Eigen {
namespace internal {
template<typename Derived, bool IsComplex>
struct eigenvalues_selector
{
// this is the implementation for the case IsComplex = true
static inline typename MatrixBase<Derived>::EigenvaluesReturnType const
run(const MatrixBase<Derived>& m)
{
typedef typename Derived::PlainObject PlainObject;
PlainObject m_eval(m);
return ComplexEigenSolver<PlainObject>(m_eval, false).eigenvalues();
}
};
template<typename Derived>
struct eigenvalues_selector<Derived, false>
{
static inline typename MatrixBase<Derived>::EigenvaluesReturnType const
run(const MatrixBase<Derived>& m)
{
typedef typename Derived::PlainObject PlainObject;
PlainObject m_eval(m);
return EigenSolver<PlainObject>(m_eval, false).eigenvalues();
}
};
} // end namespace internal
/** \brief Computes the eigenvalues of a matrix
* \returns Column vector containing the eigenvalues.
*
* \eigenvalues_module
* This function computes the eigenvalues with the help of the EigenSolver
* class (for real matrices) or the ComplexEigenSolver class (for complex
* matrices).
*
* The eigenvalues are repeated according to their algebraic multiplicity,
* so there are as many eigenvalues as rows in the matrix.
*
* The SelfAdjointView class provides a better algorithm for selfadjoint
* matrices.
*
* Example: \include MatrixBase_eigenvalues.cpp
* Output: \verbinclude MatrixBase_eigenvalues.out
*
* \sa EigenSolver::eigenvalues(), ComplexEigenSolver::eigenvalues(),
* SelfAdjointView::eigenvalues()
*/
template<typename Derived>
inline typename MatrixBase<Derived>::EigenvaluesReturnType
MatrixBase<Derived>::eigenvalues() const
{
return internal::eigenvalues_selector<Derived, NumTraits<Scalar>::IsComplex>::run(derived());
}
/** \brief Computes the eigenvalues of a matrix
* \returns Column vector containing the eigenvalues.
*
* \eigenvalues_module
* This function computes the eigenvalues with the help of the
* SelfAdjointEigenSolver class. The eigenvalues are repeated according to
* their algebraic multiplicity, so there are as many eigenvalues as rows in
* the matrix.
*
* Example: \include SelfAdjointView_eigenvalues.cpp
* Output: \verbinclude SelfAdjointView_eigenvalues.out
*
* \sa SelfAdjointEigenSolver::eigenvalues(), MatrixBase::eigenvalues()
*/
template<typename MatrixType, unsigned int UpLo>
inline typename SelfAdjointView<MatrixType, UpLo>::EigenvaluesReturnType
SelfAdjointView<MatrixType, UpLo>::eigenvalues() const
{
PlainObject thisAsMatrix(*this);
return SelfAdjointEigenSolver<PlainObject>(thisAsMatrix, false).eigenvalues();
}
/** \brief Computes the L2 operator norm
* \returns Operator norm of the matrix.
*
* \eigenvalues_module
* This function computes the L2 operator norm of a matrix, which is also
* known as the spectral norm. The norm of a matrix \f$ A \f$ is defined to be
* \f[ \|A\|_2 = \max_x \frac{\|Ax\|_2}{\|x\|_2} \f]
* where the maximum is over all vectors and the norm on the right is the
* Euclidean vector norm. The norm equals the largest singular value, which is
* the square root of the largest eigenvalue of the positive semi-definite
* matrix \f$ A^*A \f$.
*
* The current implementation uses the eigenvalues of \f$ A^*A \f$, as computed
* by SelfAdjointView::eigenvalues(), to compute the operator norm of a
* matrix. The SelfAdjointView class provides a better algorithm for
* selfadjoint matrices.
*
* Example: \include MatrixBase_operatorNorm.cpp
* Output: \verbinclude MatrixBase_operatorNorm.out
*
* \sa SelfAdjointView::eigenvalues(), SelfAdjointView::operatorNorm()
*/
template<typename Derived>
inline typename MatrixBase<Derived>::RealScalar
MatrixBase<Derived>::operatorNorm() const
{
using std::sqrt;
typename Derived::PlainObject m_eval(derived());
// FIXME if it is really guaranteed that the eigenvalues are already sorted,
// then we don't need to compute a maxCoeff() here, comparing the 1st and last ones is enough.
return sqrt((m_eval*m_eval.adjoint())
.eval()
.template selfadjointView<Lower>()
.eigenvalues()
.maxCoeff()
);
}
/** \brief Computes the L2 operator norm
* \returns Operator norm of the matrix.
*
* \eigenvalues_module
* This function computes the L2 operator norm of a self-adjoint matrix. For a
* self-adjoint matrix, the operator norm is the largest eigenvalue.
*
* The current implementation uses the eigenvalues of the matrix, as computed
* by eigenvalues(), to compute the operator norm of the matrix.
*
* Example: \include SelfAdjointView_operatorNorm.cpp
* Output: \verbinclude SelfAdjointView_operatorNorm.out
*
* \sa eigenvalues(), MatrixBase::operatorNorm()
*/
template<typename MatrixType, unsigned int UpLo>
inline typename SelfAdjointView<MatrixType, UpLo>::RealScalar
SelfAdjointView<MatrixType, UpLo>::operatorNorm() const
{
return eigenvalues().cwiseAbs().maxCoeff();
}
} // end namespace Eigen
#endif
| 5,539 | 33.842767 | 96 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Eigenvalues/RealQZ.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Alexey Korepanov <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_REAL_QZ_H
#define EIGEN_REAL_QZ_H
namespace Eigen {
/** \eigenvalues_module \ingroup Eigenvalues_Module
*
*
* \class RealQZ
*
* \brief Performs a real QZ decomposition of a pair of square matrices
*
* \tparam _MatrixType the type of the matrix of which we are computing the
* real QZ decomposition; this is expected to be an instantiation of the
* Matrix class template.
*
* Given a real square matrices A and B, this class computes the real QZ
* decomposition: \f$ A = Q S Z \f$, \f$ B = Q T Z \f$ where Q and Z are
* real orthogonal matrixes, T is upper-triangular matrix, and S is upper
* quasi-triangular matrix. An orthogonal matrix is a matrix whose
* inverse is equal to its transpose, \f$ U^{-1} = U^T \f$. A quasi-triangular
* matrix is a block-triangular matrix whose diagonal consists of 1-by-1
* blocks and 2-by-2 blocks where further reduction is impossible due to
* complex eigenvalues.
*
* The eigenvalues of the pencil \f$ A - z B \f$ can be obtained from
* 1x1 and 2x2 blocks on the diagonals of S and T.
*
* Call the function compute() to compute the real QZ decomposition of a
* given pair of matrices. Alternatively, you can use the
* RealQZ(const MatrixType& B, const MatrixType& B, bool computeQZ)
* constructor which computes the real QZ decomposition at construction
* time. Once the decomposition is computed, you can use the matrixS(),
* matrixT(), matrixQ() and matrixZ() functions to retrieve the matrices
* S, T, Q and Z in the decomposition. If computeQZ==false, some time
* is saved by not computing matrices Q and Z.
*
* Example: \include RealQZ_compute.cpp
* Output: \include RealQZ_compute.out
*
* \note The implementation is based on the algorithm in "Matrix Computations"
* by Gene H. Golub and Charles F. Van Loan, and a paper "An algorithm for
* generalized eigenvalue problems" by C.B.Moler and G.W.Stewart.
*
* \sa class RealSchur, class ComplexSchur, class EigenSolver, class ComplexEigenSolver
*/
template<typename _MatrixType> class RealQZ
{
public:
typedef _MatrixType MatrixType;
enum {
RowsAtCompileTime = MatrixType::RowsAtCompileTime,
ColsAtCompileTime = MatrixType::ColsAtCompileTime,
Options = MatrixType::Options,
MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
};
typedef typename MatrixType::Scalar Scalar;
typedef std::complex<typename NumTraits<Scalar>::Real> ComplexScalar;
typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
typedef Matrix<ComplexScalar, ColsAtCompileTime, 1, Options & ~RowMajor, MaxColsAtCompileTime, 1> EigenvalueType;
typedef Matrix<Scalar, ColsAtCompileTime, 1, Options & ~RowMajor, MaxColsAtCompileTime, 1> ColumnVectorType;
/** \brief Default constructor.
*
* \param [in] size Positive integer, size of the matrix whose QZ decomposition will be computed.
*
* The default constructor is useful in cases in which the user intends to
* perform decompositions via compute(). The \p size parameter is only
* used as a hint. It is not an error to give a wrong \p size, but it may
* impair performance.
*
* \sa compute() for an example.
*/
explicit RealQZ(Index size = RowsAtCompileTime==Dynamic ? 1 : RowsAtCompileTime) :
m_S(size, size),
m_T(size, size),
m_Q(size, size),
m_Z(size, size),
m_workspace(size*2),
m_maxIters(400),
m_isInitialized(false)
{ }
/** \brief Constructor; computes real QZ decomposition of given matrices
*
* \param[in] A Matrix A.
* \param[in] B Matrix B.
* \param[in] computeQZ If false, A and Z are not computed.
*
* This constructor calls compute() to compute the QZ decomposition.
*/
RealQZ(const MatrixType& A, const MatrixType& B, bool computeQZ = true) :
m_S(A.rows(),A.cols()),
m_T(A.rows(),A.cols()),
m_Q(A.rows(),A.cols()),
m_Z(A.rows(),A.cols()),
m_workspace(A.rows()*2),
m_maxIters(400),
m_isInitialized(false) {
compute(A, B, computeQZ);
}
/** \brief Returns matrix Q in the QZ decomposition.
*
* \returns A const reference to the matrix Q.
*/
const MatrixType& matrixQ() const {
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
eigen_assert(m_computeQZ && "The matrices Q and Z have not been computed during the QZ decomposition.");
return m_Q;
}
/** \brief Returns matrix Z in the QZ decomposition.
*
* \returns A const reference to the matrix Z.
*/
const MatrixType& matrixZ() const {
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
eigen_assert(m_computeQZ && "The matrices Q and Z have not been computed during the QZ decomposition.");
return m_Z;
}
/** \brief Returns matrix S in the QZ decomposition.
*
* \returns A const reference to the matrix S.
*/
const MatrixType& matrixS() const {
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
return m_S;
}
/** \brief Returns matrix S in the QZ decomposition.
*
* \returns A const reference to the matrix S.
*/
const MatrixType& matrixT() const {
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
return m_T;
}
/** \brief Computes QZ decomposition of given matrix.
*
* \param[in] A Matrix A.
* \param[in] B Matrix B.
* \param[in] computeQZ If false, A and Z are not computed.
* \returns Reference to \c *this
*/
RealQZ& compute(const MatrixType& A, const MatrixType& B, bool computeQZ = true);
/** \brief Reports whether previous computation was successful.
*
* \returns \c Success if computation was succesful, \c NoConvergence otherwise.
*/
ComputationInfo info() const
{
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
return m_info;
}
/** \brief Returns number of performed QR-like iterations.
*/
Index iterations() const
{
eigen_assert(m_isInitialized && "RealQZ is not initialized.");
return m_global_iter;
}
/** Sets the maximal number of iterations allowed to converge to one eigenvalue
* or decouple the problem.
*/
RealQZ& setMaxIterations(Index maxIters)
{
m_maxIters = maxIters;
return *this;
}
private:
MatrixType m_S, m_T, m_Q, m_Z;
Matrix<Scalar,Dynamic,1> m_workspace;
ComputationInfo m_info;
Index m_maxIters;
bool m_isInitialized;
bool m_computeQZ;
Scalar m_normOfT, m_normOfS;
Index m_global_iter;
typedef Matrix<Scalar,3,1> Vector3s;
typedef Matrix<Scalar,2,1> Vector2s;
typedef Matrix<Scalar,2,2> Matrix2s;
typedef JacobiRotation<Scalar> JRs;
void hessenbergTriangular();
void computeNorms();
Index findSmallSubdiagEntry(Index iu);
Index findSmallDiagEntry(Index f, Index l);
void splitOffTwoRows(Index i);
void pushDownZero(Index z, Index f, Index l);
void step(Index f, Index l, Index iter);
}; // RealQZ
/** \internal Reduces S and T to upper Hessenberg - triangular form */
template<typename MatrixType>
void RealQZ<MatrixType>::hessenbergTriangular()
{
const Index dim = m_S.cols();
// perform QR decomposition of T, overwrite T with R, save Q
HouseholderQR<MatrixType> qrT(m_T);
m_T = qrT.matrixQR();
m_T.template triangularView<StrictlyLower>().setZero();
m_Q = qrT.householderQ();
// overwrite S with Q* S
m_S.applyOnTheLeft(m_Q.adjoint());
// init Z as Identity
if (m_computeQZ)
m_Z = MatrixType::Identity(dim,dim);
// reduce S to upper Hessenberg with Givens rotations
for (Index j=0; j<=dim-3; j++) {
for (Index i=dim-1; i>=j+2; i--) {
JRs G;
// kill S(i,j)
if(m_S.coeff(i,j) != 0)
{
G.makeGivens(m_S.coeff(i-1,j), m_S.coeff(i,j), &m_S.coeffRef(i-1, j));
m_S.coeffRef(i,j) = Scalar(0.0);
m_S.rightCols(dim-j-1).applyOnTheLeft(i-1,i,G.adjoint());
m_T.rightCols(dim-i+1).applyOnTheLeft(i-1,i,G.adjoint());
// update Q
if (m_computeQZ)
m_Q.applyOnTheRight(i-1,i,G);
}
// kill T(i,i-1)
if(m_T.coeff(i,i-1)!=Scalar(0))
{
G.makeGivens(m_T.coeff(i,i), m_T.coeff(i,i-1), &m_T.coeffRef(i,i));
m_T.coeffRef(i,i-1) = Scalar(0.0);
m_S.applyOnTheRight(i,i-1,G);
m_T.topRows(i).applyOnTheRight(i,i-1,G);
// update Z
if (m_computeQZ)
m_Z.applyOnTheLeft(i,i-1,G.adjoint());
}
}
}
}
/** \internal Computes vector L1 norms of S and T when in Hessenberg-Triangular form already */
template<typename MatrixType>
inline void RealQZ<MatrixType>::computeNorms()
{
const Index size = m_S.cols();
m_normOfS = Scalar(0.0);
m_normOfT = Scalar(0.0);
for (Index j = 0; j < size; ++j)
{
m_normOfS += m_S.col(j).segment(0, (std::min)(size,j+2)).cwiseAbs().sum();
m_normOfT += m_T.row(j).segment(j, size - j).cwiseAbs().sum();
}
}
/** \internal Look for single small sub-diagonal element S(res, res-1) and return res (or 0) */
template<typename MatrixType>
inline Index RealQZ<MatrixType>::findSmallSubdiagEntry(Index iu)
{
using std::abs;
Index res = iu;
while (res > 0)
{
Scalar s = abs(m_S.coeff(res-1,res-1)) + abs(m_S.coeff(res,res));
if (s == Scalar(0.0))
s = m_normOfS;
if (abs(m_S.coeff(res,res-1)) < NumTraits<Scalar>::epsilon() * s)
break;
res--;
}
return res;
}
/** \internal Look for single small diagonal element T(res, res) for res between f and l, and return res (or f-1) */
template<typename MatrixType>
inline Index RealQZ<MatrixType>::findSmallDiagEntry(Index f, Index l)
{
using std::abs;
Index res = l;
while (res >= f) {
if (abs(m_T.coeff(res,res)) <= NumTraits<Scalar>::epsilon() * m_normOfT)
break;
res--;
}
return res;
}
/** \internal decouple 2x2 diagonal block in rows i, i+1 if eigenvalues are real */
template<typename MatrixType>
inline void RealQZ<MatrixType>::splitOffTwoRows(Index i)
{
using std::abs;
using std::sqrt;
const Index dim=m_S.cols();
if (abs(m_S.coeff(i+1,i))==Scalar(0))
return;
Index j = findSmallDiagEntry(i,i+1);
if (j==i-1)
{
// block of (S T^{-1})
Matrix2s STi = m_T.template block<2,2>(i,i).template triangularView<Upper>().
template solve<OnTheRight>(m_S.template block<2,2>(i,i));
Scalar p = Scalar(0.5)*(STi(0,0)-STi(1,1));
Scalar q = p*p + STi(1,0)*STi(0,1);
if (q>=0) {
Scalar z = sqrt(q);
// one QR-like iteration for ABi - lambda I
// is enough - when we know exact eigenvalue in advance,
// convergence is immediate
JRs G;
if (p>=0)
G.makeGivens(p + z, STi(1,0));
else
G.makeGivens(p - z, STi(1,0));
m_S.rightCols(dim-i).applyOnTheLeft(i,i+1,G.adjoint());
m_T.rightCols(dim-i).applyOnTheLeft(i,i+1,G.adjoint());
// update Q
if (m_computeQZ)
m_Q.applyOnTheRight(i,i+1,G);
G.makeGivens(m_T.coeff(i+1,i+1), m_T.coeff(i+1,i));
m_S.topRows(i+2).applyOnTheRight(i+1,i,G);
m_T.topRows(i+2).applyOnTheRight(i+1,i,G);
// update Z
if (m_computeQZ)
m_Z.applyOnTheLeft(i+1,i,G.adjoint());
m_S.coeffRef(i+1,i) = Scalar(0.0);
m_T.coeffRef(i+1,i) = Scalar(0.0);
}
}
else
{
pushDownZero(j,i,i+1);
}
}
/** \internal use zero in T(z,z) to zero S(l,l-1), working in block f..l */
template<typename MatrixType>
inline void RealQZ<MatrixType>::pushDownZero(Index z, Index f, Index l)
{
JRs G;
const Index dim = m_S.cols();
for (Index zz=z; zz<l; zz++)
{
// push 0 down
Index firstColS = zz>f ? (zz-1) : zz;
G.makeGivens(m_T.coeff(zz, zz+1), m_T.coeff(zz+1, zz+1));
m_S.rightCols(dim-firstColS).applyOnTheLeft(zz,zz+1,G.adjoint());
m_T.rightCols(dim-zz).applyOnTheLeft(zz,zz+1,G.adjoint());
m_T.coeffRef(zz+1,zz+1) = Scalar(0.0);
// update Q
if (m_computeQZ)
m_Q.applyOnTheRight(zz,zz+1,G);
// kill S(zz+1, zz-1)
if (zz>f)
{
G.makeGivens(m_S.coeff(zz+1, zz), m_S.coeff(zz+1,zz-1));
m_S.topRows(zz+2).applyOnTheRight(zz, zz-1,G);
m_T.topRows(zz+1).applyOnTheRight(zz, zz-1,G);
m_S.coeffRef(zz+1,zz-1) = Scalar(0.0);
// update Z
if (m_computeQZ)
m_Z.applyOnTheLeft(zz,zz-1,G.adjoint());
}
}
// finally kill S(l,l-1)
G.makeGivens(m_S.coeff(l,l), m_S.coeff(l,l-1));
m_S.applyOnTheRight(l,l-1,G);
m_T.applyOnTheRight(l,l-1,G);
m_S.coeffRef(l,l-1)=Scalar(0.0);
// update Z
if (m_computeQZ)
m_Z.applyOnTheLeft(l,l-1,G.adjoint());
}
/** \internal QR-like iterative step for block f..l */
template<typename MatrixType>
inline void RealQZ<MatrixType>::step(Index f, Index l, Index iter)
{
using std::abs;
const Index dim = m_S.cols();
// x, y, z
Scalar x, y, z;
if (iter==10)
{
// Wilkinson ad hoc shift
const Scalar
a11=m_S.coeff(f+0,f+0), a12=m_S.coeff(f+0,f+1),
a21=m_S.coeff(f+1,f+0), a22=m_S.coeff(f+1,f+1), a32=m_S.coeff(f+2,f+1),
b12=m_T.coeff(f+0,f+1),
b11i=Scalar(1.0)/m_T.coeff(f+0,f+0),
b22i=Scalar(1.0)/m_T.coeff(f+1,f+1),
a87=m_S.coeff(l-1,l-2),
a98=m_S.coeff(l-0,l-1),
b77i=Scalar(1.0)/m_T.coeff(l-2,l-2),
b88i=Scalar(1.0)/m_T.coeff(l-1,l-1);
Scalar ss = abs(a87*b77i) + abs(a98*b88i),
lpl = Scalar(1.5)*ss,
ll = ss*ss;
x = ll + a11*a11*b11i*b11i - lpl*a11*b11i + a12*a21*b11i*b22i
- a11*a21*b12*b11i*b11i*b22i;
y = a11*a21*b11i*b11i - lpl*a21*b11i + a21*a22*b11i*b22i
- a21*a21*b12*b11i*b11i*b22i;
z = a21*a32*b11i*b22i;
}
else if (iter==16)
{
// another exceptional shift
x = m_S.coeff(f,f)/m_T.coeff(f,f)-m_S.coeff(l,l)/m_T.coeff(l,l) + m_S.coeff(l,l-1)*m_T.coeff(l-1,l) /
(m_T.coeff(l-1,l-1)*m_T.coeff(l,l));
y = m_S.coeff(f+1,f)/m_T.coeff(f,f);
z = 0;
}
else if (iter>23 && !(iter%8))
{
// extremely exceptional shift
x = internal::random<Scalar>(-1.0,1.0);
y = internal::random<Scalar>(-1.0,1.0);
z = internal::random<Scalar>(-1.0,1.0);
}
else
{
// Compute the shifts: (x,y,z,0...) = (AB^-1 - l1 I) (AB^-1 - l2 I) e1
// where l1 and l2 are the eigenvalues of the 2x2 matrix C = U V^-1 where
// U and V are 2x2 bottom right sub matrices of A and B. Thus:
// = AB^-1AB^-1 + l1 l2 I - (l1+l2)(AB^-1)
// = AB^-1AB^-1 + det(M) - tr(M)(AB^-1)
// Since we are only interested in having x, y, z with a correct ratio, we have:
const Scalar
a11 = m_S.coeff(f,f), a12 = m_S.coeff(f,f+1),
a21 = m_S.coeff(f+1,f), a22 = m_S.coeff(f+1,f+1),
a32 = m_S.coeff(f+2,f+1),
a88 = m_S.coeff(l-1,l-1), a89 = m_S.coeff(l-1,l),
a98 = m_S.coeff(l,l-1), a99 = m_S.coeff(l,l),
b11 = m_T.coeff(f,f), b12 = m_T.coeff(f,f+1),
b22 = m_T.coeff(f+1,f+1),
b88 = m_T.coeff(l-1,l-1), b89 = m_T.coeff(l-1,l),
b99 = m_T.coeff(l,l);
x = ( (a88/b88 - a11/b11)*(a99/b99 - a11/b11) - (a89/b99)*(a98/b88) + (a98/b88)*(b89/b99)*(a11/b11) ) * (b11/a21)
+ a12/b22 - (a11/b11)*(b12/b22);
y = (a22/b22-a11/b11) - (a21/b11)*(b12/b22) - (a88/b88-a11/b11) - (a99/b99-a11/b11) + (a98/b88)*(b89/b99);
z = a32/b22;
}
JRs G;
for (Index k=f; k<=l-2; k++)
{
// variables for Householder reflections
Vector2s essential2;
Scalar tau, beta;
Vector3s hr(x,y,z);
// Q_k to annihilate S(k+1,k-1) and S(k+2,k-1)
hr.makeHouseholderInPlace(tau, beta);
essential2 = hr.template bottomRows<2>();
Index fc=(std::max)(k-1,Index(0)); // first col to update
m_S.template middleRows<3>(k).rightCols(dim-fc).applyHouseholderOnTheLeft(essential2, tau, m_workspace.data());
m_T.template middleRows<3>(k).rightCols(dim-fc).applyHouseholderOnTheLeft(essential2, tau, m_workspace.data());
if (m_computeQZ)
m_Q.template middleCols<3>(k).applyHouseholderOnTheRight(essential2, tau, m_workspace.data());
if (k>f)
m_S.coeffRef(k+2,k-1) = m_S.coeffRef(k+1,k-1) = Scalar(0.0);
// Z_{k1} to annihilate T(k+2,k+1) and T(k+2,k)
hr << m_T.coeff(k+2,k+2),m_T.coeff(k+2,k),m_T.coeff(k+2,k+1);
hr.makeHouseholderInPlace(tau, beta);
essential2 = hr.template bottomRows<2>();
{
Index lr = (std::min)(k+4,dim); // last row to update
Map<Matrix<Scalar,Dynamic,1> > tmp(m_workspace.data(),lr);
// S
tmp = m_S.template middleCols<2>(k).topRows(lr) * essential2;
tmp += m_S.col(k+2).head(lr);
m_S.col(k+2).head(lr) -= tau*tmp;
m_S.template middleCols<2>(k).topRows(lr) -= (tau*tmp) * essential2.adjoint();
// T
tmp = m_T.template middleCols<2>(k).topRows(lr) * essential2;
tmp += m_T.col(k+2).head(lr);
m_T.col(k+2).head(lr) -= tau*tmp;
m_T.template middleCols<2>(k).topRows(lr) -= (tau*tmp) * essential2.adjoint();
}
if (m_computeQZ)
{
// Z
Map<Matrix<Scalar,1,Dynamic> > tmp(m_workspace.data(),dim);
tmp = essential2.adjoint()*(m_Z.template middleRows<2>(k));
tmp += m_Z.row(k+2);
m_Z.row(k+2) -= tau*tmp;
m_Z.template middleRows<2>(k) -= essential2 * (tau*tmp);
}
m_T.coeffRef(k+2,k) = m_T.coeffRef(k+2,k+1) = Scalar(0.0);
// Z_{k2} to annihilate T(k+1,k)
G.makeGivens(m_T.coeff(k+1,k+1), m_T.coeff(k+1,k));
m_S.applyOnTheRight(k+1,k,G);
m_T.applyOnTheRight(k+1,k,G);
// update Z
if (m_computeQZ)
m_Z.applyOnTheLeft(k+1,k,G.adjoint());
m_T.coeffRef(k+1,k) = Scalar(0.0);
// update x,y,z
x = m_S.coeff(k+1,k);
y = m_S.coeff(k+2,k);
if (k < l-2)
z = m_S.coeff(k+3,k);
} // loop over k
// Q_{n-1} to annihilate y = S(l,l-2)
G.makeGivens(x,y);
m_S.applyOnTheLeft(l-1,l,G.adjoint());
m_T.applyOnTheLeft(l-1,l,G.adjoint());
if (m_computeQZ)
m_Q.applyOnTheRight(l-1,l,G);
m_S.coeffRef(l,l-2) = Scalar(0.0);
// Z_{n-1} to annihilate T(l,l-1)
G.makeGivens(m_T.coeff(l,l),m_T.coeff(l,l-1));
m_S.applyOnTheRight(l,l-1,G);
m_T.applyOnTheRight(l,l-1,G);
if (m_computeQZ)
m_Z.applyOnTheLeft(l,l-1,G.adjoint());
m_T.coeffRef(l,l-1) = Scalar(0.0);
}
template<typename MatrixType>
RealQZ<MatrixType>& RealQZ<MatrixType>::compute(const MatrixType& A_in, const MatrixType& B_in, bool computeQZ)
{
const Index dim = A_in.cols();
eigen_assert (A_in.rows()==dim && A_in.cols()==dim
&& B_in.rows()==dim && B_in.cols()==dim
&& "Need square matrices of the same dimension");
m_isInitialized = true;
m_computeQZ = computeQZ;
m_S = A_in; m_T = B_in;
m_workspace.resize(dim*2);
m_global_iter = 0;
// entrance point: hessenberg triangular decomposition
hessenbergTriangular();
// compute L1 vector norms of T, S into m_normOfS, m_normOfT
computeNorms();
Index l = dim-1,
f,
local_iter = 0;
while (l>0 && local_iter<m_maxIters)
{
f = findSmallSubdiagEntry(l);
// now rows and columns f..l (including) decouple from the rest of the problem
if (f>0) m_S.coeffRef(f,f-1) = Scalar(0.0);
if (f == l) // One root found
{
l--;
local_iter = 0;
}
else if (f == l-1) // Two roots found
{
splitOffTwoRows(f);
l -= 2;
local_iter = 0;
}
else // No convergence yet
{
// if there's zero on diagonal of T, we can isolate an eigenvalue with Givens rotations
Index z = findSmallDiagEntry(f,l);
if (z>=f)
{
// zero found
pushDownZero(z,f,l);
}
else
{
// We are sure now that S.block(f,f, l-f+1,l-f+1) is underuced upper-Hessenberg
// and T.block(f,f, l-f+1,l-f+1) is invertible uper-triangular, which allows to
// apply a QR-like iteration to rows and columns f..l.
step(f,l, local_iter);
local_iter++;
m_global_iter++;
}
}
}
// check if we converged before reaching iterations limit
m_info = (local_iter<m_maxIters) ? Success : NoConvergence;
// For each non triangular 2x2 diagonal block of S,
// reduce the respective 2x2 diagonal block of T to positive diagonal form using 2x2 SVD.
// This step is not mandatory for QZ, but it does help further extraction of eigenvalues/eigenvectors,
// and is in par with Lapack/Matlab QZ.
if(m_info==Success)
{
for(Index i=0; i<dim-1; ++i)
{
if(m_S.coeff(i+1, i) != Scalar(0))
{
JacobiRotation<Scalar> j_left, j_right;
internal::real_2x2_jacobi_svd(m_T, i, i+1, &j_left, &j_right);
// Apply resulting Jacobi rotations
m_S.applyOnTheLeft(i,i+1,j_left);
m_S.applyOnTheRight(i,i+1,j_right);
m_T.applyOnTheLeft(i,i+1,j_left);
m_T.applyOnTheRight(i,i+1,j_right);
m_T(i+1,i) = m_T(i,i+1) = Scalar(0);
if(m_computeQZ) {
m_Q.applyOnTheRight(i,i+1,j_left.transpose());
m_Z.applyOnTheLeft(i,i+1,j_right.transpose());
}
i++;
}
}
}
return *this;
} // end compute
} // end namespace Eigen
#endif //EIGEN_REAL_QZ
| 23,586 | 35.010687 | 121 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Geometry/EulerAngles.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_EULERANGLES_H
#define EIGEN_EULERANGLES_H
namespace Eigen {
/** \geometry_module \ingroup Geometry_Module
*
*
* \returns the Euler-angles of the rotation matrix \c *this using the convention defined by the triplet (\a a0,\a a1,\a a2)
*
* Each of the three parameters \a a0,\a a1,\a a2 represents the respective rotation axis as an integer in {0,1,2}.
* For instance, in:
* \code Vector3f ea = mat.eulerAngles(2, 0, 2); \endcode
* "2" represents the z axis and "0" the x axis, etc. The returned angles are such that
* we have the following equality:
* \code
* mat == AngleAxisf(ea[0], Vector3f::UnitZ())
* * AngleAxisf(ea[1], Vector3f::UnitX())
* * AngleAxisf(ea[2], Vector3f::UnitZ()); \endcode
* This corresponds to the right-multiply conventions (with right hand side frames).
*
* The returned angles are in the ranges [0:pi]x[-pi:pi]x[-pi:pi].
*
* \sa class AngleAxis
*/
template<typename Derived>
EIGEN_DEVICE_FUNC inline Matrix<typename MatrixBase<Derived>::Scalar,3,1>
MatrixBase<Derived>::eulerAngles(Index a0, Index a1, Index a2) const
{
EIGEN_USING_STD_MATH(atan2)
EIGEN_USING_STD_MATH(sin)
EIGEN_USING_STD_MATH(cos)
/* Implemented from Graphics Gems IV */
EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Derived,3,3)
Matrix<Scalar,3,1> res;
typedef Matrix<typename Derived::Scalar,2,1> Vector2;
const Index odd = ((a0+1)%3 == a1) ? 0 : 1;
const Index i = a0;
const Index j = (a0 + 1 + odd)%3;
const Index k = (a0 + 2 - odd)%3;
if (a0==a2)
{
res[0] = atan2(coeff(j,i), coeff(k,i));
if((odd && res[0]<Scalar(0)) || ((!odd) && res[0]>Scalar(0)))
{
if(res[0] > Scalar(0)) {
res[0] -= Scalar(EIGEN_PI);
}
else {
res[0] += Scalar(EIGEN_PI);
}
Scalar s2 = Vector2(coeff(j,i), coeff(k,i)).norm();
res[1] = -atan2(s2, coeff(i,i));
}
else
{
Scalar s2 = Vector2(coeff(j,i), coeff(k,i)).norm();
res[1] = atan2(s2, coeff(i,i));
}
// With a=(0,1,0), we have i=0; j=1; k=2, and after computing the first two angles,
// we can compute their respective rotation, and apply its inverse to M. Since the result must
// be a rotation around x, we have:
//
// c2 s1.s2 c1.s2 1 0 0
// 0 c1 -s1 * M = 0 c3 s3
// -s2 s1.c2 c1.c2 0 -s3 c3
//
// Thus: m11.c1 - m21.s1 = c3 & m12.c1 - m22.s1 = s3
Scalar s1 = sin(res[0]);
Scalar c1 = cos(res[0]);
res[2] = atan2(c1*coeff(j,k)-s1*coeff(k,k), c1*coeff(j,j) - s1 * coeff(k,j));
}
else
{
res[0] = atan2(coeff(j,k), coeff(k,k));
Scalar c2 = Vector2(coeff(i,i), coeff(i,j)).norm();
if((odd && res[0]<Scalar(0)) || ((!odd) && res[0]>Scalar(0))) {
if(res[0] > Scalar(0)) {
res[0] -= Scalar(EIGEN_PI);
}
else {
res[0] += Scalar(EIGEN_PI);
}
res[1] = atan2(-coeff(i,k), -c2);
}
else
res[1] = atan2(-coeff(i,k), c2);
Scalar s1 = sin(res[0]);
Scalar c1 = cos(res[0]);
res[2] = atan2(s1*coeff(k,i)-c1*coeff(j,i), c1*coeff(j,j) - s1 * coeff(k,j));
}
if (!odd)
res = -res;
return res;
}
} // end namespace Eigen
#endif // EIGEN_EULERANGLES_H
| 3,639 | 30.652174 | 125 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Geometry/Umeyama.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Hauke Heibel <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_UMEYAMA_H
#define EIGEN_UMEYAMA_H
// This file requires the user to include
// * Eigen/Core
// * Eigen/LU
// * Eigen/SVD
// * Eigen/Array
namespace Eigen {
#ifndef EIGEN_PARSED_BY_DOXYGEN
// These helpers are required since it allows to use mixed types as parameters
// for the Umeyama. The problem with mixed parameters is that the return type
// cannot trivially be deduced when float and double types are mixed.
namespace internal {
// Compile time return type deduction for different MatrixBase types.
// Different means here different alignment and parameters but the same underlying
// real scalar type.
template<typename MatrixType, typename OtherMatrixType>
struct umeyama_transform_matrix_type
{
enum {
MinRowsAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(MatrixType::RowsAtCompileTime, OtherMatrixType::RowsAtCompileTime),
// When possible we want to choose some small fixed size value since the result
// is likely to fit on the stack. So here, EIGEN_SIZE_MIN_PREFER_DYNAMIC is not what we want.
HomogeneousDimension = int(MinRowsAtCompileTime) == Dynamic ? Dynamic : int(MinRowsAtCompileTime)+1
};
typedef Matrix<typename traits<MatrixType>::Scalar,
HomogeneousDimension,
HomogeneousDimension,
AutoAlign | (traits<MatrixType>::Flags & RowMajorBit ? RowMajor : ColMajor),
HomogeneousDimension,
HomogeneousDimension
> type;
};
}
#endif
/**
* \geometry_module \ingroup Geometry_Module
*
* \brief Returns the transformation between two point sets.
*
* The algorithm is based on:
* "Least-squares estimation of transformation parameters between two point patterns",
* Shinji Umeyama, PAMI 1991, DOI: 10.1109/34.88573
*
* It estimates parameters \f$ c, \mathbf{R}, \f$ and \f$ \mathbf{t} \f$ such that
* \f{align*}
* \frac{1}{n} \sum_{i=1}^n \vert\vert y_i - (c\mathbf{R}x_i + \mathbf{t}) \vert\vert_2^2
* \f}
* is minimized.
*
* The algorithm is based on the analysis of the covariance matrix
* \f$ \Sigma_{\mathbf{x}\mathbf{y}} \in \mathbb{R}^{d \times d} \f$
* of the input point sets \f$ \mathbf{x} \f$ and \f$ \mathbf{y} \f$ where
* \f$d\f$ is corresponding to the dimension (which is typically small).
* The analysis is involving the SVD having a complexity of \f$O(d^3)\f$
* though the actual computational effort lies in the covariance
* matrix computation which has an asymptotic lower bound of \f$O(dm)\f$ when
* the input point sets have dimension \f$d \times m\f$.
*
* Currently the method is working only for floating point matrices.
*
* \todo Should the return type of umeyama() become a Transform?
*
* \param src Source points \f$ \mathbf{x} = \left( x_1, \hdots, x_n \right) \f$.
* \param dst Destination points \f$ \mathbf{y} = \left( y_1, \hdots, y_n \right) \f$.
* \param with_scaling Sets \f$ c=1 \f$ when <code>false</code> is passed.
* \return The homogeneous transformation
* \f{align*}
* T = \begin{bmatrix} c\mathbf{R} & \mathbf{t} \\ \mathbf{0} & 1 \end{bmatrix}
* \f}
* minimizing the resudiual above. This transformation is always returned as an
* Eigen::Matrix.
*/
template <typename Derived, typename OtherDerived>
typename internal::umeyama_transform_matrix_type<Derived, OtherDerived>::type
umeyama(const MatrixBase<Derived>& src, const MatrixBase<OtherDerived>& dst, bool with_scaling = true)
{
typedef typename internal::umeyama_transform_matrix_type<Derived, OtherDerived>::type TransformationMatrixType;
typedef typename internal::traits<TransformationMatrixType>::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
EIGEN_STATIC_ASSERT(!NumTraits<Scalar>::IsComplex, NUMERIC_TYPE_MUST_BE_REAL)
EIGEN_STATIC_ASSERT((internal::is_same<Scalar, typename internal::traits<OtherDerived>::Scalar>::value),
YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY)
enum { Dimension = EIGEN_SIZE_MIN_PREFER_DYNAMIC(Derived::RowsAtCompileTime, OtherDerived::RowsAtCompileTime) };
typedef Matrix<Scalar, Dimension, 1> VectorType;
typedef Matrix<Scalar, Dimension, Dimension> MatrixType;
typedef typename internal::plain_matrix_type_row_major<Derived>::type RowMajorMatrixType;
const Index m = src.rows(); // dimension
const Index n = src.cols(); // number of measurements
// required for demeaning ...
const RealScalar one_over_n = RealScalar(1) / static_cast<RealScalar>(n);
// computation of mean
const VectorType src_mean = src.rowwise().sum() * one_over_n;
const VectorType dst_mean = dst.rowwise().sum() * one_over_n;
// demeaning of src and dst points
const RowMajorMatrixType src_demean = src.colwise() - src_mean;
const RowMajorMatrixType dst_demean = dst.colwise() - dst_mean;
// Eq. (36)-(37)
const Scalar src_var = src_demean.rowwise().squaredNorm().sum() * one_over_n;
// Eq. (38)
const MatrixType sigma = one_over_n * dst_demean * src_demean.transpose();
JacobiSVD<MatrixType> svd(sigma, ComputeFullU | ComputeFullV);
// Initialize the resulting transformation with an identity matrix...
TransformationMatrixType Rt = TransformationMatrixType::Identity(m+1,m+1);
// Eq. (39)
VectorType S = VectorType::Ones(m);
if ( svd.matrixU().determinant() * svd.matrixV().determinant() < 0 )
S(m-1) = -1;
// Eq. (40) and (43)
Rt.block(0,0,m,m).noalias() = svd.matrixU() * S.asDiagonal() * svd.matrixV().transpose();
if (with_scaling)
{
// Eq. (42)
const Scalar c = Scalar(1)/src_var * svd.singularValues().dot(S);
// Eq. (41)
Rt.col(m).head(m) = dst_mean;
Rt.col(m).head(m).noalias() -= c*Rt.topLeftCorner(m,m)*src_mean;
Rt.block(0,0,m,m) *= c;
}
else
{
Rt.col(m).head(m) = dst_mean;
Rt.col(m).head(m).noalias() -= Rt.topLeftCorner(m,m)*src_mean;
}
return Rt;
}
} // end namespace Eigen
#endif // EIGEN_UMEYAMA_H
| 6,191 | 36.077844 | 124 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Geometry/arch/Geometry_SSE.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Rohit Garg <[email protected]>
// Copyright (C) 2009-2010 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_GEOMETRY_SSE_H
#define EIGEN_GEOMETRY_SSE_H
namespace Eigen {
namespace internal {
template<class Derived, class OtherDerived>
struct quat_product<Architecture::SSE, Derived, OtherDerived, float>
{
enum {
AAlignment = traits<Derived>::Alignment,
BAlignment = traits<OtherDerived>::Alignment,
ResAlignment = traits<Quaternion<float> >::Alignment
};
static inline Quaternion<float> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
{
Quaternion<float> res;
const __m128 mask = _mm_setr_ps(0.f,0.f,0.f,-0.f);
__m128 a = _a.coeffs().template packet<AAlignment>(0);
__m128 b = _b.coeffs().template packet<BAlignment>(0);
__m128 s1 = _mm_mul_ps(vec4f_swizzle1(a,1,2,0,2),vec4f_swizzle1(b,2,0,1,2));
__m128 s2 = _mm_mul_ps(vec4f_swizzle1(a,3,3,3,1),vec4f_swizzle1(b,0,1,2,1));
pstoret<float,Packet4f,ResAlignment>(
&res.x(),
_mm_add_ps(_mm_sub_ps(_mm_mul_ps(a,vec4f_swizzle1(b,3,3,3,3)),
_mm_mul_ps(vec4f_swizzle1(a,2,0,1,0),
vec4f_swizzle1(b,1,2,0,0))),
_mm_xor_ps(mask,_mm_add_ps(s1,s2))));
return res;
}
};
template<class Derived>
struct quat_conj<Architecture::SSE, Derived, float>
{
enum {
ResAlignment = traits<Quaternion<float> >::Alignment
};
static inline Quaternion<float> run(const QuaternionBase<Derived>& q)
{
Quaternion<float> res;
const __m128 mask = _mm_setr_ps(-0.f,-0.f,-0.f,0.f);
pstoret<float,Packet4f,ResAlignment>(&res.x(), _mm_xor_ps(mask, q.coeffs().template packet<traits<Derived>::Alignment>(0)));
return res;
}
};
template<typename VectorLhs,typename VectorRhs>
struct cross3_impl<Architecture::SSE,VectorLhs,VectorRhs,float,true>
{
enum {
ResAlignment = traits<typename plain_matrix_type<VectorLhs>::type>::Alignment
};
static inline typename plain_matrix_type<VectorLhs>::type
run(const VectorLhs& lhs, const VectorRhs& rhs)
{
__m128 a = lhs.template packet<traits<VectorLhs>::Alignment>(0);
__m128 b = rhs.template packet<traits<VectorRhs>::Alignment>(0);
__m128 mul1=_mm_mul_ps(vec4f_swizzle1(a,1,2,0,3),vec4f_swizzle1(b,2,0,1,3));
__m128 mul2=_mm_mul_ps(vec4f_swizzle1(a,2,0,1,3),vec4f_swizzle1(b,1,2,0,3));
typename plain_matrix_type<VectorLhs>::type res;
pstoret<float,Packet4f,ResAlignment>(&res.x(),_mm_sub_ps(mul1,mul2));
return res;
}
};
template<class Derived, class OtherDerived>
struct quat_product<Architecture::SSE, Derived, OtherDerived, double>
{
enum {
BAlignment = traits<OtherDerived>::Alignment,
ResAlignment = traits<Quaternion<double> >::Alignment
};
static inline Quaternion<double> run(const QuaternionBase<Derived>& _a, const QuaternionBase<OtherDerived>& _b)
{
const Packet2d mask = _mm_castsi128_pd(_mm_set_epi32(0x0,0x0,0x80000000,0x0));
Quaternion<double> res;
const double* a = _a.coeffs().data();
Packet2d b_xy = _b.coeffs().template packet<BAlignment>(0);
Packet2d b_zw = _b.coeffs().template packet<BAlignment>(2);
Packet2d a_xx = pset1<Packet2d>(a[0]);
Packet2d a_yy = pset1<Packet2d>(a[1]);
Packet2d a_zz = pset1<Packet2d>(a[2]);
Packet2d a_ww = pset1<Packet2d>(a[3]);
// two temporaries:
Packet2d t1, t2;
/*
* t1 = ww*xy + yy*zw
* t2 = zz*xy - xx*zw
* res.xy = t1 +/- swap(t2)
*/
t1 = padd(pmul(a_ww, b_xy), pmul(a_yy, b_zw));
t2 = psub(pmul(a_zz, b_xy), pmul(a_xx, b_zw));
#ifdef EIGEN_VECTORIZE_SSE3
EIGEN_UNUSED_VARIABLE(mask)
pstoret<double,Packet2d,ResAlignment>(&res.x(), _mm_addsub_pd(t1, preverse(t2)));
#else
pstoret<double,Packet2d,ResAlignment>(&res.x(), padd(t1, pxor(mask,preverse(t2))));
#endif
/*
* t1 = ww*zw - yy*xy
* t2 = zz*zw + xx*xy
* res.zw = t1 -/+ swap(t2) = swap( swap(t1) +/- t2)
*/
t1 = psub(pmul(a_ww, b_zw), pmul(a_yy, b_xy));
t2 = padd(pmul(a_zz, b_zw), pmul(a_xx, b_xy));
#ifdef EIGEN_VECTORIZE_SSE3
EIGEN_UNUSED_VARIABLE(mask)
pstoret<double,Packet2d,ResAlignment>(&res.z(), preverse(_mm_addsub_pd(preverse(t1), t2)));
#else
pstoret<double,Packet2d,ResAlignment>(&res.z(), psub(t1, pxor(mask,preverse(t2))));
#endif
return res;
}
};
template<class Derived>
struct quat_conj<Architecture::SSE, Derived, double>
{
enum {
ResAlignment = traits<Quaternion<double> >::Alignment
};
static inline Quaternion<double> run(const QuaternionBase<Derived>& q)
{
Quaternion<double> res;
const __m128d mask0 = _mm_setr_pd(-0.,-0.);
const __m128d mask2 = _mm_setr_pd(-0.,0.);
pstoret<double,Packet2d,ResAlignment>(&res.x(), _mm_xor_pd(mask0, q.coeffs().template packet<traits<Derived>::Alignment>(0)));
pstoret<double,Packet2d,ResAlignment>(&res.z(), _mm_xor_pd(mask2, q.coeffs().template packet<traits<Derived>::Alignment>(2)));
return res;
}
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_GEOMETRY_SSE_H
| 5,387 | 32.259259 | 130 |
h
|
Crystal_Ball_Nav
|
Crystal_Ball_Nav-master/SOGM-3D-2D-Net/cpp_wrappers/src/Eigen/src/Householder/Householder.h
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Benoit Jacob <[email protected]>
// Copyright (C) 2009 Gael Guennebaud <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_HOUSEHOLDER_H
#define EIGEN_HOUSEHOLDER_H
namespace Eigen {
namespace internal {
template<int n> struct decrement_size
{
enum {
ret = n==Dynamic ? n : n-1
};
};
}
/** Computes the elementary reflector H such that:
* \f$ H *this = [ beta 0 ... 0]^T \f$
* where the transformation H is:
* \f$ H = I - tau v v^*\f$
* and the vector v is:
* \f$ v^T = [1 essential^T] \f$
*
* The essential part of the vector \c v is stored in *this.
*
* On output:
* \param tau the scaling factor of the Householder transformation
* \param beta the result of H * \c *this
*
* \sa MatrixBase::makeHouseholder(), MatrixBase::applyHouseholderOnTheLeft(),
* MatrixBase::applyHouseholderOnTheRight()
*/
template<typename Derived>
void MatrixBase<Derived>::makeHouseholderInPlace(Scalar& tau, RealScalar& beta)
{
VectorBlock<Derived, internal::decrement_size<Base::SizeAtCompileTime>::ret> essentialPart(derived(), 1, size()-1);
makeHouseholder(essentialPart, tau, beta);
}
/** Computes the elementary reflector H such that:
* \f$ H *this = [ beta 0 ... 0]^T \f$
* where the transformation H is:
* \f$ H = I - tau v v^*\f$
* and the vector v is:
* \f$ v^T = [1 essential^T] \f$
*
* On output:
* \param essential the essential part of the vector \c v
* \param tau the scaling factor of the Householder transformation
* \param beta the result of H * \c *this
*
* \sa MatrixBase::makeHouseholderInPlace(), MatrixBase::applyHouseholderOnTheLeft(),
* MatrixBase::applyHouseholderOnTheRight()
*/
template<typename Derived>
template<typename EssentialPart>
void MatrixBase<Derived>::makeHouseholder(
EssentialPart& essential,
Scalar& tau,
RealScalar& beta) const
{
using std::sqrt;
using numext::conj;
EIGEN_STATIC_ASSERT_VECTOR_ONLY(EssentialPart)
VectorBlock<const Derived, EssentialPart::SizeAtCompileTime> tail(derived(), 1, size()-1);
RealScalar tailSqNorm = size()==1 ? RealScalar(0) : tail.squaredNorm();
Scalar c0 = coeff(0);
const RealScalar tol = (std::numeric_limits<RealScalar>::min)();
if(tailSqNorm <= tol && numext::abs2(numext::imag(c0))<=tol)
{
tau = RealScalar(0);
beta = numext::real(c0);
essential.setZero();
}
else
{
beta = sqrt(numext::abs2(c0) + tailSqNorm);
if (numext::real(c0)>=RealScalar(0))
beta = -beta;
essential = tail / (c0 - beta);
tau = conj((beta - c0) / beta);
}
}
/** Apply the elementary reflector H given by
* \f$ H = I - tau v v^*\f$
* with
* \f$ v^T = [1 essential^T] \f$
* from the left to a vector or matrix.
*
* On input:
* \param essential the essential part of the vector \c v
* \param tau the scaling factor of the Householder transformation
* \param workspace a pointer to working space with at least
* this->cols() * essential.size() entries
*
* \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(),
* MatrixBase::applyHouseholderOnTheRight()
*/
template<typename Derived>
template<typename EssentialPart>
void MatrixBase<Derived>::applyHouseholderOnTheLeft(
const EssentialPart& essential,
const Scalar& tau,
Scalar* workspace)
{
if(rows() == 1)
{
*this *= Scalar(1)-tau;
}
else if(tau!=Scalar(0))
{
Map<typename internal::plain_row_type<PlainObject>::type> tmp(workspace,cols());
Block<Derived, EssentialPart::SizeAtCompileTime, Derived::ColsAtCompileTime> bottom(derived(), 1, 0, rows()-1, cols());
tmp.noalias() = essential.adjoint() * bottom;
tmp += this->row(0);
this->row(0) -= tau * tmp;
bottom.noalias() -= tau * essential * tmp;
}
}
/** Apply the elementary reflector H given by
* \f$ H = I - tau v v^*\f$
* with
* \f$ v^T = [1 essential^T] \f$
* from the right to a vector or matrix.
*
* On input:
* \param essential the essential part of the vector \c v
* \param tau the scaling factor of the Householder transformation
* \param workspace a pointer to working space with at least
* this->cols() * essential.size() entries
*
* \sa MatrixBase::makeHouseholder(), MatrixBase::makeHouseholderInPlace(),
* MatrixBase::applyHouseholderOnTheLeft()
*/
template<typename Derived>
template<typename EssentialPart>
void MatrixBase<Derived>::applyHouseholderOnTheRight(
const EssentialPart& essential,
const Scalar& tau,
Scalar* workspace)
{
if(cols() == 1)
{
*this *= Scalar(1)-tau;
}
else if(tau!=Scalar(0))
{
Map<typename internal::plain_col_type<PlainObject>::type> tmp(workspace,rows());
Block<Derived, Derived::RowsAtCompileTime, EssentialPart::SizeAtCompileTime> right(derived(), 0, 1, rows(), cols()-1);
tmp.noalias() = right * essential.conjugate();
tmp += this->col(0);
this->col(0) -= tau * tmp;
right.noalias() -= tau * tmp * essential.transpose();
}
}
} // end namespace Eigen
#endif // EIGEN_HOUSEHOLDER_H
| 5,345 | 29.901734 | 123 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.