content
stringlengths
19
48.2k
/* Create initial mapping of symbols to trees. The goal is to divide all as symbols [0,as) into nt equivalence classes (EC) [0,nt) such that standard deviation of symbol frequencies in classes is minimal. We use a kind of a heuristic to achieve that. There might exist a better way to achieve that, but this one seems to be good (and fast) enough. If the symbol v belongs to the equivalence class t then set s->length[t][v] to zero. Otherwise set it to 1. */ static void generate_initial_trees(struct encoder_state *s, unsigned nm, unsigned nt) { unsigned a, b; unsigned freq; unsigned cum; unsigned as; unsigned t; memset(s->length, 1, sizeof(s->length)); as = 0; for (a = 0, cum = 0; cum < nm; a++) { freq = s->code[0][a]; cum += freq; as += min(freq, 1); } assert(cum == nm); nt = min(nt, as); a = 0; for (t = 0; nt > 0; t++, nt--) { assert(nm > 0); assert(as >= nt); freq = s->code[0][a]; cum = freq; as -= min(freq, 1); b = a+1; while (as > nt-1 && cum * nt < nm) { freq = s->code[0][b]; cum += freq; as -= min(freq, 1); b++; } if (cum > freq && (2*cum - freq) * nt > 2*nm) { cum -= freq; as += min(freq, 1); b--; } assert(a < b); assert(cum > 0); assert(cum <= nm); assert(as >= nt-1); Trace(("Tree %u: EC=[%3u,%3u), |EC|=%3u, cum=%6u", t, a, b, b-a, cum)); bzero(&s->length[t][a], b - a); a = b; nm -= cum; } assert(as == 0); assert(nm == 0); }
#include <stdio.h> #include <strings.h> main() { char s[101],t[101]; scanf("%s",s); int i=0,j=strlen(s),k=0,l,cou[6]; for(i=0;s[i]!='\0';i++) { if(s[i]=='h') { k=i; while(s[k]!='e' && s[k]!='\0') k++; //putchar(s[k]); if(s[k]=='e') { k++; while(s[k]!='l' && s[k]!='\0') k++; //putchar(s[k]); if(s[k]=='l') {k++; while(s[k]!='l' && s[k]!='\0') k++;///putchar(s[k]); if(s[k]=='l') { k++; while(s[k]!='o' && s[k]!='\0') k++;//putchar(s[k]); if(s[k]=='o') {printf("YES"); return;} else {printf("NO"); return;} } else {printf("NO"); return;} } else {printf("NO"); return;} } else {printf("NO"); return;} } } printf("NO"); return; }
#include<stdio.h> #include<string.h> void main() { char n[20],m[20],c; int i,j,ln; while (scanf("%s%s",n,m) != EOF) { ln=strlen(n); for (i=0;i<ln-1;i++) for (j=i+1;j<ln;j++) if (n[i]>n[j]) { c=n[i]; n[i]=n[j]; n[j]=c; } if (n[0]=='0') for (i=1;i<ln;i++) if (n[i]!='0') { c=n[0]; n[0]=n[i]; n[i]=c; break; } if (strcmp(n,m)==0) printf("OK\n"); else printf("WRONG_ANSWER\n"); } }
/** * brcmf_p2p_deinit_discovery() - disable P2P device discovery. * * @p2p: P2P specific data. * * Resets the discovery state and disables it in firmware. */ static zx_status_t brcmf_p2p_deinit_discovery(struct brcmf_p2p_info* p2p) { struct brcmf_cfg80211_vif* vif; brcmf_dbg(TRACE, "enter\n"); vif = p2p->bss_idx[P2PAPI_BSSCFG_DEVICE].vif; (void)brcmf_p2p_set_discover_state(vif->ifp, WL_P2P_DISC_ST_SCAN, 0, 0); vif = p2p->bss_idx[P2PAPI_BSSCFG_PRIMARY].vif; (void)brcmf_fil_iovar_int_set(vif->ifp, "p2p_disc", 0); return ZX_OK; }
/* * Write two 0 bytes to identify the IDport and then reset the * ID sequence. Then send the ID sequence to the card to get * the card into command state. */ static void idseq(void) { int i; uchar al; static int reset, untag; if(reset == 0){ outb(IDport, 0); outb(IDport, 0); outb(IDport, 0xC0); delay(20); reset = 1; } outb(IDport, 0); outb(IDport, 0); for(al = 0xFF, i = 0; i < 255; i++){ outb(IDport, al); if(al & 0x80){ al <<= 1; al ^= 0xCF; } else al <<= 1; } if(untag == 0){ outb(IDport, 0xD0); untag = 1; } }
// SPDX-License-Identifier: GPL-2.0+ /* * i.MX drm driver - LVDS display bridge * * Copyright (C) 2012 Sascha Hauer, Pengutronix */ #include <linux/clk.h> #include <linux/component.h> #include <linux/mfd/syscon.h> #include <linux/mfd/syscon/imx6q-iomuxc-gpr.h> #include <linux/module.h> #include <linux/of_device.h> #include <linux/of_graph.h> #include <linux/regmap.h> #include <linux/videodev2.h> #include <video/of_display_timing.h> #include <video/of_videomode.h> #include <drm/drm_atomic.h> #include <drm/drm_atomic_helper.h> #include <drm/drm_bridge.h> #include <drm/drm_fb_helper.h> #include <drm/drm_managed.h> #include <drm/drm_of.h> #include <drm/drm_panel.h> #include <drm/drm_print.h> #include <drm/drm_probe_helper.h> #include <drm/drm_simple_kms_helper.h> #include "imx-drm.h" #define DRIVER_NAME "imx-ldb" #define LDB_CH0_MODE_EN_TO_DI0 (1 << 0) #define LDB_CH0_MODE_EN_TO_DI1 (3 << 0) #define LDB_CH0_MODE_EN_MASK (3 << 0) #define LDB_CH1_MODE_EN_TO_DI0 (1 << 2) #define LDB_CH1_MODE_EN_TO_DI1 (3 << 2) #define LDB_CH1_MODE_EN_MASK (3 << 2) #define LDB_SPLIT_MODE_EN (1 << 4) #define LDB_DATA_WIDTH_CH0_24 (1 << 5) #define LDB_BIT_MAP_CH0_JEIDA (1 << 6) #define LDB_DATA_WIDTH_CH1_24 (1 << 7) #define LDB_BIT_MAP_CH1_JEIDA (1 << 8) #define LDB_DI0_VS_POL_ACT_LOW (1 << 9) #define LDB_DI1_VS_POL_ACT_LOW (1 << 10) #define LDB_BGREF_RMODE_INT (1 << 15) struct imx_ldb_channel; struct imx_ldb_encoder { struct drm_connector connector; struct drm_encoder encoder; struct imx_ldb_channel *channel; }; struct imx_ldb; struct imx_ldb_channel { struct imx_ldb *ldb; /* Defines what is connected to the ldb, only one at a time */ struct drm_panel *panel; struct drm_bridge *bridge; struct device_node *child; struct i2c_adapter *ddc; int chno; void *edid; struct drm_display_mode mode; int mode_valid; u32 bus_format; u32 bus_flags; }; static inline struct imx_ldb_channel *con_to_imx_ldb_ch(struct drm_connector *c) { return container_of(c, struct imx_ldb_encoder, connector)->channel; } static inline struct imx_ldb_channel *enc_to_imx_ldb_ch(struct drm_encoder *e) { return container_of(e, struct imx_ldb_encoder, encoder)->channel; } struct bus_mux { int reg; int shift; int mask; }; struct imx_ldb { struct regmap *regmap; struct device *dev; struct imx_ldb_channel channel[2]; struct clk *clk[2]; /* our own clock */ struct clk *clk_sel[4]; /* parent of display clock */ struct clk *clk_parent[4]; /* original parent of clk_sel */ struct clk *clk_pll[2]; /* upstream clock we can adjust */ u32 ldb_ctrl; const struct bus_mux *lvds_mux; }; static void imx_ldb_ch_set_bus_format(struct imx_ldb_channel *imx_ldb_ch, u32 bus_format) { struct imx_ldb *ldb = imx_ldb_ch->ldb; int dual = ldb->ldb_ctrl & LDB_SPLIT_MODE_EN; switch (bus_format) { case MEDIA_BUS_FMT_RGB666_1X7X3_SPWG: break; case MEDIA_BUS_FMT_RGB888_1X7X4_SPWG: if (imx_ldb_ch->chno == 0 || dual) ldb->ldb_ctrl |= LDB_DATA_WIDTH_CH0_24; if (imx_ldb_ch->chno == 1 || dual) ldb->ldb_ctrl |= LDB_DATA_WIDTH_CH1_24; break; case MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA: if (imx_ldb_ch->chno == 0 || dual) ldb->ldb_ctrl |= LDB_DATA_WIDTH_CH0_24 | LDB_BIT_MAP_CH0_JEIDA; if (imx_ldb_ch->chno == 1 || dual) ldb->ldb_ctrl |= LDB_DATA_WIDTH_CH1_24 | LDB_BIT_MAP_CH1_JEIDA; break; } } static int imx_ldb_connector_get_modes(struct drm_connector *connector) { struct imx_ldb_channel *imx_ldb_ch = con_to_imx_ldb_ch(connector); int num_modes; num_modes = drm_panel_get_modes(imx_ldb_ch->panel, connector); if (num_modes > 0) return num_modes; if (!imx_ldb_ch->edid && imx_ldb_ch->ddc) imx_ldb_ch->edid = drm_get_edid(connector, imx_ldb_ch->ddc); if (imx_ldb_ch->edid) { drm_connector_update_edid_property(connector, imx_ldb_ch->edid); num_modes = drm_add_edid_modes(connector, imx_ldb_ch->edid); } if (imx_ldb_ch->mode_valid) { struct drm_display_mode *mode; mode = drm_mode_create(connector->dev); if (!mode) return -EINVAL; drm_mode_copy(mode, &imx_ldb_ch->mode); mode->type |= DRM_MODE_TYPE_DRIVER | DRM_MODE_TYPE_PREFERRED; drm_mode_probed_add(connector, mode); num_modes++; } return num_modes; } static void imx_ldb_set_clock(struct imx_ldb *ldb, int mux, int chno, unsigned long serial_clk, unsigned long di_clk) { int ret; dev_dbg(ldb->dev, "%s: now: %ld want: %ld\n", __func__, clk_get_rate(ldb->clk_pll[chno]), serial_clk); clk_set_rate(ldb->clk_pll[chno], serial_clk); dev_dbg(ldb->dev, "%s after: %ld\n", __func__, clk_get_rate(ldb->clk_pll[chno])); dev_dbg(ldb->dev, "%s: now: %ld want: %ld\n", __func__, clk_get_rate(ldb->clk[chno]), (long int)di_clk); clk_set_rate(ldb->clk[chno], di_clk); dev_dbg(ldb->dev, "%s after: %ld\n", __func__, clk_get_rate(ldb->clk[chno])); /* set display clock mux to LDB input clock */ ret = clk_set_parent(ldb->clk_sel[mux], ldb->clk[chno]); if (ret) dev_err(ldb->dev, "unable to set di%d parent clock to ldb_di%d\n", mux, chno); } static void imx_ldb_encoder_enable(struct drm_encoder *encoder) { struct imx_ldb_channel *imx_ldb_ch = enc_to_imx_ldb_ch(encoder); struct imx_ldb *ldb = imx_ldb_ch->ldb; int dual = ldb->ldb_ctrl & LDB_SPLIT_MODE_EN; int mux = drm_of_encoder_active_port_id(imx_ldb_ch->child, encoder); if (mux < 0 || mux >= ARRAY_SIZE(ldb->clk_sel)) { dev_warn(ldb->dev, "%s: invalid mux %d\n", __func__, mux); return; } drm_panel_prepare(imx_ldb_ch->panel); if (dual) { clk_set_parent(ldb->clk_sel[mux], ldb->clk[0]); clk_set_parent(ldb->clk_sel[mux], ldb->clk[1]); clk_prepare_enable(ldb->clk[0]); clk_prepare_enable(ldb->clk[1]); } else { clk_set_parent(ldb->clk_sel[mux], ldb->clk[imx_ldb_ch->chno]); } if (imx_ldb_ch == &ldb->channel[0] || dual) { ldb->ldb_ctrl &= ~LDB_CH0_MODE_EN_MASK; if (mux == 0 || ldb->lvds_mux) ldb->ldb_ctrl |= LDB_CH0_MODE_EN_TO_DI0; else if (mux == 1) ldb->ldb_ctrl |= LDB_CH0_MODE_EN_TO_DI1; } if (imx_ldb_ch == &ldb->channel[1] || dual) { ldb->ldb_ctrl &= ~LDB_CH1_MODE_EN_MASK; if (mux == 1 || ldb->lvds_mux) ldb->ldb_ctrl |= LDB_CH1_MODE_EN_TO_DI1; else if (mux == 0) ldb->ldb_ctrl |= LDB_CH1_MODE_EN_TO_DI0; } if (ldb->lvds_mux) { const struct bus_mux *lvds_mux = NULL; if (imx_ldb_ch == &ldb->channel[0]) lvds_mux = &ldb->lvds_mux[0]; else if (imx_ldb_ch == &ldb->channel[1]) lvds_mux = &ldb->lvds_mux[1]; regmap_update_bits(ldb->regmap, lvds_mux->reg, lvds_mux->mask, mux << lvds_mux->shift); } regmap_write(ldb->regmap, IOMUXC_GPR2, ldb->ldb_ctrl); drm_panel_enable(imx_ldb_ch->panel); } static void imx_ldb_encoder_atomic_mode_set(struct drm_encoder *encoder, struct drm_crtc_state *crtc_state, struct drm_connector_state *connector_state) { struct imx_ldb_channel *imx_ldb_ch = enc_to_imx_ldb_ch(encoder); struct drm_display_mode *mode = &crtc_state->adjusted_mode; struct imx_ldb *ldb = imx_ldb_ch->ldb; int dual = ldb->ldb_ctrl & LDB_SPLIT_MODE_EN; unsigned long serial_clk; unsigned long di_clk = mode->clock * 1000; int mux = drm_of_encoder_active_port_id(imx_ldb_ch->child, encoder); u32 bus_format = imx_ldb_ch->bus_format; if (mux < 0 || mux >= ARRAY_SIZE(ldb->clk_sel)) { dev_warn(ldb->dev, "%s: invalid mux %d\n", __func__, mux); return; } if (mode->clock > 170000) { dev_warn(ldb->dev, "%s: mode exceeds 170 MHz pixel clock\n", __func__); } if (mode->clock > 85000 && !dual) { dev_warn(ldb->dev, "%s: mode exceeds 85 MHz pixel clock\n", __func__); } if (dual) { serial_clk = 3500UL * mode->clock; imx_ldb_set_clock(ldb, mux, 0, serial_clk, di_clk); imx_ldb_set_clock(ldb, mux, 1, serial_clk, di_clk); } else { serial_clk = 7000UL * mode->clock; imx_ldb_set_clock(ldb, mux, imx_ldb_ch->chno, serial_clk, di_clk); } /* FIXME - assumes straight connections DI0 --> CH0, DI1 --> CH1 */ if (imx_ldb_ch == &ldb->channel[0] || dual) { if (mode->flags & DRM_MODE_FLAG_NVSYNC) ldb->ldb_ctrl |= LDB_DI0_VS_POL_ACT_LOW; else if (mode->flags & DRM_MODE_FLAG_PVSYNC) ldb->ldb_ctrl &= ~LDB_DI0_VS_POL_ACT_LOW; } if (imx_ldb_ch == &ldb->channel[1] || dual) { if (mode->flags & DRM_MODE_FLAG_NVSYNC) ldb->ldb_ctrl |= LDB_DI1_VS_POL_ACT_LOW; else if (mode->flags & DRM_MODE_FLAG_PVSYNC) ldb->ldb_ctrl &= ~LDB_DI1_VS_POL_ACT_LOW; } if (!bus_format) { struct drm_connector *connector = connector_state->connector; struct drm_display_info *di = &connector->display_info; if (di->num_bus_formats) bus_format = di->bus_formats[0]; } imx_ldb_ch_set_bus_format(imx_ldb_ch, bus_format); } static void imx_ldb_encoder_disable(struct drm_encoder *encoder) { struct imx_ldb_channel *imx_ldb_ch = enc_to_imx_ldb_ch(encoder); struct imx_ldb *ldb = imx_ldb_ch->ldb; int dual = ldb->ldb_ctrl & LDB_SPLIT_MODE_EN; int mux, ret; drm_panel_disable(imx_ldb_ch->panel); if (imx_ldb_ch == &ldb->channel[0] || dual) ldb->ldb_ctrl &= ~LDB_CH0_MODE_EN_MASK; if (imx_ldb_ch == &ldb->channel[1] || dual) ldb->ldb_ctrl &= ~LDB_CH1_MODE_EN_MASK; regmap_write(ldb->regmap, IOMUXC_GPR2, ldb->ldb_ctrl); if (dual) { clk_disable_unprepare(ldb->clk[0]); clk_disable_unprepare(ldb->clk[1]); } if (ldb->lvds_mux) { const struct bus_mux *lvds_mux = NULL; if (imx_ldb_ch == &ldb->channel[0]) lvds_mux = &ldb->lvds_mux[0]; else if (imx_ldb_ch == &ldb->channel[1]) lvds_mux = &ldb->lvds_mux[1]; regmap_read(ldb->regmap, lvds_mux->reg, &mux); mux &= lvds_mux->mask; mux >>= lvds_mux->shift; } else { mux = (imx_ldb_ch == &ldb->channel[0]) ? 0 : 1; } /* set display clock mux back to original input clock */ ret = clk_set_parent(ldb->clk_sel[mux], ldb->clk_parent[mux]); if (ret) dev_err(ldb->dev, "unable to set di%d parent clock to original parent\n", mux); drm_panel_unprepare(imx_ldb_ch->panel); } static int imx_ldb_encoder_atomic_check(struct drm_encoder *encoder, struct drm_crtc_state *crtc_state, struct drm_connector_state *conn_state) { struct imx_crtc_state *imx_crtc_state = to_imx_crtc_state(crtc_state); struct imx_ldb_channel *imx_ldb_ch = enc_to_imx_ldb_ch(encoder); struct drm_display_info *di = &conn_state->connector->display_info; u32 bus_format = imx_ldb_ch->bus_format; /* Bus format description in DT overrides connector display info. */ if (!bus_format && di->num_bus_formats) { bus_format = di->bus_formats[0]; imx_crtc_state->bus_flags = di->bus_flags; } else { bus_format = imx_ldb_ch->bus_format; imx_crtc_state->bus_flags = imx_ldb_ch->bus_flags; } switch (bus_format) { case MEDIA_BUS_FMT_RGB666_1X7X3_SPWG: imx_crtc_state->bus_format = MEDIA_BUS_FMT_RGB666_1X18; break; case MEDIA_BUS_FMT_RGB888_1X7X4_SPWG: case MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA: imx_crtc_state->bus_format = MEDIA_BUS_FMT_RGB888_1X24; break; default: return -EINVAL; } imx_crtc_state->di_hsync_pin = 2; imx_crtc_state->di_vsync_pin = 3; return 0; } static const struct drm_connector_funcs imx_ldb_connector_funcs = { .fill_modes = drm_helper_probe_single_connector_modes, .destroy = imx_drm_connector_destroy, .reset = drm_atomic_helper_connector_reset, .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, }; static const struct drm_connector_helper_funcs imx_ldb_connector_helper_funcs = { .get_modes = imx_ldb_connector_get_modes, }; static const struct drm_encoder_helper_funcs imx_ldb_encoder_helper_funcs = { .atomic_mode_set = imx_ldb_encoder_atomic_mode_set, .enable = imx_ldb_encoder_enable, .disable = imx_ldb_encoder_disable, .atomic_check = imx_ldb_encoder_atomic_check, }; static int imx_ldb_get_clk(struct imx_ldb *ldb, int chno) { char clkname[16]; snprintf(clkname, sizeof(clkname), "di%d", chno); ldb->clk[chno] = devm_clk_get(ldb->dev, clkname); if (IS_ERR(ldb->clk[chno])) return PTR_ERR(ldb->clk[chno]); snprintf(clkname, sizeof(clkname), "di%d_pll", chno); ldb->clk_pll[chno] = devm_clk_get(ldb->dev, clkname); return PTR_ERR_OR_ZERO(ldb->clk_pll[chno]); } static int imx_ldb_register(struct drm_device *drm, struct imx_ldb_channel *imx_ldb_ch) { struct imx_ldb *ldb = imx_ldb_ch->ldb; struct imx_ldb_encoder *ldb_encoder; struct drm_connector *connector; struct drm_encoder *encoder; int ret; ldb_encoder = drmm_simple_encoder_alloc(drm, struct imx_ldb_encoder, encoder, DRM_MODE_ENCODER_LVDS); if (IS_ERR(ldb_encoder)) return PTR_ERR(ldb_encoder); ldb_encoder->channel = imx_ldb_ch; connector = &ldb_encoder->connector; encoder = &ldb_encoder->encoder; ret = imx_drm_encoder_parse_of(drm, encoder, imx_ldb_ch->child); if (ret) return ret; ret = imx_ldb_get_clk(ldb, imx_ldb_ch->chno); if (ret) return ret; if (ldb->ldb_ctrl & LDB_SPLIT_MODE_EN) { ret = imx_ldb_get_clk(ldb, 1); if (ret) return ret; } drm_encoder_helper_add(encoder, &imx_ldb_encoder_helper_funcs); if (imx_ldb_ch->bridge) { ret = drm_bridge_attach(encoder, imx_ldb_ch->bridge, NULL, 0); if (ret) { DRM_ERROR("Failed to initialize bridge with drm\n"); return ret; } } else { /* * We want to add the connector whenever there is no bridge * that brings its own, not only when there is a panel. For * historical reasons, the ldb driver can also work without * a panel. */ drm_connector_helper_add(connector, &imx_ldb_connector_helper_funcs); drm_connector_init_with_ddc(drm, connector, &imx_ldb_connector_funcs, DRM_MODE_CONNECTOR_LVDS, imx_ldb_ch->ddc); drm_connector_attach_encoder(connector, encoder); } return 0; } struct imx_ldb_bit_mapping { u32 bus_format; u32 datawidth; const char * const mapping; }; static const struct imx_ldb_bit_mapping imx_ldb_bit_mappings[] = { { MEDIA_BUS_FMT_RGB666_1X7X3_SPWG, 18, "spwg" }, { MEDIA_BUS_FMT_RGB888_1X7X4_SPWG, 24, "spwg" }, { MEDIA_BUS_FMT_RGB888_1X7X4_JEIDA, 24, "jeida" }, }; static u32 of_get_bus_format(struct device *dev, struct device_node *np) { const char *bm; u32 datawidth = 0; int ret, i; ret = of_property_read_string(np, "fsl,data-mapping", &bm); if (ret < 0) return ret; of_property_read_u32(np, "fsl,data-width", &datawidth); for (i = 0; i < ARRAY_SIZE(imx_ldb_bit_mappings); i++) { if (!strcasecmp(bm, imx_ldb_bit_mappings[i].mapping) && datawidth == imx_ldb_bit_mappings[i].datawidth) return imx_ldb_bit_mappings[i].bus_format; } dev_err(dev, "invalid data mapping: %d-bit \"%s\"\n", datawidth, bm); return -ENOENT; } static struct bus_mux imx6q_lvds_mux[2] = { { .reg = IOMUXC_GPR3, .shift = 6, .mask = IMX6Q_GPR3_LVDS0_MUX_CTL_MASK, }, { .reg = IOMUXC_GPR3, .shift = 8, .mask = IMX6Q_GPR3_LVDS1_MUX_CTL_MASK, } }; /* * For a device declaring compatible = "fsl,imx6q-ldb", "fsl,imx53-ldb", * of_match_device will walk through this list and take the first entry * matching any of its compatible values. Therefore, the more generic * entries (in this case fsl,imx53-ldb) need to be ordered last. */ static const struct of_device_id imx_ldb_dt_ids[] = { { .compatible = "fsl,imx6q-ldb", .data = imx6q_lvds_mux, }, { .compatible = "fsl,imx53-ldb", .data = NULL, }, { } }; MODULE_DEVICE_TABLE(of, imx_ldb_dt_ids); static int imx_ldb_panel_ddc(struct device *dev, struct imx_ldb_channel *channel, struct device_node *child) { struct device_node *ddc_node; const u8 *edidp; int ret; ddc_node = of_parse_phandle(child, "ddc-i2c-bus", 0); if (ddc_node) { channel->ddc = of_find_i2c_adapter_by_node(ddc_node); of_node_put(ddc_node); if (!channel->ddc) { dev_warn(dev, "failed to get ddc i2c adapter\n"); return -EPROBE_DEFER; } } if (!channel->ddc) { int edid_len; /* if no DDC available, fallback to hardcoded EDID */ dev_dbg(dev, "no ddc available\n"); edidp = of_get_property(child, "edid", &edid_len); if (edidp) { channel->edid = kmemdup(edidp, edid_len, GFP_KERNEL); } else if (!channel->panel) { /* fallback to display-timings node */ ret = of_get_drm_display_mode(child, &channel->mode, &channel->bus_flags, OF_USE_NATIVE_MODE); if (!ret) channel->mode_valid = 1; } } return 0; } static int imx_ldb_bind(struct device *dev, struct device *master, void *data) { struct drm_device *drm = data; struct imx_ldb *imx_ldb = dev_get_drvdata(dev); int ret; int i; for (i = 0; i < 2; i++) { struct imx_ldb_channel *channel = &imx_ldb->channel[i]; if (!channel->ldb) continue; ret = imx_ldb_register(drm, channel); if (ret) return ret; } return 0; } static const struct component_ops imx_ldb_ops = { .bind = imx_ldb_bind, }; static int imx_ldb_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *np = dev->of_node; const struct of_device_id *of_id = of_match_device(imx_ldb_dt_ids, dev); struct device_node *child; struct imx_ldb *imx_ldb; int dual; int ret; int i; imx_ldb = devm_kzalloc(dev, sizeof(*imx_ldb), GFP_KERNEL); if (!imx_ldb) return -ENOMEM; imx_ldb->regmap = syscon_regmap_lookup_by_phandle(np, "gpr"); if (IS_ERR(imx_ldb->regmap)) { dev_err(dev, "failed to get parent regmap\n"); return PTR_ERR(imx_ldb->regmap); } /* disable LDB by resetting the control register to POR default */ regmap_write(imx_ldb->regmap, IOMUXC_GPR2, 0); imx_ldb->dev = dev; if (of_id) imx_ldb->lvds_mux = of_id->data; dual = of_property_read_bool(np, "fsl,dual-channel"); if (dual) imx_ldb->ldb_ctrl |= LDB_SPLIT_MODE_EN; /* * There are three different possible clock mux configurations: * i.MX53: ipu1_di0_sel, ipu1_di1_sel * i.MX6q: ipu1_di0_sel, ipu1_di1_sel, ipu2_di0_sel, ipu2_di1_sel * i.MX6dl: ipu1_di0_sel, ipu1_di1_sel, lcdif_sel * Map them all to di0_sel...di3_sel. */ for (i = 0; i < 4; i++) { char clkname[16]; sprintf(clkname, "di%d_sel", i); imx_ldb->clk_sel[i] = devm_clk_get(imx_ldb->dev, clkname); if (IS_ERR(imx_ldb->clk_sel[i])) { ret = PTR_ERR(imx_ldb->clk_sel[i]); imx_ldb->clk_sel[i] = NULL; break; } imx_ldb->clk_parent[i] = clk_get_parent(imx_ldb->clk_sel[i]); } if (i == 0) return ret; for_each_child_of_node(np, child) { struct imx_ldb_channel *channel; int bus_format; ret = of_property_read_u32(child, "reg", &i); if (ret || i < 0 || i > 1) { ret = -EINVAL; goto free_child; } if (!of_device_is_available(child)) continue; if (dual && i > 0) { dev_warn(dev, "dual-channel mode, ignoring second output\n"); continue; } channel = &imx_ldb->channel[i]; channel->ldb = imx_ldb; channel->chno = i; /* * The output port is port@4 with an external 4-port mux or * port@2 with the internal 2-port mux. */ ret = drm_of_find_panel_or_bridge(child, imx_ldb->lvds_mux ? 4 : 2, 0, &channel->panel, &channel->bridge); if (ret && ret != -ENODEV) goto free_child; /* panel ddc only if there is no bridge */ if (!channel->bridge) { ret = imx_ldb_panel_ddc(dev, channel, child); if (ret) goto free_child; } bus_format = of_get_bus_format(dev, child); if (bus_format == -EINVAL) { /* * If no bus format was specified in the device tree, * we can still get it from the connected panel later. */ if (channel->panel && channel->panel->funcs && channel->panel->funcs->get_modes) bus_format = 0; } if (bus_format < 0) { dev_err(dev, "could not determine data mapping: %d\n", bus_format); ret = bus_format; goto free_child; } channel->bus_format = bus_format; channel->child = child; } platform_set_drvdata(pdev, imx_ldb); return component_add(&pdev->dev, &imx_ldb_ops); free_child: of_node_put(child); return ret; } static int imx_ldb_remove(struct platform_device *pdev) { struct imx_ldb *imx_ldb = platform_get_drvdata(pdev); int i; for (i = 0; i < 2; i++) { struct imx_ldb_channel *channel = &imx_ldb->channel[i]; kfree(channel->edid); i2c_put_adapter(channel->ddc); } component_del(&pdev->dev, &imx_ldb_ops); return 0; } static struct platform_driver imx_ldb_driver = { .probe = imx_ldb_probe, .remove = imx_ldb_remove, .driver = { .of_match_table = imx_ldb_dt_ids, .name = DRIVER_NAME, }, }; module_platform_driver(imx_ldb_driver); MODULE_DESCRIPTION("i.MX LVDS driver"); MODULE_AUTHOR("Sascha Hauer, Pengutronix"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRIVER_NAME);
/** Tripod gait moves the hexapod in the direction dir1 for steps. Three legs forming a tripod move first then the other three legs move Used for normal gait of the hexapod @param dir1 : Direction of motion @param steps : number of steps */ void tripod_gait(unsigned char dir1, unsigned char steps) { unsigned char dir3 = ((dir1 + 1) % 6) + 1; unsigned char dir5 = ((dir3 + 1) % 6) + 1; unsigned char dir2 = 7 - dir5; unsigned char dir4 = 7 - dir3; unsigned char dir6 = 7 - dir1; unsigned char step_forward = 70; unsigned char step_side = 50; unsigned char lift = 40; int delay_time = TWO_HUNDRED_FIFTY_MSEC; if(dir1%2 == 0) { swap(&dir2, &dir4); swap(&dir3, &dir5); } while (steps-- > 0) { angle(dir1, MOTOR_B, 90); angle(dir3, MOTOR_B, 90); angle(dir5, MOTOR_B, 90); delay(HUNDRED_MSEC); angle(dir2, MOTOR_B, lift); angle(dir4, MOTOR_B, lift); angle(dir6, MOTOR_B, lift); delay(delay_time); angle(dir1, MOTOR_C, 90); angle(dir3, MOTOR_A, 90); angle(dir5, MOTOR_A, 90); angle(dir2, MOTOR_A, 90 - step_side); angle(dir4, MOTOR_A, 90 + step_side); angle(dir6, MOTOR_C, 90 + step_forward); delay(delay_time); angle(dir2, MOTOR_B, 90); angle(dir4, MOTOR_B, 90); angle(dir6, MOTOR_B, 90); delay(HUNDRED_MSEC); angle(dir1, MOTOR_B, lift); angle(dir3, MOTOR_B, lift); angle(dir5, MOTOR_B, lift); delay(delay_time); angle(dir1, MOTOR_C, 90 + step_forward); angle(dir3, MOTOR_A, 90 - step_side); angle(dir5, MOTOR_A, 90 + step_side); angle(dir2, MOTOR_A, 90); angle(dir4, MOTOR_A, 90); angle(dir6, MOTOR_C, 90); delay(delay_time); } }
/** * Creates a new complex number equals to a + i*b. */ cDouble* newCDouble(double a, double b) { cDouble *z = malloc(sizeof(cDouble)); assert(z != NULL); z->a = a; z->b = b; return z; }
/** * Read pages from server. * * Page in MDS_READPAGE RPC is packed in LU_PAGE_SIZE, and each page contains * a header lu_dirpage which describes the start/end hash, and whether this * page is empty (contains no dir entry) or hash collide with next page. * After client receives reply, several pages will be integrated into dir page * in PAGE_SIZE (if PAGE_SIZE greater than LU_PAGE_SIZE), and the * lu_dirpage for this integrated page will be adjusted. **/ static int mdc_read_page_remote(void *data, struct page *page0) { struct readpage_param *rp = data; struct page **page_pool; struct page *page; struct lu_dirpage *dp; int rd_pgs = 0; int npages; struct md_op_data *op_data = rp->rp_mod; struct ptlrpc_request *req; int max_pages = op_data->op_max_pages; struct inode *inode; struct lu_fid *fid; int i; int rc; LASSERT(max_pages > 0 && max_pages <= PTLRPC_MAX_BRW_PAGES); inode = op_data->op_data; fid = &op_data->op_fid1; LASSERT(inode); page_pool = kcalloc(max_pages, sizeof(page), GFP_NOFS); if (page_pool) { page_pool[0] = page0; } else { page_pool = &page0; max_pages = 1; } for (npages = 1; npages < max_pages; npages++) { page = page_cache_alloc_cold(inode->i_mapping); if (!page) break; page_pool[npages] = page; } rc = mdc_getpage(rp->rp_exp, fid, rp->rp_off, page_pool, npages, &req); if (!rc) { int lu_pgs = req->rq_bulk->bd_nob_transferred; rd_pgs = (req->rq_bulk->bd_nob_transferred + PAGE_SIZE - 1) >> PAGE_SHIFT; lu_pgs >>= LU_PAGE_SHIFT; LASSERT(!(req->rq_bulk->bd_nob_transferred & ~LU_PAGE_MASK)); CDEBUG(D_INODE, "read %d(%d) pages\n", rd_pgs, lu_pgs); mdc_adjust_dirpages(page_pool, rd_pgs, lu_pgs); SetPageUptodate(page0); } unlock_page(page0); ptlrpc_req_finished(req); CDEBUG(D_CACHE, "read %d/%d pages\n", rd_pgs, npages); for (i = 1; i < npages; i++) { unsigned long offset; __u64 hash; int ret; page = page_pool[i]; if (rc < 0 || i >= rd_pgs) { put_page(page); continue; } SetPageUptodate(page); dp = kmap(page); hash = le64_to_cpu(dp->ldp_hash_start); kunmap(page); offset = hash_x_index(hash, rp->rp_hash64); prefetchw(&page->flags); ret = add_to_page_cache_lru(page, inode->i_mapping, offset, GFP_KERNEL); if (!ret) unlock_page(page); else CDEBUG(D_VFSTRACE, "page %lu add to page cache failed: rc = %d\n", offset, ret); put_page(page); } if (page_pool != &page0) kfree(page_pool); return rc; }
#include <math.h> #define EPS 1.0e-6 #define JMAX 20 #define JMAXP (JMAX+1) #define K 10 double qromb1(double (*func)(double), double a, double b) { void polint1(double xa[], double ya[], int n, double x, double *y, double *dy); double trapzd1(double (*func)(double), double a, double b, int n); void nrerror(char error_text[]); double ss,dss; double s[JMAXP],h[JMAXP+1]; int j; h[1]=1.0; for (j=1;j<=JMAX;j++) { s[j]=trapzd1(func,a,b,j); if (j >= K) { polint1(&h[j-K],&s[j-K],K,0.0,&ss,&dss); if (fabs(dss) <= EPS*fabs(ss)) return ss; } h[j+1]=0.25*h[j]; } nrerror("Too many steps in routine qromb1"); return 0.0; } #undef EPS #undef JMAX #undef JMAXP #undef K
/* * Printing to UART. * These functions are useful for debugging a bootloader. */ static inline void cinit() { U1BRG = PIC32_BRG_BAUD (CPU_KHZ * 1000, 115200); U1STA = 0; U1MODE = PIC32_UMODE_PDSEL_8NPAR | PIC32_UMODE_ON; U1STASET = PIC32_USTA_URXEN | PIC32_USTA_UTXEN; }
/* Return a pointer to the next token from PARSER, reading it in if necessary. */ c_token * c_parser_peek_token (c_parser *parser) { if (parser->tokens_avail == 0) { c_lex_one_token (parser, &parser->tokens[0]); parser->tokens_avail = 1; } return &parser->tokens[0]; }
/******************************************************************************* * Function Name: CapSense_TMG_ballisticsMultiplier ******************************************************************************** * * Summary: * This API is to run the ballistic Multiplier. * CapSense_TMG_TimerEnableInt has to be called once prior calling this API. * * Parameters: * ballisticMultiplier: Pointer to the structure which contains API parameters. * currentTimestamp : Current timestamp value. * pos: Pointer to dX and dY coordinates. * * Return: * None * * Global Variables: * None * *******************************************************************************/ void CapSense_TMG_BallisticsMultiplier(const CapSense_TMG_BALLISTIC_MULT * ballisticMultiplier, uint32_t currentTimestamp, int16_t *pos) { #if (CapSense_TMG_BALLISTICS_ENABLED == 1u) CapSense_TMG_BALLISTIC_MULT_INT ballisticsStrct; ballisticsStrct.paramStr = *ballisticMultiplier; ballisticsStrct.currentTimestamp = currentTimestamp; BallisticMultiplier(&ballisticsStrct, pos); #endif }
#include <stdio.h> #include<string.h> int main(void) { char s[6000]; scanf("%s",s); int n=strlen(s); n=n-1; long long int count1=0; long long int count2=0; long long prod=0; int pos=-1; char b='b'; char e='e'; char a='a'; char r='r'; long long int sum=0; for(int i=0;i<=n-3;i++) { if(s[i]=='b'&&s[i+1]=='e'&&s[i+2]=='a'&&s[i+3]=='r') { count1=i-pos; //printf("cnt1=%d\n",count1); count2=n-i; count2=count2-2; //printf("cnt2=%d\n",count2); prod=count1*count2; sum=sum+prod; pos=i; //printf("pos=%d",pos); } } printf("%lld",sum); return 0; }
#ifndef UTILS_RNG_OPTIONS_H #define UTILS_RNG_OPTIONS_H #include <memory> namespace options { class OptionParser; class Options; } namespace utils { class RandomNumberGenerator; // Add random_seed option to parser. extern void add_rng_options(options::OptionParser &parser); /* Return an RNG based on the given options, which can either be the global RNG or a local one with a user-specified seed. Only use this together with "add_rng_options()". */ extern std::shared_ptr<RandomNumberGenerator> parse_rng_from_options( const options::Options &options); } #endif
/** * gfs2_block_map - Map a block from an inode to a disk block * @inode: The inode * @lblock: The logical block number * @bh_map: The bh to be mapped * @create: True if its ok to alloc blocks to satify the request * * Sets buffer_mapped() if successful, sets buffer_boundary() if a * read of metadata will be required before the next block can be * mapped. Sets buffer_new() if new blocks were allocated. * * Returns: errno */ int gfs2_block_map(struct inode *inode, sector_t lblock, struct buffer_head *bh_map, int create) { struct gfs2_inode *ip = GFS2_I(inode); struct gfs2_sbd *sdp = GFS2_SB(inode); unsigned int bsize = sdp->sd_sb.sb_bsize; const size_t maxlen = bh_map->b_size >> inode->i_blkbits; const u64 *arr = sdp->sd_heightsize; __be64 *ptr; u64 size; struct metapath mp; int ret; int eob; unsigned int len; struct buffer_head *bh; u8 height; BUG_ON(maxlen == 0); memset(&mp, 0, sizeof(mp)); bmap_lock(ip, create); clear_buffer_mapped(bh_map); clear_buffer_new(bh_map); clear_buffer_boundary(bh_map); trace_gfs2_bmap(ip, bh_map, lblock, create, 1); if (gfs2_is_dir(ip)) { bsize = sdp->sd_jbsize; arr = sdp->sd_jheightsize; } ret = gfs2_meta_inode_buffer(ip, &mp.mp_bh[0]); if (ret) goto out; height = ip->i_height; size = (lblock + 1) * bsize; while (size > arr[height]) height++; find_metapath(sdp, lblock, &mp, height); ret = 1; if (height > ip->i_height || gfs2_is_stuffed(ip)) goto do_alloc; ret = lookup_metapath(ip, &mp); if (ret < 0) goto out; if (ret != ip->i_height) goto do_alloc; ptr = metapointer(ip->i_height - 1, &mp); if (*ptr == 0) goto do_alloc; map_bh(bh_map, inode->i_sb, be64_to_cpu(*ptr)); bh = mp.mp_bh[ip->i_height - 1]; len = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob); bh_map->b_size = (len << inode->i_blkbits); if (eob) set_buffer_boundary(bh_map); ret = 0; out: release_metapath(&mp); trace_gfs2_bmap(ip, bh_map, lblock, create, ret); bmap_unlock(ip, create); return ret; do_alloc: if (!create) { BUG_ON(gfs2_is_stuffed(ip)); ret = 0; goto out; } ret = gfs2_bmap_alloc(inode, lblock, bh_map, &mp, ret, height, maxlen); goto out; }
/** Sesto core initialization * This function initialize the sesto core by downlaoding the firmware. * * @param core Pointer to phymod core access structure * @param init_config Init configuration specified by user * @param core_status PMD status read from PHY chip * * @return PHYMOD_E_NONE successful function execution */ int sesto_core_init(const phymod_core_access_t* core, const phymod_core_init_config_t* init_config, const phymod_core_status_t* core_status) { uint32_t chip_id = 0, rev = 0; uint8_t sys_side_core = 0; int rv = PHYMOD_E_NONE; SESTO_IF_ERR_RETURN( _sesto_core_init(core, init_config)); SESTO_IF_ERR_RETURN(sesto_get_chipid(&core->access, &chip_id, &rev)); if (chip_id != SESTO_CHIP_ID_82764) { sys_side_core = PHYMOD_INTF_CONFIG_PORT_PHY_MODE_REVERSE_GET(core) ? SESTO_FALCON_CORE: SESTO_MERLIN_CORE; } else { sys_side_core = PHYMOD_INTF_CONFIG_PORT_PHY_MODE_REVERSE_GET(core) ? SESTO_MERLIN_CORE: SESTO_FALCON_CORE; } SESTO_CHIP_FIELD_WRITE(&core->access, DP_SESTO_MODE_CTRL0, mode_falcon_line, !sys_side_core); ERR: return rv; }
/** * wil6210_disconnect - disconnect one connection * @vif: virtual interface context * @bssid: peer to disconnect, NULL to disconnect all * @reason_code: Reason code for the Disassociation frame * @from_event: whether is invoked from FW event handler * * Disconnect and release associated resources. If invoked not from the * FW event handler, issue WMI command(s) to trigger MAC disconnect. */ void wil6210_disconnect(struct wil6210_vif *vif, const u8 *bssid, u16 reason_code, bool from_event) { struct wil6210_priv *wil = vif_to_wil(vif); wil_dbg_misc(wil, "disconnect\n"); del_timer_sync(&vif->connect_timer); _wil6210_disconnect(vif, bssid, reason_code, from_event); }
/* * If we are using libata we can drive this chip properly but must * do this early on to make the additional device appear during * the PCI scanning. */ static void quirk_jmicron_ata(struct pci_dev *pdev) { u32 conf1, conf5, class; u8 hdr; if (PCI_FUNC(pdev->devfn)) return; pci_read_config_dword(pdev, 0x40, &conf1); pci_read_config_dword(pdev, 0x80, &conf5); conf1 &= ~0x00CFF302; conf5 &= ~(1 << 24); switch (pdev->device) { case PCI_DEVICE_ID_JMICRON_JMB360: conf1 |= 0x0002A100; break; case PCI_DEVICE_ID_JMICRON_JMB365: case PCI_DEVICE_ID_JMICRON_JMB366: conf5 |= (1 << 24); case PCI_DEVICE_ID_JMICRON_JMB361: case PCI_DEVICE_ID_JMICRON_JMB363: conf1 |= 0x00C2A102; break; case PCI_DEVICE_ID_JMICRON_JMB368: conf1 |= 0x00C00000; break; } pci_write_config_dword(pdev, 0x40, conf1); pci_write_config_dword(pdev, 0x80, conf5); pci_read_config_byte(pdev, PCI_HEADER_TYPE, &hdr); pdev->hdr_type = hdr & 0x7f; pdev->multifunction = !!(hdr & 0x80); pci_read_config_dword(pdev, PCI_CLASS_REVISION, &class); pdev->class = class >> 8; }
/** * Grab one sample from the ADXL362 accelerometer */ BOOL ACCEL_singleSample_FIFO(threeAxis_t_8* result) { while(!SPI_acquirePort()); BITCLR(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_transaction(gpRxBuf, (uint8_t*)ADXL_READ_XYZ_16BIT_FIFO, sizeof(ADXL_READ_XYZ_16BIT_FIFO)); BITSET(POUT_ACCEL_CS, PIN_ACCEL_CS); SPI_releasePort(); result->x = ((gpRxBuf[2] & 0x0F) << 4)|((gpRxBuf[1] & 0xF0) >> 4); result->y = ((gpRxBuf[4] & 0x0F) << 4)|((gpRxBuf[3] & 0xF0) >> 4); result->z = ((gpRxBuf[6] & 0x0F) << 4)|((gpRxBuf[5] & 0xF0) >> 4); return SUCCESS; }
/**************************************************************************** * Name: spi_lock * * Description: * On SPI buses where there are multiple devices, it will be necessary to * lock SPI to have exclusive access to the buses for a sequence of * transfers. The bus should be locked before the chip is selected. After * locking the SPI bus, the caller should then also call the setfrequency, * setbits, and setmode methods to make sure that the SPI is properly * configured for the device. If the SPI bus is being shared, then it * may have been left in an incompatible state. * * Input Parameters: * dev - Device-specific state data * lock - true: Lock spi bus, false: unlock SPI bus * * Returned Value: * None * ****************************************************************************/ static int spi_lock(struct spi_dev_s *dev, bool lock) { struct max326_spidev_s *priv = (struct max326_spidev_s *)dev; int ret; if (lock) { ret = nxsem_wait_uninterruptible(&priv->exclsem); } else { ret = nxsem_post(&priv->exclsem); } return ret; }
#include<stdio.h> #include<string.h> char q[10][10]; int book[10],b,a,c,l[20],m[20],n[10]; void abc(int); int main() { int i,j; scanf("%d",&b); for(i=0;i<8;i++) for(j=0;j<8;j++) q[i][j]='.'; for(i=0;i<b;i++) { scanf("%d%d",&a,&c); q[a][c]='Q'; book[c]=1; l[a+c]=1; m[a-c+8]=1; n[a]=1; } abc(0); return 0; } void abc(int p) { int i; if(n[p]==1) abc(p+1); if(p==8) { for(i=0;i<8;i++) printf("%s\n",q[i]); return; } for(i=0;i<8;i++) { if(book[i]==0&&l[p+i]==0&&m[p-i+8]==0) { book[i]=1; l[p+i]=1; m[p-i+8]=1; q[p][i]='Q'; abc(p+1); book[i]=0; l[p+i]=0; m[p-i+8]=0; q[p][i]='.'; } } }
/* I_FIND seems to live a life of its own */ static int my_find(int fd, char *module) { #if defined(I_FIND) && defined(I_LIST) static int flag; static struct str_list sl; int n; int i; if(!flag){ n = ioctl(fd, I_LIST, 0); if(n < 0){ perror("ioctl(fd, I_LIST, 0)"); return -1; } sl.sl_modlist=(struct str_mlist*)malloc(n * sizeof(struct str_mlist)); sl.sl_nmods = n; n = ioctl(fd, I_LIST, &sl); if(n < 0){ perror("ioctl(fd, I_LIST, n)"); return -1; } flag = 1; } for(i=0; i<sl.sl_nmods; i++) if(!strcmp(sl.sl_modlist[i].l_name, module)) return 1; #endif return 0; }
#include <stdio.h> #include <string.h> int main(void){ char O[50]; char E[50]; scanf("%s",&O); scanf("%s",&E); char ans[strlen(O)+strlen(E)]; int j= strlen(O)-strlen(E); for(int i=0;i<strlen(O)+strlen(E)-abs(j);i++){ if(i%2==0){ ans[i]=O[i/2]; }else{ ans[i]=E[i/2]; } } int count=0; if(j>0){ for(int i=strlen(O)+strlen(E)-abs(j);i<strlen(O)+strlen(E);i++) { ans[i]=O[(strlen(O)+strlen(E)-abs(j))/2+count]; count++; } }else if(j<0){ for(int i=strlen(O)+strlen(E)-abs(j);i<strlen(O)+strlen(E);i++) { ans[i]=E[(strlen(O)+strlen(E)-abs(j))/2+count]; count++; } } printf("%s",ans); return 0; }
/* * security/tomoyo/network.c * * Copyright (C) 2005-2011 NTT DATA CORPORATION */ #include "common.h" #include <linux/slab.h> /* Structure for holding inet domain socket's address. */ struct tomoyo_inet_addr_info { __be16 port; /* In network byte order. */ const __be32 *address; /* In network byte order. */ bool is_ipv6; }; /* Structure for holding unix domain socket's address. */ struct tomoyo_unix_addr_info { u8 *addr; /* This may not be '\0' terminated string. */ unsigned int addr_len; }; /* Structure for holding socket address. */ struct tomoyo_addr_info { u8 protocol; u8 operation; struct tomoyo_inet_addr_info inet; struct tomoyo_unix_addr_info unix0; }; /* String table for socket's protocols. */ const char * const tomoyo_proto_keyword[TOMOYO_SOCK_MAX] = { [SOCK_STREAM] = "stream", [SOCK_DGRAM] = "dgram", [SOCK_RAW] = "raw", [SOCK_SEQPACKET] = "seqpacket", [0] = " ", /* Dummy for avoiding NULL pointer dereference. */ [4] = " ", /* Dummy for avoiding NULL pointer dereference. */ }; /** * tomoyo_parse_ipaddr_union - Parse an IP address. * * @param: Pointer to "struct tomoyo_acl_param". * @ptr: Pointer to "struct tomoyo_ipaddr_union". * * Returns true on success, false otherwise. */ bool tomoyo_parse_ipaddr_union(struct tomoyo_acl_param *param, struct tomoyo_ipaddr_union *ptr) { u8 * const min = ptr->ip[0].in6_u.u6_addr8; u8 * const max = ptr->ip[1].in6_u.u6_addr8; char *address = tomoyo_read_token(param); const char *end; if (!strchr(address, ':') && in4_pton(address, -1, min, '-', &end) > 0) { ptr->is_ipv6 = false; if (!*end) ptr->ip[1].s6_addr32[0] = ptr->ip[0].s6_addr32[0]; else if (*end++ != '-' || in4_pton(end, -1, max, '\0', &end) <= 0 || *end) return false; return true; } if (in6_pton(address, -1, min, '-', &end) > 0) { ptr->is_ipv6 = true; if (!*end) memmove(max, min, sizeof(u16) * 8); else if (*end++ != '-' || in6_pton(end, -1, max, '\0', &end) <= 0 || *end) return false; return true; } return false; } /** * tomoyo_print_ipv4 - Print an IPv4 address. * * @buffer: Buffer to write to. * @buffer_len: Size of @buffer. * @min_ip: Pointer to __be32. * @max_ip: Pointer to __be32. * * Returns nothing. */ static void tomoyo_print_ipv4(char *buffer, const unsigned int buffer_len, const __be32 *min_ip, const __be32 *max_ip) { snprintf(buffer, buffer_len, "%pI4%c%pI4", min_ip, *min_ip == *max_ip ? '\0' : '-', max_ip); } /** * tomoyo_print_ipv6 - Print an IPv6 address. * * @buffer: Buffer to write to. * @buffer_len: Size of @buffer. * @min_ip: Pointer to "struct in6_addr". * @max_ip: Pointer to "struct in6_addr". * * Returns nothing. */ static void tomoyo_print_ipv6(char *buffer, const unsigned int buffer_len, const struct in6_addr *min_ip, const struct in6_addr *max_ip) { snprintf(buffer, buffer_len, "%pI6c%c%pI6c", min_ip, !memcmp(min_ip, max_ip, 16) ? '\0' : '-', max_ip); } /** * tomoyo_print_ip - Print an IP address. * * @buf: Buffer to write to. * @size: Size of @buf. * @ptr: Pointer to "struct ipaddr_union". * * Returns nothing. */ void tomoyo_print_ip(char *buf, const unsigned int size, const struct tomoyo_ipaddr_union *ptr) { if (ptr->is_ipv6) tomoyo_print_ipv6(buf, size, &ptr->ip[0], &ptr->ip[1]); else tomoyo_print_ipv4(buf, size, &ptr->ip[0].s6_addr32[0], &ptr->ip[1].s6_addr32[0]); } /* * Mapping table from "enum tomoyo_network_acl_index" to * "enum tomoyo_mac_index" for inet domain socket. */ static const u8 tomoyo_inet2mac [TOMOYO_SOCK_MAX][TOMOYO_MAX_NETWORK_OPERATION] = { [SOCK_STREAM] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_INET_STREAM_BIND, [TOMOYO_NETWORK_LISTEN] = TOMOYO_MAC_NETWORK_INET_STREAM_LISTEN, [TOMOYO_NETWORK_CONNECT] = TOMOYO_MAC_NETWORK_INET_STREAM_CONNECT, }, [SOCK_DGRAM] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_INET_DGRAM_BIND, [TOMOYO_NETWORK_SEND] = TOMOYO_MAC_NETWORK_INET_DGRAM_SEND, }, [SOCK_RAW] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_INET_RAW_BIND, [TOMOYO_NETWORK_SEND] = TOMOYO_MAC_NETWORK_INET_RAW_SEND, }, }; /* * Mapping table from "enum tomoyo_network_acl_index" to * "enum tomoyo_mac_index" for unix domain socket. */ static const u8 tomoyo_unix2mac [TOMOYO_SOCK_MAX][TOMOYO_MAX_NETWORK_OPERATION] = { [SOCK_STREAM] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_UNIX_STREAM_BIND, [TOMOYO_NETWORK_LISTEN] = TOMOYO_MAC_NETWORK_UNIX_STREAM_LISTEN, [TOMOYO_NETWORK_CONNECT] = TOMOYO_MAC_NETWORK_UNIX_STREAM_CONNECT, }, [SOCK_DGRAM] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_UNIX_DGRAM_BIND, [TOMOYO_NETWORK_SEND] = TOMOYO_MAC_NETWORK_UNIX_DGRAM_SEND, }, [SOCK_SEQPACKET] = { [TOMOYO_NETWORK_BIND] = TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_BIND, [TOMOYO_NETWORK_LISTEN] = TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_LISTEN, [TOMOYO_NETWORK_CONNECT] = TOMOYO_MAC_NETWORK_UNIX_SEQPACKET_CONNECT, }, }; /** * tomoyo_same_inet_acl - Check for duplicated "struct tomoyo_inet_acl" entry. * * @a: Pointer to "struct tomoyo_acl_info". * @b: Pointer to "struct tomoyo_acl_info". * * Returns true if @a == @b except permission bits, false otherwise. */ static bool tomoyo_same_inet_acl(const struct tomoyo_acl_info *a, const struct tomoyo_acl_info *b) { const struct tomoyo_inet_acl *p1 = container_of(a, typeof(*p1), head); const struct tomoyo_inet_acl *p2 = container_of(b, typeof(*p2), head); return p1->protocol == p2->protocol && tomoyo_same_ipaddr_union(&p1->address, &p2->address) && tomoyo_same_number_union(&p1->port, &p2->port); } /** * tomoyo_same_unix_acl - Check for duplicated "struct tomoyo_unix_acl" entry. * * @a: Pointer to "struct tomoyo_acl_info". * @b: Pointer to "struct tomoyo_acl_info". * * Returns true if @a == @b except permission bits, false otherwise. */ static bool tomoyo_same_unix_acl(const struct tomoyo_acl_info *a, const struct tomoyo_acl_info *b) { const struct tomoyo_unix_acl *p1 = container_of(a, typeof(*p1), head); const struct tomoyo_unix_acl *p2 = container_of(b, typeof(*p2), head); return p1->protocol == p2->protocol && tomoyo_same_name_union(&p1->name, &p2->name); } /** * tomoyo_merge_inet_acl - Merge duplicated "struct tomoyo_inet_acl" entry. * * @a: Pointer to "struct tomoyo_acl_info". * @b: Pointer to "struct tomoyo_acl_info". * @is_delete: True for @a &= ~@b, false for @a |= @b. * * Returns true if @a is empty, false otherwise. */ static bool tomoyo_merge_inet_acl(struct tomoyo_acl_info *a, struct tomoyo_acl_info *b, const bool is_delete) { u8 * const a_perm = &container_of(a, struct tomoyo_inet_acl, head)->perm; u8 perm = *a_perm; const u8 b_perm = container_of(b, struct tomoyo_inet_acl, head)->perm; if (is_delete) perm &= ~b_perm; else perm |= b_perm; *a_perm = perm; return !perm; } /** * tomoyo_merge_unix_acl - Merge duplicated "struct tomoyo_unix_acl" entry. * * @a: Pointer to "struct tomoyo_acl_info". * @b: Pointer to "struct tomoyo_acl_info". * @is_delete: True for @a &= ~@b, false for @a |= @b. * * Returns true if @a is empty, false otherwise. */ static bool tomoyo_merge_unix_acl(struct tomoyo_acl_info *a, struct tomoyo_acl_info *b, const bool is_delete) { u8 * const a_perm = &container_of(a, struct tomoyo_unix_acl, head)->perm; u8 perm = *a_perm; const u8 b_perm = container_of(b, struct tomoyo_unix_acl, head)->perm; if (is_delete) perm &= ~b_perm; else perm |= b_perm; *a_perm = perm; return !perm; } /** * tomoyo_write_inet_network - Write "struct tomoyo_inet_acl" list. * * @param: Pointer to "struct tomoyo_acl_param". * * Returns 0 on success, negative value otherwise. * * Caller holds tomoyo_read_lock(). */ int tomoyo_write_inet_network(struct tomoyo_acl_param *param) { struct tomoyo_inet_acl e = { .head.type = TOMOYO_TYPE_INET_ACL }; int error = -EINVAL; u8 type; const char *protocol = tomoyo_read_token(param); const char *operation = tomoyo_read_token(param); for (e.protocol = 0; e.protocol < TOMOYO_SOCK_MAX; e.protocol++) if (!strcmp(protocol, tomoyo_proto_keyword[e.protocol])) break; for (type = 0; type < TOMOYO_MAX_NETWORK_OPERATION; type++) if (tomoyo_permstr(operation, tomoyo_socket_keyword[type])) e.perm |= 1 << type; if (e.protocol == TOMOYO_SOCK_MAX || !e.perm) return -EINVAL; if (param->data[0] == '@') { param->data++; e.address.group = tomoyo_get_group(param, TOMOYO_ADDRESS_GROUP); if (!e.address.group) return -ENOMEM; } else { if (!tomoyo_parse_ipaddr_union(param, &e.address)) goto out; } if (!tomoyo_parse_number_union(param, &e.port) || e.port.values[1] > 65535) goto out; error = tomoyo_update_domain(&e.head, sizeof(e), param, tomoyo_same_inet_acl, tomoyo_merge_inet_acl); out: tomoyo_put_group(e.address.group); tomoyo_put_number_union(&e.port); return error; } /** * tomoyo_write_unix_network - Write "struct tomoyo_unix_acl" list. * * @param: Pointer to "struct tomoyo_acl_param". * * Returns 0 on success, negative value otherwise. */ int tomoyo_write_unix_network(struct tomoyo_acl_param *param) { struct tomoyo_unix_acl e = { .head.type = TOMOYO_TYPE_UNIX_ACL }; int error; u8 type; const char *protocol = tomoyo_read_token(param); const char *operation = tomoyo_read_token(param); for (e.protocol = 0; e.protocol < TOMOYO_SOCK_MAX; e.protocol++) if (!strcmp(protocol, tomoyo_proto_keyword[e.protocol])) break; for (type = 0; type < TOMOYO_MAX_NETWORK_OPERATION; type++) if (tomoyo_permstr(operation, tomoyo_socket_keyword[type])) e.perm |= 1 << type; if (e.protocol == TOMOYO_SOCK_MAX || !e.perm) return -EINVAL; if (!tomoyo_parse_name_union(param, &e.name)) return -EINVAL; error = tomoyo_update_domain(&e.head, sizeof(e), param, tomoyo_same_unix_acl, tomoyo_merge_unix_acl); tomoyo_put_name_union(&e.name); return error; } /** * tomoyo_audit_net_log - Audit network log. * * @r: Pointer to "struct tomoyo_request_info". * @family: Name of socket family ("inet" or "unix"). * @protocol: Name of protocol in @family. * @operation: Name of socket operation. * @address: Name of address. * * Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_net_log(struct tomoyo_request_info *r, const char *family, const u8 protocol, const u8 operation, const char *address) { return tomoyo_supervisor(r, "network %s %s %s %s\n", family, tomoyo_proto_keyword[protocol], tomoyo_socket_keyword[operation], address); } /** * tomoyo_audit_inet_log - Audit INET network log. * * @r: Pointer to "struct tomoyo_request_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_inet_log(struct tomoyo_request_info *r) { char buf[128]; int len; const __be32 *address = r->param.inet_network.address; if (r->param.inet_network.is_ipv6) tomoyo_print_ipv6(buf, sizeof(buf), (const struct in6_addr *) address, (const struct in6_addr *) address); else tomoyo_print_ipv4(buf, sizeof(buf), address, address); len = strlen(buf); snprintf(buf + len, sizeof(buf) - len, " %u", r->param.inet_network.port); return tomoyo_audit_net_log(r, "inet", r->param.inet_network.protocol, r->param.inet_network.operation, buf); } /** * tomoyo_audit_unix_log - Audit UNIX network log. * * @r: Pointer to "struct tomoyo_request_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_audit_unix_log(struct tomoyo_request_info *r) { return tomoyo_audit_net_log(r, "unix", r->param.unix_network.protocol, r->param.unix_network.operation, r->param.unix_network.address->name); } /** * tomoyo_check_inet_acl - Check permission for inet domain socket operation. * * @r: Pointer to "struct tomoyo_request_info". * @ptr: Pointer to "struct tomoyo_acl_info". * * Returns true if granted, false otherwise. */ static bool tomoyo_check_inet_acl(struct tomoyo_request_info *r, const struct tomoyo_acl_info *ptr) { const struct tomoyo_inet_acl *acl = container_of(ptr, typeof(*acl), head); const u8 size = r->param.inet_network.is_ipv6 ? 16 : 4; if (!(acl->perm & (1 << r->param.inet_network.operation)) || !tomoyo_compare_number_union(r->param.inet_network.port, &acl->port)) return false; if (acl->address.group) return tomoyo_address_matches_group (r->param.inet_network.is_ipv6, r->param.inet_network.address, acl->address.group); return acl->address.is_ipv6 == r->param.inet_network.is_ipv6 && memcmp(&acl->address.ip[0], r->param.inet_network.address, size) <= 0 && memcmp(r->param.inet_network.address, &acl->address.ip[1], size) <= 0; } /** * tomoyo_check_unix_acl - Check permission for unix domain socket operation. * * @r: Pointer to "struct tomoyo_request_info". * @ptr: Pointer to "struct tomoyo_acl_info". * * Returns true if granted, false otherwise. */ static bool tomoyo_check_unix_acl(struct tomoyo_request_info *r, const struct tomoyo_acl_info *ptr) { const struct tomoyo_unix_acl *acl = container_of(ptr, typeof(*acl), head); return (acl->perm & (1 << r->param.unix_network.operation)) && tomoyo_compare_name_union(r->param.unix_network.address, &acl->name); } /** * tomoyo_inet_entry - Check permission for INET network operation. * * @address: Pointer to "struct tomoyo_addr_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_inet_entry(const struct tomoyo_addr_info *address) { const int idx = tomoyo_read_lock(); struct tomoyo_request_info r; int error = 0; const u8 type = tomoyo_inet2mac[address->protocol][address->operation]; if (type && tomoyo_init_request_info(&r, NULL, type) != TOMOYO_CONFIG_DISABLED) { r.param_type = TOMOYO_TYPE_INET_ACL; r.param.inet_network.protocol = address->protocol; r.param.inet_network.operation = address->operation; r.param.inet_network.is_ipv6 = address->inet.is_ipv6; r.param.inet_network.address = address->inet.address; r.param.inet_network.port = ntohs(address->inet.port); do { tomoyo_check_acl(&r, tomoyo_check_inet_acl); error = tomoyo_audit_inet_log(&r); } while (error == TOMOYO_RETRY_REQUEST); } tomoyo_read_unlock(idx); return error; } /** * tomoyo_check_inet_address - Check permission for inet domain socket's operation. * * @addr: Pointer to "struct sockaddr". * @addr_len: Size of @addr. * @port: Port number. * @address: Pointer to "struct tomoyo_addr_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_check_inet_address(const struct sockaddr *addr, const unsigned int addr_len, const u16 port, struct tomoyo_addr_info *address) { struct tomoyo_inet_addr_info *i = &address->inet; switch (addr->sa_family) { case AF_INET6: if (addr_len < SIN6_LEN_RFC2133) goto skip; i->is_ipv6 = true; i->address = (__be32 *) ((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr; i->port = ((struct sockaddr_in6 *) addr)->sin6_port; break; case AF_INET: if (addr_len < sizeof(struct sockaddr_in)) goto skip; i->is_ipv6 = false; i->address = (__be32 *) &((struct sockaddr_in *) addr)->sin_addr; i->port = ((struct sockaddr_in *) addr)->sin_port; break; default: goto skip; } if (address->protocol == SOCK_RAW) i->port = htons(port); return tomoyo_inet_entry(address); skip: return 0; } /** * tomoyo_unix_entry - Check permission for UNIX network operation. * * @address: Pointer to "struct tomoyo_addr_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_unix_entry(const struct tomoyo_addr_info *address) { const int idx = tomoyo_read_lock(); struct tomoyo_request_info r; int error = 0; const u8 type = tomoyo_unix2mac[address->protocol][address->operation]; if (type && tomoyo_init_request_info(&r, NULL, type) != TOMOYO_CONFIG_DISABLED) { char *buf = address->unix0.addr; int len = address->unix0.addr_len - sizeof(sa_family_t); if (len <= 0) { buf = "anonymous"; len = 9; } else if (buf[0]) { len = strnlen(buf, len); } buf = tomoyo_encode2(buf, len); if (buf) { struct tomoyo_path_info addr; addr.name = buf; tomoyo_fill_path_info(&addr); r.param_type = TOMOYO_TYPE_UNIX_ACL; r.param.unix_network.protocol = address->protocol; r.param.unix_network.operation = address->operation; r.param.unix_network.address = &addr; do { tomoyo_check_acl(&r, tomoyo_check_unix_acl); error = tomoyo_audit_unix_log(&r); } while (error == TOMOYO_RETRY_REQUEST); kfree(buf); } else error = -ENOMEM; } tomoyo_read_unlock(idx); return error; } /** * tomoyo_check_unix_address - Check permission for unix domain socket's operation. * * @addr: Pointer to "struct sockaddr". * @addr_len: Size of @addr. * @address: Pointer to "struct tomoyo_addr_info". * * Returns 0 on success, negative value otherwise. */ static int tomoyo_check_unix_address(struct sockaddr *addr, const unsigned int addr_len, struct tomoyo_addr_info *address) { struct tomoyo_unix_addr_info *u = &address->unix0; if (addr->sa_family != AF_UNIX) return 0; u->addr = ((struct sockaddr_un *) addr)->sun_path; u->addr_len = addr_len; return tomoyo_unix_entry(address); } /** * tomoyo_kernel_service - Check whether I'm kernel service or not. * * Returns true if I'm kernel service, false otherwise. */ static bool tomoyo_kernel_service(void) { /* Nothing to do if I am a kernel service. */ return segment_eq(get_fs(), KERNEL_DS); } /** * tomoyo_sock_family - Get socket's family. * * @sk: Pointer to "struct sock". * * Returns one of PF_INET, PF_INET6, PF_UNIX or 0. */ static u8 tomoyo_sock_family(struct sock *sk) { u8 family; if (tomoyo_kernel_service()) return 0; family = sk->sk_family; switch (family) { case PF_INET: case PF_INET6: case PF_UNIX: return family; default: return 0; } } /** * tomoyo_socket_listen_permission - Check permission for listening a socket. * * @sock: Pointer to "struct socket". * * Returns 0 on success, negative value otherwise. */ int tomoyo_socket_listen_permission(struct socket *sock) { struct tomoyo_addr_info address; const u8 family = tomoyo_sock_family(sock->sk); const unsigned int type = sock->type; struct sockaddr_storage addr; int addr_len; if (!family || (type != SOCK_STREAM && type != SOCK_SEQPACKET)) return 0; { const int error = sock->ops->getname(sock, (struct sockaddr *) &addr, &addr_len, 0); if (error) return error; } address.protocol = type; address.operation = TOMOYO_NETWORK_LISTEN; if (family == PF_UNIX) return tomoyo_check_unix_address((struct sockaddr *) &addr, addr_len, &address); return tomoyo_check_inet_address((struct sockaddr *) &addr, addr_len, 0, &address); } /** * tomoyo_socket_connect_permission - Check permission for setting the remote address of a socket. * * @sock: Pointer to "struct socket". * @addr: Pointer to "struct sockaddr". * @addr_len: Size of @addr. * * Returns 0 on success, negative value otherwise. */ int tomoyo_socket_connect_permission(struct socket *sock, struct sockaddr *addr, int addr_len) { struct tomoyo_addr_info address; const u8 family = tomoyo_sock_family(sock->sk); const unsigned int type = sock->type; if (!family) return 0; address.protocol = type; switch (type) { case SOCK_DGRAM: case SOCK_RAW: address.operation = TOMOYO_NETWORK_SEND; break; case SOCK_STREAM: case SOCK_SEQPACKET: address.operation = TOMOYO_NETWORK_CONNECT; break; default: return 0; } if (family == PF_UNIX) return tomoyo_check_unix_address(addr, addr_len, &address); return tomoyo_check_inet_address(addr, addr_len, sock->sk->sk_protocol, &address); } /** * tomoyo_socket_bind_permission - Check permission for setting the local address of a socket. * * @sock: Pointer to "struct socket". * @addr: Pointer to "struct sockaddr". * @addr_len: Size of @addr. * * Returns 0 on success, negative value otherwise. */ int tomoyo_socket_bind_permission(struct socket *sock, struct sockaddr *addr, int addr_len) { struct tomoyo_addr_info address; const u8 family = tomoyo_sock_family(sock->sk); const unsigned int type = sock->type; if (!family) return 0; switch (type) { case SOCK_STREAM: case SOCK_DGRAM: case SOCK_RAW: case SOCK_SEQPACKET: address.protocol = type; address.operation = TOMOYO_NETWORK_BIND; break; default: return 0; } if (family == PF_UNIX) return tomoyo_check_unix_address(addr, addr_len, &address); return tomoyo_check_inet_address(addr, addr_len, sock->sk->sk_protocol, &address); } /** * tomoyo_socket_sendmsg_permission - Check permission for sending a datagram. * * @sock: Pointer to "struct socket". * @msg: Pointer to "struct msghdr". * @size: Unused. * * Returns 0 on success, negative value otherwise. */ int tomoyo_socket_sendmsg_permission(struct socket *sock, struct msghdr *msg, int size) { struct tomoyo_addr_info address; const u8 family = tomoyo_sock_family(sock->sk); const unsigned int type = sock->type; if (!msg->msg_name || !family || (type != SOCK_DGRAM && type != SOCK_RAW)) return 0; address.protocol = type; address.operation = TOMOYO_NETWORK_SEND; if (family == PF_UNIX) return tomoyo_check_unix_address((struct sockaddr *) msg->msg_name, msg->msg_namelen, &address); return tomoyo_check_inet_address((struct sockaddr *) msg->msg_name, msg->msg_namelen, sock->sk->sk_protocol, &address); }
/* SPDX-License-Identifier: GPL-2.0+ */ /* * (C) Copyright 2013-2015 * NVIDIA Corporation <www.nvidia.com> */ #ifndef _MAX77620_INIT_H_ #define _MAX77620_INIT_H_ /* MAX77620-PMIC-specific early init regs */ #define MAX77620_I2C_ADDR 0x78 #define MAX77620_I2C_ADDR_7BIT 0x3C #define MAX77620_CNFGGLBL1_REG 0x00 #define MAX77620_SD0_REG 0x16 #define MAX77620_SD1_REG 0x17 #define MAX77620_SD2_REG 0x18 #define MAX77620_SD3_REG 0x19 #define MAX77620_CNFG2SD_REG 0x22 #define MAX77620_CNFG1_L0_REG 0x23 #define MAX77620_CNFG2_L0_REG 0x24 #define MAX77620_CNFG1_L1_REG 0x25 #define MAX77620_CNFG2_L1_REG 0x26 #define MAX77620_CNFG1_L2_REG 0x27 #define MAX77620_CNFG2_L2_REG 0x28 #define MAX77620_CNFG1_L3_REG 0x29 #define MAX77620_CNFG2_L3_REG 0x2A #define MAX77620_CNFG1_L4_REG 0x2B #define MAX77620_CNFG2_L4_REG 0x2C #define MAX77620_CNFG1_L5_REG 0x2D #define MAX77620_CNFG2_L5_REG 0x2E #define MAX77620_CNFG1_L6_REG 0x2F #define MAX77620_CNFG2_L6_REG 0x30 #define MAX77620_CNFG1_L7_REG 0x31 #define MAX77620_CNFG2_L7_REG 0x32 #define MAX77620_CNFG1_L8_REG 0x33 #define MAX77620_CNFG2_L8_REG 0x34 #define MAX77620_CNFG3_LDO_REG 0x35 #define MAX77620_GPIO0_REG 0x36 #define MAX77620_GPIO1_REG 0x37 #define MAX77620_GPIO2_REG 0x38 #define MAX77620_GPIO3_REG 0x39 #define MAX77620_GPIO4_REG 0x3A #define MAX77620_GPIO5_REG 0x3B #define MAX77620_GPIO6_REG 0x3C #define MAX77620_GPIO7_REG 0x3D #define MAX77620_GPIO_PUE_GPIO 0x3E #define MAX77620_GPIO_PDE_GPIO 0x3F #define MAX77620_AME_GPIO 0x40 #define MAX77620_REG_ONOFF_CFG1 0x41 #define MAX77620_REG_ONOFF_CFG2 0x42 #define MAX77620_CID0_REG 0x58 #define MAX77620_CID1_REG 0x59 #define MAX77620_CID2_REG 0x5A #define MAX77620_CID3_REG 0x5B #define MAX77620_CID4_REG 0x5C #define MAX77620_CID5_REG 0x5D #define I2C_SEND_2_BYTES 0x0A02 void pmic_enable_cpu_vdd(void); #endif /* _MAX77620_INIT_H_ */
/* When a stmt has been parsed, this function is called. */ void finish_stmt (void) { last_expr_type = NULL_TREE; }
// i32 is stored as a full word in the code, and aligned to machine-word boundary // TODO this is very inefficient, improve it! void asm_thumb_mov_reg_i32_aligned(asm_thumb_t *as, uint reg_dest, int i32) { if ((as->base.code_offset & 3) == 0) { asm_thumb_op16(as, ASM_THUMB_OP_NOP); } asm_thumb_op16(as, OP_B_N(2)); mp_asm_base_data(&as->base, 4, i32); asm_thumb_mov_reg_i32_optimised(as, reg_dest, i32); }
/* ====================================================================== Slot Management Routines Find_slot() looks for an existing slot for a given id/attr pair, and returns it if found. If no such slot exists, it returns NIL. Make_slot() looks for an existing slot for a given id/attr pair, returns it if found, and otherwise creates a new slot and returns it. Mark_slot_as_changed() is called by the preference manager whenever the preferences for a slot change. This updates the list of changed_slots and highest_goal_whose_context_changed for use by the decider. ====================================================================== */ slot *find_slot (Symbol *id, Symbol *attr) { slot *s; if (!id) return NIL; for (s=id->id.slots; s!=NIL; s=s->next) if (s->attr==attr) return s; return NIL; }
/* Copyright (C) 2005, 2004 Erik Eliasson, Johan Bilien This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * Authors: Erik Eliasson <eliasson@it.kth.se> * Johan Bilien <jobi@via.ecp.fr> */ #ifndef KEYAGREEMENT_PSK_H #define KEYAGREEMENT_PSK_H #include<libmikey/libmikey_config.h> #include<libmikey/KeyAgreement.h> class LIBMIKEY_API KeyAgreementPSK : public KeyAgreement{ public: KeyAgreementPSK( const byte_t * psk, int pskLength ); virtual ~KeyAgreementPSK(); int32_t type(); /** * Generates a TGK of de given length with the random function from the * OpenSSL library and stores it in this instance */ void generateTgk( uint32_t tgkLength = 192 ); /** * Generates and stores the transport encryption key of the given length. * It is derived by the envelope key */ void genTranspEncrKey( byte_t * encrKey, int encrKeyLength ); /** * Generates and stores the salting key of the given length. * It is also derived by the envelope key */ void genTranspSaltKey( byte_t * saltKey, int saltKeyLength ); /** * Creates and stores the authentication key to authenticate the MAC/signature * of the MIKEY message. */ void genTranspAuthKey( byte_t * authKey, int authKeyLength ); /** * Returns the timestamp on which the message was sent */ uint64_t tSent(); /** * Sets the timestamp */ void setTSent( uint64_t tSent ); /** * Timestamp on which the message was received */ uint64_t t_received; /** * Authentication key */ byte_t * authKey; /** * Length of the authentication key */ unsigned int authKeyLength; /** * If the V bit is set by the initiator, the responder has to send a * verification message. */ void setV(int value) {v=value;} /** * Used to test if the V bit is set. */ int getV() {return v;} /** * MAC algorithmus (HMAC-SHA1) */ int macAlg; virtual MikeyMessage* createMessage(); protected: KeyAgreementPSK(); void setPSK( const byte_t* psk, int pskLength ); byte_t* getPSK(); int getPSKLength(); private: byte_t * pskPtr; int pskLengthValue; /** * The V bit */ int v; /** * Timestamp from when the message was sent */ uint64_t tSentValue; }; #endif
/*****************************************************************************/ /* */ /* finddirection() Find the first triangle on the path from one point */ /* to another. */ /* */ /* Finds the triangle that intersects a line segment drawn from the */ /* origin of `searchtri' to the point `searchpoint', and returns the result */ /* in `searchtri'. The origin of `searchtri' does not change, even though */ /* the triangle returned may differ from the one passed in. This routine */ /* is used to find the direction to move in to get from one point to */ /* another. */ /* */ /* The return value notes whether the destination or apex of the found */ /* triangle is collinear with the two points in question. */ /* */ /*****************************************************************************/ enum finddirectionresult finddirection(struct mesh *m, struct behavior *b, struct otri *searchtri, vertex searchpoint) { struct otri checktri; vertex startvertex; vertex leftvertex, rightvertex; float leftccw, rightccw; int leftflag, rightflag; triangle ptr; org(*searchtri, startvertex); dest(*searchtri, rightvertex); apex(*searchtri, leftvertex); leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex); leftflag = leftccw > 0.0; rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex); rightflag = rightccw > 0.0; if (leftflag && rightflag) { onext(*searchtri, checktri); if (checktri.tri == m->dummytri) { leftflag = 0; } else { rightflag = 0; } } while (leftflag) { onextself(*searchtri); if (searchtri->tri == m->dummytri) { printf("Internal error in finddirection(): Unable to find a\n"); printf(" triangle leading from (%.12g, %.12g) to", startvertex[0], startvertex[1]); printf(" (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]); internalerror(); } apex(*searchtri, leftvertex); rightccw = leftccw; leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex); leftflag = leftccw > 0.0; } while (rightflag) { oprevself(*searchtri); if (searchtri->tri == m->dummytri) { printf("Internal error in finddirection(): Unable to find a\n"); printf(" triangle leading from (%.12g, %.12g) to", startvertex[0], startvertex[1]); printf(" (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]); internalerror(); } dest(*searchtri, rightvertex); leftccw = rightccw; rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex); rightflag = rightccw > 0.0; } if (leftccw == 0.0) { return LEFTCOLLINEAR; } else if (rightccw == 0.0) { return RIGHTCOLLINEAR; } else { return WITHIN; } }
/* Serves the same data over multiple connections. */ static int null_can_multi_conn (void *handle) { return 1; }
//***************************************************************************** // //! Configures the interrupt SOC trigger of an SOC. //! //! \param base is the base address of the ADC module. //! \param socNumber is the number of the start-of-conversion. //! \param trigger the interrupt source that will cause the SOC. //! //! This function configures the interrupt start-of-conversion trigger in //! the ADC module. //! //! The \e socNumber number is a value \b ADC_SOC_NUMBERX where X is a number //! from 0 to 15 specifying which SOC is to be configured on the ADC module //! specified by \e base. //! //! The \e trigger specifies the interrupt that causes a start of conversion or //! none. It should be one of the following values. //! //! - \b ADC_INT_SOC_TRIGGER_NONE //! - \b ADC_INT_SOC_TRIGGER_ADCINT1 //! - \b ADC_INT_SOC_TRIGGER_ADCINT2 //! //! This functionality is useful for creating continuous conversions. //! //! \return None. // //***************************************************************************** static inline void ADC_setInterruptSOCTrigger(uint32_t base, ADC_SOCNumber socNumber, ADC_IntSOCTrigger trigger) { uint16_t shiftVal; Check the arguments. ASSERT(ADC_isBaseValid(base)); Each SOC has a 2-bit field in this register. shiftVal = (uint16_t)socNumber << 1U; Set the configuration of the specified SOC. Not that we're treating ADCINTSOCSEL1 and ADCINTSOCSEL2 as one 32-bit register here. EALLOW; HWREG(base + ADC_O_INTSOCSEL1) = (HWREG(base + ADC_O_INTSOCSEL1) & ~((uint32_t)ADC_INTSOCSEL1_SOC0_M << shiftVal)) | ((uint32_t)trigger << shiftVal); EDIS; }
/** Wipe variables for el thread. */ static void iopy_el_thr_vars_wipe(void) { pthread_cond_destroy(&_G.el_thr_start_cond); pthread_mutex_destroy(&_G.el_mutex); pthread_cond_destroy(&_G.el_mutex_after_lock_cond); pthread_cond_destroy(&_G.el_wait_thr_cond); }
/* * Copyright 2007, Michael Ellerman, IBM Corporation. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/pci.h> #include <linux/msi.h> #include <linux/export.h> #include <linux/of_platform.h> #include <linux/debugfs.h> #include <linux/slab.h> #include <asm/dcr.h> #include <asm/machdep.h> #include <asm/prom.h> /* * MSIC registers, specified as offsets from dcr_base */ #define MSIC_CTRL_REG 0x0 /* Base Address registers specify FIFO location in BE memory */ #define MSIC_BASE_ADDR_HI_REG 0x3 #define MSIC_BASE_ADDR_LO_REG 0x4 /* Hold the read/write offsets into the FIFO */ #define MSIC_READ_OFFSET_REG 0x5 #define MSIC_WRITE_OFFSET_REG 0x6 /* MSIC control register flags */ #define MSIC_CTRL_ENABLE 0x0001 #define MSIC_CTRL_FIFO_FULL_ENABLE 0x0002 #define MSIC_CTRL_IRQ_ENABLE 0x0008 #define MSIC_CTRL_FULL_STOP_ENABLE 0x0010 /* * The MSIC can be configured to use a FIFO of 32KB, 64KB, 128KB or 256KB. * Currently we're using a 64KB FIFO size. */ #define MSIC_FIFO_SIZE_SHIFT 16 #define MSIC_FIFO_SIZE_BYTES (1 << MSIC_FIFO_SIZE_SHIFT) /* * To configure the FIFO size as (1 << n) bytes, we write (n - 15) into bits * 8-9 of the MSIC control reg. */ #define MSIC_CTRL_FIFO_SIZE (((MSIC_FIFO_SIZE_SHIFT - 15) << 8) & 0x300) /* * We need to mask the read/write offsets to make sure they stay within * the bounds of the FIFO. Also they should always be 16-byte aligned. */ #define MSIC_FIFO_SIZE_MASK ((MSIC_FIFO_SIZE_BYTES - 1) & ~0xFu) /* Each entry in the FIFO is 16 bytes, the first 4 bytes hold the irq # */ #define MSIC_FIFO_ENTRY_SIZE 0x10 struct axon_msic { struct irq_domain *irq_domain; __le32 *fifo_virt; dma_addr_t fifo_phys; dcr_host_t dcr_host; u32 read_offset; #ifdef DEBUG u32 __iomem *trigger; #endif }; #ifdef DEBUG void axon_msi_debug_setup(struct device_node *dn, struct axon_msic *msic); #else static inline void axon_msi_debug_setup(struct device_node *dn, struct axon_msic *msic) { } #endif static void msic_dcr_write(struct axon_msic *msic, unsigned int dcr_n, u32 val) { pr_devel("axon_msi: dcr_write(0x%x, 0x%x)\n", val, dcr_n); dcr_write(msic->dcr_host, dcr_n, val); } static void axon_msi_cascade(unsigned int irq, struct irq_desc *desc) { struct irq_chip *chip = irq_desc_get_chip(desc); struct axon_msic *msic = irq_get_handler_data(irq); u32 write_offset, msi; int idx; int retry = 0; write_offset = dcr_read(msic->dcr_host, MSIC_WRITE_OFFSET_REG); pr_devel("axon_msi: original write_offset 0x%x\n", write_offset); /* write_offset doesn't wrap properly, so we have to mask it */ write_offset &= MSIC_FIFO_SIZE_MASK; while (msic->read_offset != write_offset && retry < 100) { idx = msic->read_offset / sizeof(__le32); msi = le32_to_cpu(msic->fifo_virt[idx]); msi &= 0xFFFF; pr_devel("axon_msi: woff %x roff %x msi %x\n", write_offset, msic->read_offset, msi); if (msi < nr_irqs && irq_get_chip_data(msi) == msic) { generic_handle_irq(msi); msic->fifo_virt[idx] = cpu_to_le32(0xffffffff); } else { /* * Reading the MSIC_WRITE_OFFSET_REG does not * reliably flush the outstanding DMA to the * FIFO buffer. Here we were reading stale * data, so we need to retry. */ udelay(1); retry++; pr_devel("axon_msi: invalid irq 0x%x!\n", msi); continue; } if (retry) { pr_devel("axon_msi: late irq 0x%x, retry %d\n", msi, retry); retry = 0; } msic->read_offset += MSIC_FIFO_ENTRY_SIZE; msic->read_offset &= MSIC_FIFO_SIZE_MASK; } if (retry) { printk(KERN_WARNING "axon_msi: irq timed out\n"); msic->read_offset += MSIC_FIFO_ENTRY_SIZE; msic->read_offset &= MSIC_FIFO_SIZE_MASK; } chip->irq_eoi(&desc->irq_data); } static struct axon_msic *find_msi_translator(struct pci_dev *dev) { struct irq_domain *irq_domain; struct device_node *dn, *tmp; const phandle *ph; struct axon_msic *msic = NULL; dn = of_node_get(pci_device_to_OF_node(dev)); if (!dn) { dev_dbg(&dev->dev, "axon_msi: no pci_dn found\n"); return NULL; } for (; dn; dn = of_get_next_parent(dn)) { ph = of_get_property(dn, "msi-translator", NULL); if (ph) break; } if (!ph) { dev_dbg(&dev->dev, "axon_msi: no msi-translator property found\n"); goto out_error; } tmp = dn; dn = of_find_node_by_phandle(*ph); of_node_put(tmp); if (!dn) { dev_dbg(&dev->dev, "axon_msi: msi-translator doesn't point to a node\n"); goto out_error; } irq_domain = irq_find_host(dn); if (!irq_domain) { dev_dbg(&dev->dev, "axon_msi: no irq_domain found for node %s\n", dn->full_name); goto out_error; } msic = irq_domain->host_data; out_error: of_node_put(dn); return msic; } static int axon_msi_check_device(struct pci_dev *dev, int nvec, int type) { if (!find_msi_translator(dev)) return -ENODEV; return 0; } static int setup_msi_msg_address(struct pci_dev *dev, struct msi_msg *msg) { struct device_node *dn; struct msi_desc *entry; int len; const u32 *prop; dn = of_node_get(pci_device_to_OF_node(dev)); if (!dn) { dev_dbg(&dev->dev, "axon_msi: no pci_dn found\n"); return -ENODEV; } entry = list_first_entry(&dev->msi_list, struct msi_desc, list); for (; dn; dn = of_get_next_parent(dn)) { if (entry->msi_attrib.is_64) { prop = of_get_property(dn, "msi-address-64", &len); if (prop) break; } prop = of_get_property(dn, "msi-address-32", &len); if (prop) break; } if (!prop) { dev_dbg(&dev->dev, "axon_msi: no msi-address-(32|64) properties found\n"); return -ENOENT; } switch (len) { case 8: msg->address_hi = prop[0]; msg->address_lo = prop[1]; break; case 4: msg->address_hi = 0; msg->address_lo = prop[0]; break; default: dev_dbg(&dev->dev, "axon_msi: malformed msi-address-(32|64) property\n"); of_node_put(dn); return -EINVAL; } of_node_put(dn); return 0; } static int axon_msi_setup_msi_irqs(struct pci_dev *dev, int nvec, int type) { unsigned int virq, rc; struct msi_desc *entry; struct msi_msg msg; struct axon_msic *msic; msic = find_msi_translator(dev); if (!msic) return -ENODEV; rc = setup_msi_msg_address(dev, &msg); if (rc) return rc; list_for_each_entry(entry, &dev->msi_list, list) { virq = irq_create_direct_mapping(msic->irq_domain); if (virq == NO_IRQ) { dev_warn(&dev->dev, "axon_msi: virq allocation failed!\n"); return -1; } dev_dbg(&dev->dev, "axon_msi: allocated virq 0x%x\n", virq); irq_set_msi_desc(virq, entry); msg.data = virq; write_msi_msg(virq, &msg); } return 0; } static void axon_msi_teardown_msi_irqs(struct pci_dev *dev) { struct msi_desc *entry; dev_dbg(&dev->dev, "axon_msi: tearing down msi irqs\n"); list_for_each_entry(entry, &dev->msi_list, list) { if (entry->irq == NO_IRQ) continue; irq_set_msi_desc(entry->irq, NULL); irq_dispose_mapping(entry->irq); } } static struct irq_chip msic_irq_chip = { .irq_mask = mask_msi_irq, .irq_unmask = unmask_msi_irq, .irq_shutdown = mask_msi_irq, .name = "AXON-MSI", }; static int msic_host_map(struct irq_domain *h, unsigned int virq, irq_hw_number_t hw) { irq_set_chip_data(virq, h->host_data); irq_set_chip_and_handler(virq, &msic_irq_chip, handle_simple_irq); return 0; } static const struct irq_domain_ops msic_host_ops = { .map = msic_host_map, }; static void axon_msi_shutdown(struct platform_device *device) { struct axon_msic *msic = dev_get_drvdata(&device->dev); u32 tmp; pr_devel("axon_msi: disabling %s\n", msic->irq_domain->of_node->full_name); tmp = dcr_read(msic->dcr_host, MSIC_CTRL_REG); tmp &= ~MSIC_CTRL_ENABLE & ~MSIC_CTRL_IRQ_ENABLE; msic_dcr_write(msic, MSIC_CTRL_REG, tmp); } static int axon_msi_probe(struct platform_device *device) { struct device_node *dn = device->dev.of_node; struct axon_msic *msic; unsigned int virq; int dcr_base, dcr_len; pr_devel("axon_msi: setting up dn %s\n", dn->full_name); msic = kzalloc(sizeof(struct axon_msic), GFP_KERNEL); if (!msic) { printk(KERN_ERR "axon_msi: couldn't allocate msic for %s\n", dn->full_name); goto out; } dcr_base = dcr_resource_start(dn, 0); dcr_len = dcr_resource_len(dn, 0); if (dcr_base == 0 || dcr_len == 0) { printk(KERN_ERR "axon_msi: couldn't parse dcr properties on %s\n", dn->full_name); goto out_free_msic; } msic->dcr_host = dcr_map(dn, dcr_base, dcr_len); if (!DCR_MAP_OK(msic->dcr_host)) { printk(KERN_ERR "axon_msi: dcr_map failed for %s\n", dn->full_name); goto out_free_msic; } msic->fifo_virt = dma_alloc_coherent(&device->dev, MSIC_FIFO_SIZE_BYTES, &msic->fifo_phys, GFP_KERNEL); if (!msic->fifo_virt) { printk(KERN_ERR "axon_msi: couldn't allocate fifo for %s\n", dn->full_name); goto out_free_msic; } virq = irq_of_parse_and_map(dn, 0); if (virq == NO_IRQ) { printk(KERN_ERR "axon_msi: irq parse and map failed for %s\n", dn->full_name); goto out_free_fifo; } memset(msic->fifo_virt, 0xff, MSIC_FIFO_SIZE_BYTES); /* We rely on being able to stash a virq in a u16, so limit irqs to < 65536 */ msic->irq_domain = irq_domain_add_nomap(dn, 65536, &msic_host_ops, msic); if (!msic->irq_domain) { printk(KERN_ERR "axon_msi: couldn't allocate irq_domain for %s\n", dn->full_name); goto out_free_fifo; } irq_set_handler_data(virq, msic); irq_set_chained_handler(virq, axon_msi_cascade); pr_devel("axon_msi: irq 0x%x setup for axon_msi\n", virq); /* Enable the MSIC hardware */ msic_dcr_write(msic, MSIC_BASE_ADDR_HI_REG, msic->fifo_phys >> 32); msic_dcr_write(msic, MSIC_BASE_ADDR_LO_REG, msic->fifo_phys & 0xFFFFFFFF); msic_dcr_write(msic, MSIC_CTRL_REG, MSIC_CTRL_IRQ_ENABLE | MSIC_CTRL_ENABLE | MSIC_CTRL_FIFO_SIZE); msic->read_offset = dcr_read(msic->dcr_host, MSIC_WRITE_OFFSET_REG) & MSIC_FIFO_SIZE_MASK; dev_set_drvdata(&device->dev, msic); ppc_md.setup_msi_irqs = axon_msi_setup_msi_irqs; ppc_md.teardown_msi_irqs = axon_msi_teardown_msi_irqs; ppc_md.msi_check_device = axon_msi_check_device; axon_msi_debug_setup(dn, msic); printk(KERN_DEBUG "axon_msi: setup MSIC on %s\n", dn->full_name); return 0; out_free_fifo: dma_free_coherent(&device->dev, MSIC_FIFO_SIZE_BYTES, msic->fifo_virt, msic->fifo_phys); out_free_msic: kfree(msic); out: return -1; } static const struct of_device_id axon_msi_device_id[] = { { .compatible = "ibm,axon-msic" }, {} }; static struct platform_driver axon_msi_driver = { .probe = axon_msi_probe, .shutdown = axon_msi_shutdown, .driver = { .name = "axon-msi", .owner = THIS_MODULE, .of_match_table = axon_msi_device_id, }, }; static int __init axon_msi_init(void) { return platform_driver_register(&axon_msi_driver); } subsys_initcall(axon_msi_init); #ifdef DEBUG static int msic_set(void *data, u64 val) { struct axon_msic *msic = data; out_le32(msic->trigger, val); return 0; } static int msic_get(void *data, u64 *val) { *val = 0; return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_msic, msic_get, msic_set, "%llu\n"); void axon_msi_debug_setup(struct device_node *dn, struct axon_msic *msic) { char name[8]; u64 addr; addr = of_translate_address(dn, of_get_property(dn, "reg", NULL)); if (addr == OF_BAD_ADDR) { pr_devel("axon_msi: couldn't translate reg property\n"); return; } msic->trigger = ioremap(addr, 0x4); if (!msic->trigger) { pr_devel("axon_msi: ioremap failed\n"); return; } snprintf(name, sizeof(name), "msic_%d", of_node_to_nid(dn)); if (!debugfs_create_file(name, 0600, powerpc_debugfs_root, msic, &fops_msic)) { pr_devel("axon_msi: debugfs_create_file failed!\n"); return; } } #endif /* DEBUG */
/// \brief Splits up the component. /// /// Splitting the component into singleton components (component /// of size one). void split(int cls) { int fdx = classes[cls].firstItem; int idx = items[fdx].next; while (idx != fdx) { int next = items[idx].next; singletonItem(idx); int cdx = newClass(); items[idx].parent = ~cdx; laceClass(cdx); classes[cdx].size = 1; classes[cdx].firstItem = idx; idx = next; } items[idx].prev = idx; items[idx].next = idx; classes[~(items[idx].parent)].size = 1; }
//=- HexagonFrameLowering.h - Define frame lowering for Hexagon --*- C++ -*--=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_HEXAGON_HEXAGONFRAMELOWERING_H #define LLVM_LIB_TARGET_HEXAGON_HEXAGONFRAMELOWERING_H #include "Hexagon.h" #include "HexagonBlockRanges.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/Target/TargetFrameLowering.h" #include <vector> namespace llvm { class HexagonInstrInfo; class HexagonRegisterInfo; class HexagonFrameLowering : public TargetFrameLowering { public: explicit HexagonFrameLowering() : TargetFrameLowering(StackGrowsDown, 8, 0, 1, true) {} // All of the prolog/epilog functionality, including saving and restoring // callee-saved registers is handled in emitPrologue. This is to have the // logic for shrink-wrapping in one place. void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override; void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override {} bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const std::vector<CalleeSavedInfo> &CSI, const TargetRegisterInfo *TRI) const override { return true; } bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const std::vector<CalleeSavedInfo> &CSI, const TargetRegisterInfo *TRI) const override { return true; } MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const override; void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS = nullptr) const override; void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS) const override; bool targetHandlesStackFrameRounding() const override { return true; } int getFrameIndexReference(const MachineFunction &MF, int FI, unsigned &FrameReg) const override; bool hasFP(const MachineFunction &MF) const override; const SpillSlot *getCalleeSavedSpillSlots(unsigned &NumEntries) const override { static const SpillSlot Offsets[] = { { Hexagon::R17, -4 }, { Hexagon::R16, -8 }, { Hexagon::D8, -8 }, { Hexagon::R19, -12 }, { Hexagon::R18, -16 }, { Hexagon::D9, -16 }, { Hexagon::R21, -20 }, { Hexagon::R20, -24 }, { Hexagon::D10, -24 }, { Hexagon::R23, -28 }, { Hexagon::R22, -32 }, { Hexagon::D11, -32 }, { Hexagon::R25, -36 }, { Hexagon::R24, -40 }, { Hexagon::D12, -40 }, { Hexagon::R27, -44 }, { Hexagon::R26, -48 }, { Hexagon::D13, -48 } }; NumEntries = array_lengthof(Offsets); return Offsets; } bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector<CalleeSavedInfo> &CSI) const override; bool needsAligna(const MachineFunction &MF) const; const MachineInstr *getAlignaInstr(const MachineFunction &MF) const; void insertCFIInstructions(MachineFunction &MF) const; private: typedef std::vector<CalleeSavedInfo> CSIVect; void expandAlloca(MachineInstr *AI, const HexagonInstrInfo &TII, unsigned SP, unsigned CF) const; void insertPrologueInBlock(MachineBasicBlock &MBB, bool PrologueStubs) const; void insertEpilogueInBlock(MachineBasicBlock &MBB) const; bool insertCSRSpillsInBlock(MachineBasicBlock &MBB, const CSIVect &CSI, const HexagonRegisterInfo &HRI, bool &PrologueStubs) const; bool insertCSRRestoresInBlock(MachineBasicBlock &MBB, const CSIVect &CSI, const HexagonRegisterInfo &HRI) const; void updateEntryPaths(MachineFunction &MF, MachineBasicBlock &SaveB) const; bool updateExitPaths(MachineBasicBlock &MBB, MachineBasicBlock &RestoreB, BitVector &DoneT, BitVector &DoneF, BitVector &Path) const; void insertCFIInstructionsAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator At) const; void adjustForCalleeSavedRegsSpillCall(MachineFunction &MF) const; bool expandCopy(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandStoreInt(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandLoadInt(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandStoreVecPred(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandLoadVecPred(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandStoreVec2(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandLoadVec2(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandStoreVec(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandLoadVec(MachineBasicBlock &B, MachineBasicBlock::iterator It, MachineRegisterInfo &MRI, const HexagonInstrInfo &HII, SmallVectorImpl<unsigned> &NewRegs) const; bool expandSpillMacros(MachineFunction &MF, SmallVectorImpl<unsigned> &NewRegs) const; unsigned findPhysReg(MachineFunction &MF, HexagonBlockRanges::IndexRange &FIR, HexagonBlockRanges::InstrIndexMap &IndexMap, HexagonBlockRanges::RegToRangeMap &DeadMap, const TargetRegisterClass *RC) const; void optimizeSpillSlots(MachineFunction &MF, SmallVectorImpl<unsigned> &VRegs) const; void findShrunkPrologEpilog(MachineFunction &MF, MachineBasicBlock *&PrologB, MachineBasicBlock *&EpilogB) const; void addCalleeSaveRegistersAsImpOperand(MachineInstr *MI, const CSIVect &CSI, bool IsDef, bool IsKill) const; bool shouldInlineCSR(MachineFunction &MF, const CSIVect &CSI) const; bool useSpillFunction(MachineFunction &MF, const CSIVect &CSI) const; bool useRestoreFunction(MachineFunction &MF, const CSIVect &CSI) const; bool mayOverflowFrameOffset(MachineFunction &MF) const; }; } // end namespace llvm #endif // LLVM_LIB_TARGET_HEXAGON_HEXAGONFRAMELOWERING_H
/* * Early init is called at the very beginning and is meant for modules which * absolutely need to start as soon as possible. hardware_early_init() blocks * which means code in here should be fast. */ int hardware_early_init(void) { watchdog_init(); I2C_Shutdown(MXC_I2C1_BUS0); I2C_Init(MXC_I2C1_BUS0, I2C_FAST_MODE, NULL); #ifndef CARD10_DEBUG_CORE1 I2C_Shutdown(MXC_I2C0_BUS0); I2C_Init(MXC_I2C0_BUS0, I2C_FAST_MODE, NULL); #endif GPIO_Init(); const gpio_cfg_t pwr_hold_pin = { PORT_0, PIN_30, GPIO_FUNC_OUT, GPIO_PAD_NONE }; GPIO_Config(&pwr_hold_pin); GPIO_OutSet(&pwr_hold_pin); pmic_init(); pmic_set_led(0, 0); pmic_set_led(1, 0); pmic_set_led(2, 0); portexpander_init(); TRNG_Init(NULL); PB_Init(); while (RTC_SquareWave( MXC_RTC, SQUARE_WAVE_ENABLED, F_32KHZ, NOISE_IMMUNE_MODE, NULL) == E_BUSY ) ; if (RTC_GetSecond() < 1546300800UL) { epic_rtc_set_milliseconds(1546300800UL * 1000); } const sys_cfg_spi_t spi17y_master_cfg = { .map = MAP_A, .ss0 = Enable, .ss1 = Disable, .ss2 = Disable, }; if (SPI_Init(SPI0, 0, SPI_SPEED, spi17y_master_cfg) != 0) { LOG_ERR("init", "Error configuring SPI"); while (1) ; } display_init_slim(); leds_init(); #ifdef CARD10_DEBUG_CORE1 LOG_WARN("init", "Core 1 Debugger Mode"); static const gpio_cfg_t swclk = { PORT_0, PIN_7, GPIO_FUNC_ALT3, GPIO_PAD_NONE, }; static const gpio_cfg_t swdio = { PORT_0, PIN_6, GPIO_FUNC_ALT3, GPIO_PAD_NONE, }; GPIO_Config(&swclk); GPIO_Config(&swdio); #endif SCB->SCR |= SCB_SCR_SEVONPEND_Msk; if (epic_usb_cdcacm() < 0) { LOG_ERR("startup", "USB-Serial unavailable"); } fatfs_init(); api_interrupt_init(); api_dispatcher_init(); stream_init(); hwlock_init(); dispatcher_mutex_init(); max30001_mutex_init(); SCB->CCR |= SCB_CCR_USERSETMPEND_Msk; return 0; }
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (c) 2019 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or modify it under the * terms of the version 2.1 (or later) of the GNU Lesser General Public License * as published by the Free Software Foundation; or version 2.0 of the Apache * License as published by the Apache Software Foundation. See the LICENSE files * for more details. * * RELIC is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the LICENSE files for more details. * * You should have received a copy of the GNU Lesser General Public or the * Apache License along with RELIC. If not, see <https://www.gnu.org/licenses/> * or <https://www.apache.org/licenses/>. */ /** * @file * * Implementation of the low-level inversion functions. * * @&version $Id$ * @ingroup fp */ #include <gmp.h> #include "relic_fp.h" #include "relic_fp_low.h" #include "relic_core.h" /*============================================================================*/ /* Public definitions */ /*============================================================================*/ void fp_invm_low(dig_t *c, const dig_t *a) { mp_size_t cn; rlc_align dig_t s[RLC_FP_DIGS], t[2 * RLC_FP_DIGS], u[RLC_FP_DIGS + 1]; #if FP_RDC == MONTY dv_zero(t + RLC_FP_DIGS, RLC_FP_DIGS); dv_copy(t, a, RLC_FP_DIGS); fp_rdcn_low(u, t); #else fp_copy(u, a); #endif dv_copy(s, fp_prime_get(), RLC_FP_DIGS); mpn_gcdext(t, c, &cn, u, RLC_FP_DIGS, s, RLC_FP_DIGS); if (cn < 0) { dv_zero(c - cn, RLC_FP_DIGS + cn); mpn_sub_n(c, fp_prime_get(), c, RLC_FP_DIGS); } else { dv_zero(c + cn, RLC_FP_DIGS - cn); } #if FP_RDC == MONTY dv_zero(t, RLC_FP_DIGS); dv_copy(t + RLC_FP_DIGS, c, RLC_FP_DIGS); mpn_tdiv_qr(u, c, 0, t, 2 * RLC_FP_DIGS, fp_prime_get(), RLC_FP_DIGS); #endif }
/** * Readback and save the Configuration FLash area. * This would be used to compare what was written, or save current device design before erasing. * @param pXO2dev reference to the XO2 device to access and program */ int XO2ECA_apiReadBackCfg(XO2Handle_t *pXO2dev, unsigned char *pBuf) { return(NOT_IMPLEMENTED_ERR); }
// // Copyright 2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // SystemInfo.h: gathers information available without starting a GPU driver. #ifndef GPU_INFO_UTIL_SYSTEM_INFO_H_ #define GPU_INFO_UTIL_SYSTEM_INFO_H_ #include <cstdint> #include <optional> #include <string> #include <vector> namespace angle { using VendorID = uint32_t; using DeviceID = uint32_t; using RevisionID = uint32_t; using SystemDeviceID = uint64_t; using DriverID = uint32_t; struct VersionInfo { uint32_t major = 0; uint32_t minor = 0; uint32_t subMinor = 0; uint32_t patch = 0; }; struct GPUDeviceInfo { GPUDeviceInfo(); ~GPUDeviceInfo(); GPUDeviceInfo(const GPUDeviceInfo &other); VendorID vendorId = 0; DeviceID deviceId = 0; RevisionID revisionId = 0; SystemDeviceID systemDeviceId = 0; std::string driverVendor; std::string driverVersion; std::string driverDate; // Fields only available via GetSystemInfoVulkan: VersionInfo detailedDriverVersion; DriverID driverId = 0; uint32_t driverApiVersion = 0; }; struct SystemInfo { SystemInfo(); ~SystemInfo(); SystemInfo(const SystemInfo &other); bool hasNVIDIAGPU() const; bool hasIntelGPU() const; bool hasAMDGPU() const; // Returns the index to `gpus` if the entry matches the preferred device string. std::optional<size_t> getPreferredGPUIndex() const; std::vector<GPUDeviceInfo> gpus; // Index of the GPU expected to be used for 3D graphics. Based on a best-guess heuristic on // some platforms. On Windows, this is accurate. Note `gpus` must be checked for empty before // indexing. int activeGPUIndex = 0; bool isOptimus = false; bool isAMDSwitchable = false; // Only true on dual-GPU Mac laptops. bool isMacSwitchable = false; // Only available on Android std::string machineManufacturer; int androidSdkLevel = 0; // Only available on macOS and Android std::string machineModelName; // Only available on macOS std::string machineModelVersion; }; // Gathers information about the system without starting a GPU driver and returns them in `info`. // Returns true if all info was gathered, false otherwise. Even when false is returned, `info` will // be filled with partial information. bool GetSystemInfo(SystemInfo *info); // Vulkan-specific info collection. bool GetSystemInfoVulkan(SystemInfo *info); // Known PCI vendor IDs constexpr VendorID kVendorID_AMD = 0x1002; constexpr VendorID kVendorID_ARM = 0x13B5; constexpr VendorID kVendorID_Broadcom = 0x14E4; constexpr VendorID kVendorID_GOOGLE = 0x1AE0; constexpr VendorID kVendorID_ImgTec = 0x1010; constexpr VendorID kVendorID_Intel = 0x8086; constexpr VendorID kVendorID_NVIDIA = 0x10DE; constexpr VendorID kVendorID_Qualcomm = 0x5143; constexpr VendorID kVendorID_Samsung = 0x144D; constexpr VendorID kVendorID_VMWare = 0x15ad; constexpr VendorID kVendorID_Apple = 0x106B; constexpr VendorID kVendorID_Microsoft = 0x1414; constexpr VendorID kVendorID_VirtIO = 0x1AF4; // Known non-PCI (i.e. Khronos-registered) vendor IDs constexpr VendorID kVendorID_Vivante = 0x10001; constexpr VendorID kVendorID_VeriSilicon = 0x10002; constexpr VendorID kVendorID_Kazan = 0x10003; constexpr VendorID kVendorID_CodePlay = 0x10004; constexpr VendorID kVendorID_Mesa = 0x10005; constexpr VendorID kVendorID_PoCL = 0x10006; // Known device IDs constexpr DeviceID kDeviceID_Swiftshader = 0xC0DE; constexpr DeviceID kDeviceID_Adreno540 = 0x5040001; constexpr DeviceID kDeviceID_UHD630Mobile = 0x3E9B; // Predicates on vendor IDs bool IsAMD(VendorID vendorId); bool IsARM(VendorID vendorId); bool IsBroadcom(VendorID vendorId); bool IsImgTec(VendorID vendorId); bool IsIntel(VendorID vendorId); bool IsKazan(VendorID vendorId); bool IsNVIDIA(VendorID vendorId); bool IsQualcomm(VendorID vendorId); bool IsSamsung(VendorID vendorId); bool IsGoogle(VendorID vendorId); bool IsSwiftshader(VendorID vendorId); bool IsVeriSilicon(VendorID vendorId); bool IsVMWare(VendorID vendorId); bool IsVirtIO(VendorID vendorId); bool IsVivante(VendorID vendorId); bool IsAppleGPU(VendorID vendorId); bool IsMicrosoft(VendorID vendorId); // Returns a readable vendor name given the VendorID std::string VendorName(VendorID vendor); // Use a heuristic to attempt to find the GPU used for 3D graphics. Sets activeGPUIndex, // isOptimus, and isAMDSwitchable. // Always assumes the non-Intel GPU is active on dual-GPU machines. void GetDualGPUInfo(SystemInfo *info); // Dumps the system info to stdout. void PrintSystemInfo(const SystemInfo &info); VersionInfo ParseNvidiaDriverVersion(uint32_t version); VersionInfo ParseMesaDriverVersion(uint32_t version); uint64_t GetSystemDeviceIdFromParts(uint32_t highPart, uint32_t lowPart); uint32_t GetSystemDeviceIdHighPart(uint64_t systemDeviceId); uint32_t GetSystemDeviceIdLowPart(uint64_t systemDeviceId); // Returns lower-case of ANGLE_PREFERRED_DEVICE environment variable contents. std::string GetPreferredDeviceString(); } // namespace angle #endif // GPU_INFO_UTIL_SYSTEM_INFO_H_
/* Return nonzero if C is either a digit or a lowercase alphabet character. */ static int is_lower_alphanum (const char c) { return (isdigit (c) || (isalpha (c) && islower (c))); }
/* * when btree blocks are allocated, they have some corresponding bits set for * them in one of two extent_io trees. This is used to make sure all of * those extents are on disk for transaction or log commit */ static int btrfs_write_and_wait_marked_extents(struct btrfs_root *root, struct extent_io_tree *dirty_pages, int mark) { int ret; int ret2; struct blk_plug plug; blk_start_plug(&plug); ret = btrfs_write_marked_extents(root, dirty_pages, mark); blk_finish_plug(&plug); ret2 = btrfs_wait_marked_extents(root, dirty_pages, mark); if (ret) return ret; if (ret2) return ret2; return 0; }
/****************************************************************************** * Top contributors (to current version): * Andrew Reynolds, Morgan Deters, Andres Noetzli * * This file is part of the cvc5 project. * * Copyright (c) 2009-2023 by the authors listed in the file AUTHORS * in the top-level source directory and their institutional affiliations. * All rights reserved. See the file COPYING in the top-level source * directory for licensing information. * **************************************************************************** * * The module for storing assertions for an SMT engine. */ #include "cvc5_private.h" #ifndef CVC5__SMT__ASSERTIONS_H #define CVC5__SMT__ASSERTIONS_H #include <vector> #include "context/cdlist.h" #include "context/cdo.h" #include "expr/node.h" #include "smt/env_obj.h" namespace cvc5::internal { namespace smt { class AbstractValues; class PreprocessProofGenerator; /** * Contains all information pertaining to the assertions of an SMT engine. * * This class is responsible for setting up the assertions pipeline for * check-sat calls. It is *not* responsible for the preprocessing itself, and * instead is intended to be the input to a preprocessor utility. */ class Assertions : protected EnvObj { /** The type of our internal assertion list */ typedef context::CDList<Node> AssertionList; public: Assertions(Env& env); ~Assertions(); /** refresh * * Ensures that all global declarations have been processed in the current * context. This may trigger substitutions to be added to the top-level * substitution and/or formulas added to the current set of assertions. * * If global declarations are true, this method must be called before * processing assertions. */ void refresh(); /* * Initialize a call to check satisfiability. This adds assumptions to * the list of assumptions maintained by this class, and finalizes the * set of formulas (in the assertions pipeline) that will be used for the * upcoming check-sat call. * * @param assumptions The assumptions of the upcoming check-sat call. */ void setAssumptions(const std::vector<Node>& assumptions); /** * Add a formula to the current context: preprocess, do per-theory * setup, use processAssertionList(), asserting to T-solver for * literals and conjunction of literals. Returns false if * immediately determined to be inconsistent. * * @throw TypeCheckingException, LogicException */ void assertFormula(const Node& n); /** * Assert that n corresponds to an assertion from a define-fun or * define-fun-rec command. * This assertion is added to the set of assertions maintained by this class. * If this has a global definition, this assertion is persistent for any * subsequent check-sat calls. */ void addDefineFunDefinition(Node n, bool global); /** * Get assertions list corresponding to the original list of assertions, * before preprocessing. This includes assertions corresponding to define-fun * and define-fun-rec. */ const context::CDList<Node>& getAssertionList() const; /** * Get assertions list corresponding to the original list of assertions * that correspond to definitions (define-fun or define-fun-rec). */ const context::CDList<Node>& getAssertionListDefinitions() const; /** Get the set corresponding to the above */ std::unordered_set<Node> getCurrentAssertionListDefitions() const; /** * Get the list of assumptions, which are those registered to this class * on initializeCheckSat. */ std::vector<Node>& getAssumptions(); private: /** * Fully type-check the argument, and also type-check that it's * actually Boolean. * throw@ TypeCheckingException */ void ensureBoolean(const Node& n); /** * Adds a formula to the current context. Action here depends on * the SimplificationMode (in the current Options scope); the * formula might be pushed out to the propositional layer * immediately, or it might be simplified and kept, or it might not * even be simplified. * The arguments isInput and isAssumption are used for bookkeeping for unsat * cores. * The argument maybeHasFv should be set to true if the assertion may have * free variables. By construction, assertions from the smt2 parser are * guaranteed not to have free variables. However, other cases such as * assertions from the SyGuS parser may have free variables (say if the * input contains an assert or define-fun-rec command). */ void addFormula(TNode n, bool isFunDef, bool maybeHasFv); /** * The assertion list (before any conversion) for supporting getAssertions(). */ AssertionList d_assertionList; /** The subset of above the correspond to define-fun or define-fun-rec */ AssertionList d_assertionListDefs; /** * List of lemmas generated for global (recursive) function definitions. We * assert this list of definitions in each check-sat call. */ std::vector<Node> d_globalDefineFunLemmas; /** The index of the above list that we have processed */ context::CDO<size_t> d_globalDefineFunLemmasIndex; /** * The list of assumptions from the previous call to checkSatisfiability. */ std::vector<Node> d_assumptions; }; } // namespace smt } // namespace cvc5::internal #endif
/* ---------------------------------------------------------------------[<]- Function: bits_destroy Synopsis: Releases all memory used by a bitstring and deletes the bitstring. Do not refer to the bitstring after calling this function. ---------------------------------------------------------------------[>]-*/ void bits_destroy ( BITS *bits) { int block_nbr; ASSERT (bits); for (block_nbr = 0; block_nbr < bits-> block_count; block_nbr++) mem_free (bits-> block [block_nbr]); mem_free (bits); }
//--------------------------------------------------------------------------- // InitPieVectTable: //--------------------------------------------------------------------------- // This function initializes the PIE vector table to a known state. // This function must be executed after boot time. void InitPieVectTable(void) { Uint16 i; Uint32 *Source = (void *) &PieVectTableInit; Uint32 *Dest = (void *) &PieVectTable; Source = Source + 3; Dest = Dest + 3; EALLOW; for(i = 0; i < 221; i++) { *Dest++ = *Source++; } EDIS; PieCtrlRegs.PIECTRL.bit.ENPIE = 1; }
/* * cardbus.c -- 16-bit PCMCIA core support * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * The initial developer of the original code is David A. Hinds * <dahinds@users.sourceforge.net>. Portions created by David A. Hinds * are Copyright (C) 1999 David A. Hinds. All Rights Reserved. * * (C) 1999 David A. Hinds */ /* * Cardbus handling has been re-written to be more of a PCI bridge thing, * and the PCI code basically does all the resource handling. * * Linus, Jan 2000 */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/pci.h> #include <linux/ioport.h> #include <asm/irq.h> #include <asm/io.h> #define IN_CARD_SERVICES #include <pcmcia/cs_types.h> #include <pcmcia/ss.h> #include <pcmcia/cs.h> #include <pcmcia/bulkmem.h> #include <pcmcia/cistpl.h> #include "cs_internal.h" /*====================================================================*/ /* Offsets in the Expansion ROM Image Header */ #define ROM_SIGNATURE 0x0000 /* 2 bytes */ #define ROM_DATA_PTR 0x0018 /* 2 bytes */ /* Offsets in the CardBus PC Card Data Structure */ #define PCDATA_SIGNATURE 0x0000 /* 4 bytes */ #define PCDATA_VPD_PTR 0x0008 /* 2 bytes */ #define PCDATA_LENGTH 0x000a /* 2 bytes */ #define PCDATA_REVISION 0x000c #define PCDATA_IMAGE_SZ 0x0010 /* 2 bytes */ #define PCDATA_ROM_LEVEL 0x0012 /* 2 bytes */ #define PCDATA_CODE_TYPE 0x0014 #define PCDATA_INDICATOR 0x0015 /*===================================================================== Expansion ROM's have a special layout, and pointers specify an image number and an offset within that image. xlate_rom_addr() converts an image/offset address to an absolute offset from the ROM's base address. =====================================================================*/ static u_int xlate_rom_addr(void __iomem *b, u_int addr) { u_int img = 0, ofs = 0, sz; u_short data; while ((readb(b) == 0x55) && (readb(b + 1) == 0xaa)) { if (img == (addr >> 28)) return (addr & 0x0fffffff) + ofs; data = readb(b + ROM_DATA_PTR) + (readb(b + ROM_DATA_PTR + 1) << 8); sz = 512 * (readb(b + data + PCDATA_IMAGE_SZ) + (readb(b + data + PCDATA_IMAGE_SZ + 1) << 8)); if ((sz == 0) || (readb(b + data + PCDATA_INDICATOR) & 0x80)) break; b += sz; ofs += sz; img++; } return 0; } /*===================================================================== These are similar to setup_cis_mem and release_cis_mem for 16-bit cards. The "result" that is used externally is the cb_cis_virt pointer in the struct pcmcia_socket structure. =====================================================================*/ static void cb_release_cis_mem(struct pcmcia_socket * s) { if (s->cb_cis_virt) { cs_dbg(s, 1, "cb_release_cis_mem()\n"); iounmap(s->cb_cis_virt); s->cb_cis_virt = NULL; s->cb_cis_res = NULL; } } static int cb_setup_cis_mem(struct pcmcia_socket * s, struct resource *res) { unsigned int start, size; if (res == s->cb_cis_res) return 0; if (s->cb_cis_res) cb_release_cis_mem(s); start = res->start; size = res->end - start + 1; s->cb_cis_virt = ioremap(start, size); if (!s->cb_cis_virt) return -1; s->cb_cis_res = res; return 0; } /*===================================================================== This is used by the CIS processing code to read CIS information from a CardBus device. =====================================================================*/ int read_cb_mem(struct pcmcia_socket * s, int space, u_int addr, u_int len, void *ptr) { struct pci_dev *dev; struct resource *res; cs_dbg(s, 3, "read_cb_mem(%d, %#x, %u)\n", space, addr, len); dev = pci_get_slot(s->cb_dev->subordinate, 0); if (!dev) goto fail; /* Config space? */ if (space == 0) { if (addr + len > 0x100) goto fail; for (; len; addr++, ptr++, len--) pci_read_config_byte(dev, addr, ptr); return 0; } res = dev->resource + space - 1; pci_dev_put(dev); if (!res->flags) goto fail; if (cb_setup_cis_mem(s, res) != 0) goto fail; if (space == 7) { addr = xlate_rom_addr(s->cb_cis_virt, addr); if (addr == 0) goto fail; } if (addr + len > res->end - res->start) goto fail; memcpy_fromio(ptr, s->cb_cis_virt + addr, len); return 0; fail: memset(ptr, 0xff, len); return -1; } /*===================================================================== cb_alloc() and cb_free() allocate and free the kernel data structures for a Cardbus device, and handle the lowest level PCI device setup issues. =====================================================================*/ /* * Since there is only one interrupt available to CardBus * devices, all devices downstream of this device must * be using this IRQ. */ static void cardbus_assign_irqs(struct pci_bus *bus, int irq) { struct pci_dev *dev; list_for_each_entry(dev, &bus->devices, bus_list) { u8 irq_pin; pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &irq_pin); if (irq_pin) { dev->irq = irq; pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq); } if (dev->subordinate) cardbus_assign_irqs(dev->subordinate, irq); } } int cb_alloc(struct pcmcia_socket * s) { struct pci_bus *bus = s->cb_dev->subordinate; struct pci_dev *dev; unsigned int max, pass; s->functions = pci_scan_slot(bus, PCI_DEVFN(0, 0)); // pcibios_fixup_bus(bus); max = bus->secondary; for (pass = 0; pass < 2; pass++) list_for_each_entry(dev, &bus->devices, bus_list) if (dev->hdr_type == PCI_HEADER_TYPE_BRIDGE || dev->hdr_type == PCI_HEADER_TYPE_CARDBUS) max = pci_scan_bridge(bus, dev, max, pass); /* * Size all resources below the CardBus controller. */ pci_bus_size_bridges(bus); pci_bus_assign_resources(bus); cardbus_assign_irqs(bus, s->pci_irq); /* socket specific tune function */ if (s->tune_bridge) s->tune_bridge(s, bus); pci_enable_bridges(bus); pci_bus_add_devices(bus); s->irq.AssignedIRQ = s->pci_irq; return CS_SUCCESS; } void cb_free(struct pcmcia_socket * s) { struct pci_dev *bridge = s->cb_dev; cb_release_cis_mem(s); if (bridge) pci_remove_behind_bridge(bridge); }
#include <stdio.h> int max(int a, int b) { if(a>b) return a; return b; } int main() { int n, ulh, ulm, ath, atm, caixas=0, at=1, i; scanf(" %d", &n); scanf(" %d %d", &ulh, &ulm); for(i=1;i<n;i++) { scanf(" %d %d", &ath, &atm); if(ath==ulh && ulm==atm) at++; else { caixas = max(caixas, at); at=1; } ulh = ath; ulm = atm; } caixas = max(caixas, at); printf("%d", caixas); return 0; }
/**************************************************************************** * * ftcalc.h * * Arithmetic computations (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef FTCALC_H_ #define FTCALC_H_ #include <freetype/freetype.h> #include "compiler-macros.h" FT_BEGIN_HEADER /************************************************************************** * * FT_MulDiv() and FT_MulFix() are declared in freetype.h. * */ #ifndef FT_CONFIG_OPTION_NO_ASSEMBLER /* Provide assembler fragments for performance-critical functions. */ /* These must be defined `static __inline__' with GCC. */ #if defined( __CC_ARM ) || defined( __ARMCC__ ) /* RVCT */ #define FT_MULFIX_ASSEMBLER FT_MulFix_arm /* documentation is in freetype.h */ static __inline FT_Int32 FT_MulFix_arm( FT_Int32 a, FT_Int32 b ) { FT_Int32 t, t2; __asm { smull t2, t, b, a /* (lo=t2,hi=t) = a*b */ mov a, t, asr #31 /* a = (hi >> 31) */ add a, a, #0x8000 /* a += 0x8000 */ adds t2, t2, a /* t2 += a */ adc t, t, #0 /* t += carry */ mov a, t2, lsr #16 /* a = t2 >> 16 */ orr a, a, t, lsl #16 /* a |= t << 16 */ } return a; } #endif /* __CC_ARM || __ARMCC__ */ #ifdef __GNUC__ #if defined( __arm__ ) && \ ( !defined( __thumb__ ) || defined( __thumb2__ ) ) && \ !( defined( __CC_ARM ) || defined( __ARMCC__ ) ) #define FT_MULFIX_ASSEMBLER FT_MulFix_arm /* documentation is in freetype.h */ static __inline__ FT_Int32 FT_MulFix_arm( FT_Int32 a, FT_Int32 b ) { FT_Int32 t, t2; __asm__ __volatile__ ( "smull %1, %2, %4, %3\n\t" /* (lo=%1,hi=%2) = a*b */ "mov %0, %2, asr #31\n\t" /* %0 = (hi >> 31) */ #if defined( __clang__ ) && defined( __thumb2__ ) "add.w %0, %0, #0x8000\n\t" /* %0 += 0x8000 */ #else "add %0, %0, #0x8000\n\t" /* %0 += 0x8000 */ #endif "adds %1, %1, %0\n\t" /* %1 += %0 */ "adc %2, %2, #0\n\t" /* %2 += carry */ "mov %0, %1, lsr #16\n\t" /* %0 = %1 >> 16 */ "orr %0, %0, %2, lsl #16\n\t" /* %0 |= %2 << 16 */ : "=r"(a), "=&r"(t2), "=&r"(t) : "r"(a), "r"(b) : "cc" ); return a; } #endif /* __arm__ && */ /* ( __thumb2__ || !__thumb__ ) && */ /* !( __CC_ARM || __ARMCC__ ) */ #if defined( __i386__ ) #define FT_MULFIX_ASSEMBLER FT_MulFix_i386 /* documentation is in freetype.h */ static __inline__ FT_Int32 FT_MulFix_i386( FT_Int32 a, FT_Int32 b ) { FT_Int32 result; __asm__ __volatile__ ( "imul %%edx\n" "movl %%edx, %%ecx\n" "sarl $31, %%ecx\n" "addl $0x8000, %%ecx\n" "addl %%ecx, %%eax\n" "adcl $0, %%edx\n" "shrl $16, %%eax\n" "shll $16, %%edx\n" "addl %%edx, %%eax\n" : "=a"(result), "=d"(b) : "a"(a), "d"(b) : "%ecx", "cc" ); return result; } #endif /* i386 */ #endif /* __GNUC__ */ #ifdef _MSC_VER /* Visual C++ */ #ifdef _M_IX86 #define FT_MULFIX_ASSEMBLER FT_MulFix_i386 /* documentation is in freetype.h */ static __inline FT_Int32 FT_MulFix_i386( FT_Int32 a, FT_Int32 b ) { FT_Int32 result; __asm { mov eax, a mov edx, b imul edx mov ecx, edx sar ecx, 31 add ecx, 8000h add eax, ecx adc edx, 0 shr eax, 16 shl edx, 16 add eax, edx mov result, eax } return result; } #endif /* _M_IX86 */ #endif /* _MSC_VER */ #if defined( __GNUC__ ) && defined( __x86_64__ ) #define FT_MULFIX_ASSEMBLER FT_MulFix_x86_64 static __inline__ FT_Int32 FT_MulFix_x86_64( FT_Int32 a, FT_Int32 b ) { /* Temporarily disable the warning that C90 doesn't support */ /* `long long'. */ #if __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wlong-long" #endif #if 1 /* Technically not an assembly fragment, but GCC does a really good */ /* job at inlining it and generating good machine code for it. */ long long ret, tmp; ret = (long long)a * b; tmp = ret >> 63; ret += 0x8000 + tmp; return (FT_Int32)( ret >> 16 ); #else /* For some reason, GCC 4.6 on Ubuntu 12.04 generates invalid machine */ /* code from the lines below. The main issue is that `wide_a' is not */ /* properly initialized by sign-extending `a'. Instead, the generated */ /* machine code assumes that the register that contains `a' on input */ /* can be used directly as a 64-bit value, which is wrong most of the */ /* time. */ long long wide_a = (long long)a; long long wide_b = (long long)b; long long result; __asm__ __volatile__ ( "imul %2, %1\n" "mov %1, %0\n" "sar $63, %0\n" "lea 0x8000(%1, %0), %0\n" "sar $16, %0\n" : "=&r"(result), "=&r"(wide_a) : "r"(wide_b) : "cc" ); return (FT_Int32)result; #endif #if __GNUC__ > 4 || ( __GNUC__ == 4 && __GNUC_MINOR__ >= 6 ) #pragma GCC diagnostic pop #endif } #endif /* __GNUC__ && __x86_64__ */ #endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */ #ifdef FT_CONFIG_OPTION_INLINE_MULFIX #ifdef FT_MULFIX_ASSEMBLER #define FT_MulFix( a, b ) FT_MULFIX_ASSEMBLER( (FT_Int32)(a), (FT_Int32)(b) ) #endif #endif /************************************************************************** * * @function: * FT_MulDiv_No_Round * * @description: * A very simple function used to perform the computation '(a*b)/c' * (without rounding) with maximum accuracy (it uses a 64-bit * intermediate integer whenever necessary). * * This function isn't necessarily as fast as some processor-specific * operations, but is at least completely portable. * * @input: * a :: * The first multiplier. * b :: * The second multiplier. * c :: * The divisor. * * @return: * The result of '(a*b)/c'. This function never traps when trying to * divide by zero; it simply returns 'MaxInt' or 'MinInt' depending on * the signs of 'a' and 'b'. */ FT_BASE( FT_Long ) FT_MulDiv_No_Round( FT_Long a, FT_Long b, FT_Long c ); /* * A variant of FT_Matrix_Multiply which scales its result afterwards. The * idea is that both `a' and `b' are scaled by factors of 10 so that the * values are as precise as possible to get a correct result during the * 64bit multiplication. Let `sa' and `sb' be the scaling factors of `a' * and `b', respectively, then the scaling factor of the result is `sa*sb'. */ FT_BASE( void ) FT_Matrix_Multiply_Scaled( const FT_Matrix* a, FT_Matrix *b, FT_Long scaling ); /* * Check a matrix. If the transformation would lead to extreme shear or * extreme scaling, for example, return 0. If everything is OK, return 1. * * Based on geometric considerations we use the following inequality to * identify a degenerate matrix. * * 50 * abs(xx*yy - xy*yx) < xx^2 + xy^2 + yx^2 + yy^2 * * Value 50 is heuristic. */ FT_BASE( FT_Bool ) FT_Matrix_Check( const FT_Matrix* matrix ); /* * A variant of FT_Vector_Transform. See comments for * FT_Matrix_Multiply_Scaled. */ FT_BASE( void ) FT_Vector_Transform_Scaled( FT_Vector* vector, const FT_Matrix* matrix, FT_Long scaling ); /* * This function normalizes a vector and returns its original length. The * normalized vector is a 16.16 fixed-point unit vector with length close * to 0x10000. The accuracy of the returned length is limited to 16 bits * also. The function utilizes quick inverse square root approximation * without divisions and square roots relying on Newton's iterations * instead. */ FT_BASE( FT_UInt32 ) FT_Vector_NormLen( FT_Vector* vector ); /* * Return -1, 0, or +1, depending on the orientation of a given corner. We * use the Cartesian coordinate system, with positive vertical values going * upwards. The function returns +1 if the corner turns to the left, -1 to * the right, and 0 for undecidable cases. */ FT_BASE( FT_Int ) ft_corner_orientation( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); /* * Return TRUE if a corner is flat or nearly flat. This is equivalent to * saying that the corner point is close to its neighbors, or inside an * ellipse defined by the neighbor focal points to be more precise. */ FT_BASE( FT_Int ) ft_corner_is_flat( FT_Pos in_x, FT_Pos in_y, FT_Pos out_x, FT_Pos out_y ); /* * Return the most significant bit index. */ #ifndef FT_CONFIG_OPTION_NO_ASSEMBLER #if defined( __clang__ ) || ( defined( __GNUC__ ) && \ ( __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 4 ) ) ) #if FT_SIZEOF_INT == 4 #define FT_MSB( x ) ( 31 - __builtin_clz( x ) ) #elif FT_SIZEOF_LONG == 4 #define FT_MSB( x ) ( 31 - __builtin_clzl( x ) ) #endif #elif defined( _MSC_VER ) && _MSC_VER >= 1400 #if defined( _WIN32_WCE ) #include <cmnintrin.h> #pragma intrinsic( _CountLeadingZeros ) #define FT_MSB( x ) ( 31 - _CountLeadingZeros( x ) ) #elif defined( _M_ARM64 ) || defined( _M_ARM ) #include <intrin.h> #pragma intrinsic( _CountLeadingZeros ) #define FT_MSB( x ) ( 31 - _CountLeadingZeros( x ) ) #elif defined( _M_IX86 ) || defined( _M_AMD64 ) || defined( _M_IA64 ) #include <intrin.h> #pragma intrinsic( _BitScanReverse ) static __inline FT_Int32 FT_MSB_i386( FT_UInt32 x ) { unsigned long where; _BitScanReverse( &where, x ); return (FT_Int32)where; } #define FT_MSB( x ) FT_MSB_i386( x ) #endif #elif defined( __WATCOMC__ ) && defined( __386__ ) extern __inline FT_Int32 FT_MSB_i386( FT_UInt32 x ); #pragma aux FT_MSB_i386 = \ "bsr eax, eax" \ parm [eax] nomemory \ value [eax] \ modify exact [eax] nomemory; #define FT_MSB( x ) FT_MSB_i386( x ) #elif defined( __DECC ) || defined( __DECCXX ) #include <builtins.h> #define FT_MSB( x ) (FT_Int)( 63 - _leadz( x ) ) #elif defined( _CRAYC ) #include <intrinsics.h> #define FT_MSB( x ) (FT_Int)( 31 - _leadz32( x ) ) #endif /* FT_MSB macro definitions */ #endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */ #ifndef FT_MSB FT_BASE( FT_Int ) FT_MSB( FT_UInt32 z ); #endif /* * Return sqrt(x*x+y*y), which is the same as `FT_Vector_Length' but uses * two fixed-point arguments instead. */ FT_BASE( FT_Fixed ) FT_Hypot( FT_Fixed x, FT_Fixed y ); #if 0 /************************************************************************** * * @function: * FT_SqrtFixed * * @description: * Computes the square root of a 16.16 fixed-point value. * * @input: * x :: * The value to compute the root for. * * @return: * The result of 'sqrt(x)'. * * @note: * This function is not very fast. */ FT_BASE( FT_Int32 ) FT_SqrtFixed( FT_Int32 x ); #endif /* 0 */ #define INT_TO_F26DOT6( x ) ( (FT_Long)(x) * 64 ) /* << 6 */ #define INT_TO_F2DOT14( x ) ( (FT_Long)(x) * 16384 ) /* << 14 */ #define INT_TO_FIXED( x ) ( (FT_Long)(x) * 65536 ) /* << 16 */ #define F2DOT14_TO_FIXED( x ) ( (FT_Long)(x) * 4 ) /* << 2 */ #define FIXED_TO_INT( x ) ( FT_RoundFix( x ) >> 16 ) #define ROUND_F26DOT6( x ) ( ( (x) + 32 - ( x < 0 ) ) & -64 ) /* * The following macros have two purposes. * * - Tag places where overflow is expected and harmless. * * - Avoid run-time sanitizer errors. * * Use with care! */ #define ADD_INT( a, b ) \ (FT_Int)( (FT_UInt)(a) + (FT_UInt)(b) ) #define SUB_INT( a, b ) \ (FT_Int)( (FT_UInt)(a) - (FT_UInt)(b) ) #define MUL_INT( a, b ) \ (FT_Int)( (FT_UInt)(a) * (FT_UInt)(b) ) #define NEG_INT( a ) \ (FT_Int)( (FT_UInt)0 - (FT_UInt)(a) ) #define ADD_LONG( a, b ) \ (FT_Long)( (FT_ULong)(a) + (FT_ULong)(b) ) #define SUB_LONG( a, b ) \ (FT_Long)( (FT_ULong)(a) - (FT_ULong)(b) ) #define MUL_LONG( a, b ) \ (FT_Long)( (FT_ULong)(a) * (FT_ULong)(b) ) #define NEG_LONG( a ) \ (FT_Long)( (FT_ULong)0 - (FT_ULong)(a) ) #define ADD_INT32( a, b ) \ (FT_Int32)( (FT_UInt32)(a) + (FT_UInt32)(b) ) #define SUB_INT32( a, b ) \ (FT_Int32)( (FT_UInt32)(a) - (FT_UInt32)(b) ) #define MUL_INT32( a, b ) \ (FT_Int32)( (FT_UInt32)(a) * (FT_UInt32)(b) ) #define NEG_INT32( a ) \ (FT_Int32)( (FT_UInt32)0 - (FT_UInt32)(a) ) #ifdef FT_INT64 #define ADD_INT64( a, b ) \ (FT_Int64)( (FT_UInt64)(a) + (FT_UInt64)(b) ) #define SUB_INT64( a, b ) \ (FT_Int64)( (FT_UInt64)(a) - (FT_UInt64)(b) ) #define MUL_INT64( a, b ) \ (FT_Int64)( (FT_UInt64)(a) * (FT_UInt64)(b) ) #define NEG_INT64( a ) \ (FT_Int64)( (FT_UInt64)0 - (FT_UInt64)(a) ) #endif /* FT_INT64 */ FT_END_HEADER #endif /* FTCALC_H_ */ /* END */
/* -Abstract The memory allocation prototypes and macros for use in CSPICE. -Disclaimer THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE SOFTWARE AND RELATED MATERIALS, HOWEVER USED. IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. -Particulars The routines maintain a count of the number of mallocs vs. free, signalling an error if any unreleased memory exists at the end of an Icy interface call. The macro ALLOC_CHECK performs malloc/free test. If used, the macro should exists at the end of any routine using these memory management routines. Prototypes in this file: alloc_count zzalloc_count alloc_SpiceMemory alloc_SpiceString_C_array alloc_SpiceString_C_Copy_array alloc_SpiceDouble_C_array alloc_SpiceInt_C_array alloc_SpiceString alloc_SpiceString_Pointer_array free_SpiceString_C_array free_SpiceMemory -Version CSPICE 1.0.3 02-MAY-2008 (EDW) Added alloc_count prototype. CSPICE 1.0.2 10-MAY-2007 (EDW) Minor edits to clarify 'size' in alloc_SpiceMemory as size_t. CSPICE 1.0.1 23-JUN-2005 (EDW) Add prototype for alloc_SpiceString_Pointer_array, allocate an array of pointers to SpiceChar. Icy 1.0.0 December 19, 2003 (EDW) Initial release. */ #ifndef ZZALLOC_H #define ZZALLOC_H /* Allocation call prototypes: */ int alloc_count (); SpiceChar ** alloc_SpiceString_C_array ( int string_length, int string_count ); SpiceChar ** alloc_SpiceString_C_Copy_array ( int array_len , int string_len, SpiceChar ** array ); SpiceDouble * alloc_SpiceDouble_C_array ( int rows, int cols ); SpiceInt * alloc_SpiceInt_C_array ( int rows, int cols ); SpiceChar * alloc_SpiceString ( int length ); SpiceChar ** alloc_SpiceString_Pointer_array( int array_len ); void free_SpiceString_C_array ( int dim, SpiceChar ** array ); void * alloc_SpiceMemory ( size_t size ); void free_SpiceMemory ( void * ptr ); /* Simple macro to ensure a zero value alloc count at end of routine. Note, the need to use this macro exists only in those routines allocating/deallocating memory. */ #define ALLOC_CHECK if ( alloc_count() != 0 ) \ { \ setmsg_c ( "Malloc/Free count not zero at end of routine." \ " Malloc count = #."); \ errint_c ( "#", alloc_count() ); \ sigerr_c ( "SPICE(MALLOCCOUNT)" ); \ } #endif
//***************************************************************************** // //! SPI Slave Interrupt handler //! //! This function is invoked when SPI slave has its receive register full or //! transmit register empty. //! //! \return None. // //***************************************************************************** static void SlaveIntHandler() { unsigned long ulRecvData; unsigned long ulStatus; ulStatus = MAP_SPIIntStatus(GSPI_BASE,true); MAP_SPIIntClear(GSPI_BASE,SPI_INT_RX_FULL|SPI_INT_TX_EMPTY); if(ulStatus & SPI_INT_TX_EMPTY) { MAP_SPIDataPut(GSPI_BASE,g_ucTxBuff[ucTxBuffNdx%TR_BUFF_SIZE]); ucTxBuffNdx++; } if(ulStatus & SPI_INT_RX_FULL) { MAP_SPIDataGetNonBlocking(GSPI_BASE,&ulRecvData); g_ucTxBuff[ucRxBuffNdx%TR_BUFF_SIZE] = ulRecvData; Report("%c",ulRecvData); ucRxBuffNdx++; } }
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2015 Intel Corporation */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stddef.h> #include <limits.h> #include <inttypes.h> #include <unistd.h> #include <pthread.h> #include <fcntl.h> #include <sys/time.h> #include <sys/mman.h> #include <rte_per_lcore.h> #include <rte_log.h> #include <rte_spinlock.h> #include <rte_common.h> #include "lthread_api.h" #include "lthread_int.h" #include "lthread_mutex.h" #include "lthread_sched.h" #include "lthread_queue.h" #include "lthread_objcache.h" #include "lthread_diag.h" /* * Create a mutex */ int lthread_mutex_init(char *name, struct lthread_mutex **mutex, __rte_unused const struct lthread_mutexattr *attr) { struct lthread_mutex *m; if (mutex == NULL) return POSIX_ERRNO(EINVAL); m = _lthread_objcache_alloc((THIS_SCHED)->mutex_cache); if (m == NULL) return POSIX_ERRNO(EAGAIN); m->blocked = _lthread_queue_create("blocked queue"); if (m->blocked == NULL) { _lthread_objcache_free((THIS_SCHED)->mutex_cache, m); return POSIX_ERRNO(EAGAIN); } if (name == NULL) strncpy(m->name, "no name", sizeof(m->name)); else strncpy(m->name, name, sizeof(m->name)); m->name[sizeof(m->name)-1] = 0; m->root_sched = THIS_SCHED; m->owner = NULL; rte_atomic64_init(&m->count); DIAG_CREATE_EVENT(m, LT_DIAG_MUTEX_CREATE); /* success */ (*mutex) = m; return 0; } /* * Destroy a mutex */ int lthread_mutex_destroy(struct lthread_mutex *m) { if ((m == NULL) || (m->blocked == NULL)) { DIAG_EVENT(m, LT_DIAG_MUTEX_DESTROY, m, POSIX_ERRNO(EINVAL)); return POSIX_ERRNO(EINVAL); } if (m->owner == NULL) { /* try to delete the blocked queue */ if (_lthread_queue_destroy(m->blocked) < 0) { DIAG_EVENT(m, LT_DIAG_MUTEX_DESTROY, m, POSIX_ERRNO(EBUSY)); return POSIX_ERRNO(EBUSY); } /* free the mutex to cache */ _lthread_objcache_free(m->root_sched->mutex_cache, m); DIAG_EVENT(m, LT_DIAG_MUTEX_DESTROY, m, 0); return 0; } /* can't do its still in use */ DIAG_EVENT(m, LT_DIAG_MUTEX_DESTROY, m, POSIX_ERRNO(EBUSY)); return POSIX_ERRNO(EBUSY); } /* * Try to obtain a mutex */ int lthread_mutex_lock(struct lthread_mutex *m) { struct lthread *lt = THIS_LTHREAD; if ((m == NULL) || (m->blocked == NULL)) { DIAG_EVENT(m, LT_DIAG_MUTEX_LOCK, m, POSIX_ERRNO(EINVAL)); return POSIX_ERRNO(EINVAL); } /* allow no recursion */ if (m->owner == lt) { DIAG_EVENT(m, LT_DIAG_MUTEX_LOCK, m, POSIX_ERRNO(EDEADLK)); return POSIX_ERRNO(EDEADLK); } for (;;) { rte_atomic64_inc(&m->count); do { if (rte_atomic64_cmpset ((uint64_t *) &m->owner, 0, (uint64_t) lt)) { /* happy days, we got the lock */ DIAG_EVENT(m, LT_DIAG_MUTEX_LOCK, m, 0); return 0; } /* spin due to race with unlock when * nothing was blocked */ } while ((rte_atomic64_read(&m->count) == 1) && (m->owner == NULL)); /* queue the current thread in the blocked queue * we defer this to after we return to the scheduler * to ensure that the current thread context is saved * before unlock could result in it being dequeued and * resumed */ DIAG_EVENT(m, LT_DIAG_MUTEX_BLOCKED, m, lt); lt->pending_wr_queue = m->blocked; /* now relinquish cpu */ _suspend(); /* resumed, must loop and compete for the lock again */ } return 0; } /* try to lock a mutex but don't block */ int lthread_mutex_trylock(struct lthread_mutex *m) { struct lthread *lt = THIS_LTHREAD; if ((m == NULL) || (m->blocked == NULL)) { DIAG_EVENT(m, LT_DIAG_MUTEX_TRYLOCK, m, POSIX_ERRNO(EINVAL)); return POSIX_ERRNO(EINVAL); } if (m->owner == lt) { /* no recursion */ DIAG_EVENT(m, LT_DIAG_MUTEX_TRYLOCK, m, POSIX_ERRNO(EDEADLK)); return POSIX_ERRNO(EDEADLK); } rte_atomic64_inc(&m->count); if (rte_atomic64_cmpset ((uint64_t *) &m->owner, (uint64_t) NULL, (uint64_t) lt)) { /* got the lock */ DIAG_EVENT(m, LT_DIAG_MUTEX_TRYLOCK, m, 0); return 0; } /* failed so return busy */ rte_atomic64_dec(&m->count); DIAG_EVENT(m, LT_DIAG_MUTEX_TRYLOCK, m, POSIX_ERRNO(EBUSY)); return POSIX_ERRNO(EBUSY); } /* * Unlock a mutex */ int lthread_mutex_unlock(struct lthread_mutex *m) { struct lthread *lt = THIS_LTHREAD; struct lthread *unblocked; if ((m == NULL) || (m->blocked == NULL)) { DIAG_EVENT(m, LT_DIAG_MUTEX_UNLOCKED, m, POSIX_ERRNO(EINVAL)); return POSIX_ERRNO(EINVAL); } /* fail if its owned */ if (m->owner != lt || m->owner == NULL) { DIAG_EVENT(m, LT_DIAG_MUTEX_UNLOCKED, m, POSIX_ERRNO(EPERM)); return POSIX_ERRNO(EPERM); } rte_atomic64_dec(&m->count); /* if there are blocked threads then make one ready */ while (rte_atomic64_read(&m->count) > 0) { unblocked = _lthread_queue_remove(m->blocked); if (unblocked != NULL) { rte_atomic64_dec(&m->count); DIAG_EVENT(m, LT_DIAG_MUTEX_UNLOCKED, m, unblocked); RTE_ASSERT(unblocked->sched != NULL); _ready_queue_insert((struct lthread_sched *) unblocked->sched, unblocked); break; } } /* release the lock */ m->owner = NULL; return 0; } /* * return the diagnostic ref val stored in a mutex */ uint64_t lthread_mutex_diag_ref(struct lthread_mutex *m) { if (m == NULL) return 0; return m->diag_ref; }
/*---------------------------------------------------------------------------*/ /* Write to a 16-bit register. args: reg register to write to val value to write */ void tmp102_write_reg (uint8_t reg, uint16_t val) { uint8_t tx_buf[] = { reg, 0x00, 0x00 }; tx_buf[1] = (uint8_t) (val >> 8); tx_buf[2] = (uint8_t) (val & 0x00FF); i2c_write_register(1,TMP102_ADDR, sizeof(tx_buf), tx_buf); }
/** Create a NxN float identity matrix. @param m Location to store the resulting identity matrix. @param n The size of the matrix. */ static inline void matNf_identity(float m[], int n) { for(int row=0; row<n; row++) for(int col=0; col<n; col++) if(row==col) m[row+col*n] = 1.0f; else m[row+col*n] = 0.0f; }
#ifndef __OSD_ATTRIBUTES_H__ #define __OSD_ATTRIBUTES_H__ #include <scsi/osd_protocol.h> /* * Contains types and constants that define attribute pages and attribute * numbers and their data types. */ #define ATTR_SET(pg, id, l, ptr) \ { .attr_page = pg, .attr_id = id, .len = l, .val_ptr = ptr } #define ATTR_DEF(pg, id, l) ATTR_SET(pg, id, l, NULL) /* osd-r10 4.7.3 Attributes pages */ enum { OSD_APAGE_OBJECT_FIRST = 0x0, OSD_APAGE_OBJECT_DIRECTORY = 0, OSD_APAGE_OBJECT_INFORMATION = 1, OSD_APAGE_OBJECT_QUOTAS = 2, OSD_APAGE_OBJECT_TIMESTAMP = 3, OSD_APAGE_OBJECT_COLLECTIONS = 4, OSD_APAGE_OBJECT_SECURITY = 5, OSD_APAGE_OBJECT_LAST = 0x2fffffff, OSD_APAGE_PARTITION_FIRST = 0x30000000, OSD_APAGE_PARTITION_DIRECTORY = OSD_APAGE_PARTITION_FIRST + 0, OSD_APAGE_PARTITION_INFORMATION = OSD_APAGE_PARTITION_FIRST + 1, OSD_APAGE_PARTITION_QUOTAS = OSD_APAGE_PARTITION_FIRST + 2, OSD_APAGE_PARTITION_TIMESTAMP = OSD_APAGE_PARTITION_FIRST + 3, OSD_APAGE_PARTITION_ATTR_ACCESS = OSD_APAGE_PARTITION_FIRST + 4, OSD_APAGE_PARTITION_SECURITY = OSD_APAGE_PARTITION_FIRST + 5, OSD_APAGE_PARTITION_LAST = 0x5FFFFFFF, OSD_APAGE_COLLECTION_FIRST = 0x60000000, OSD_APAGE_COLLECTION_DIRECTORY = OSD_APAGE_COLLECTION_FIRST + 0, OSD_APAGE_COLLECTION_INFORMATION = OSD_APAGE_COLLECTION_FIRST + 1, OSD_APAGE_COLLECTION_TIMESTAMP = OSD_APAGE_COLLECTION_FIRST + 3, OSD_APAGE_COLLECTION_SECURITY = OSD_APAGE_COLLECTION_FIRST + 5, OSD_APAGE_COLLECTION_LAST = 0x8FFFFFFF, OSD_APAGE_ROOT_FIRST = 0x90000000, OSD_APAGE_ROOT_DIRECTORY = OSD_APAGE_ROOT_FIRST + 0, OSD_APAGE_ROOT_INFORMATION = OSD_APAGE_ROOT_FIRST + 1, OSD_APAGE_ROOT_QUOTAS = OSD_APAGE_ROOT_FIRST + 2, OSD_APAGE_ROOT_TIMESTAMP = OSD_APAGE_ROOT_FIRST + 3, OSD_APAGE_ROOT_SECURITY = OSD_APAGE_ROOT_FIRST + 5, OSD_APAGE_ROOT_LAST = 0xBFFFFFFF, OSD_APAGE_RESERVED_TYPE_FIRST = 0xC0000000, OSD_APAGE_RESERVED_TYPE_LAST = 0xEFFFFFFF, OSD_APAGE_COMMON_FIRST = 0xF0000000, OSD_APAGE_COMMON_LAST = 0xFFFFFFFD, OSD_APAGE_CURRENT_COMMAND = 0xFFFFFFFE, OSD_APAGE_REQUEST_ALL = 0xFFFFFFFF, }; /* subcategories of attr pages within each range above */ enum { OSD_APAGE_STD_FIRST = 0x0, OSD_APAGE_STD_DIRECTORY = 0, OSD_APAGE_STD_INFORMATION = 1, OSD_APAGE_STD_QUOTAS = 2, OSD_APAGE_STD_TIMESTAMP = 3, OSD_APAGE_STD_COLLECTIONS = 4, OSD_APAGE_STD_POLICY_SECURITY = 5, OSD_APAGE_STD_LAST = 0x0000007F, OSD_APAGE_RESERVED_FIRST = 0x00000080, OSD_APAGE_RESERVED_LAST = 0x00007FFF, OSD_APAGE_OTHER_STD_FIRST = 0x00008000, OSD_APAGE_OTHER_STD_LAST = 0x0000EFFF, OSD_APAGE_PUBLIC_FIRST = 0x0000F000, OSD_APAGE_PUBLIC_LAST = 0x0000FFFF, OSD_APAGE_APP_DEFINED_FIRST = 0x00010000, OSD_APAGE_APP_DEFINED_LAST = 0x1FFFFFFF, OSD_APAGE_VENDOR_SPECIFIC_FIRST = 0x20000000, OSD_APAGE_VENDOR_SPECIFIC_LAST = 0x2FFFFFFF, }; enum { OSD_ATTR_PAGE_IDENTIFICATION = 0, /* in all pages 40 bytes */ }; struct page_identification { u8 vendor_identification[8]; u8 page_identification[32]; } __packed; struct osd_attr_page_header { __be32 page_number; __be32 page_length; } __packed; /* 7.1.2.8 Root Information attributes page (OSD_APAGE_ROOT_INFORMATION) */ enum { OSD_ATTR_RI_OSD_SYSTEM_ID = 0x3, /* 20 */ OSD_ATTR_RI_VENDOR_IDENTIFICATION = 0x4, /* 8 */ OSD_ATTR_RI_PRODUCT_IDENTIFICATION = 0x5, /* 16 */ OSD_ATTR_RI_PRODUCT_MODEL = 0x6, /* 32 */ OSD_ATTR_RI_PRODUCT_REVISION_LEVEL = 0x7, /* 4 */ OSD_ATTR_RI_PRODUCT_SERIAL_NUMBER = 0x8, /* variable */ OSD_ATTR_RI_OSD_NAME = 0x9, /* variable */ OSD_ATTR_RI_MAX_CDB_CONTINUATION_LEN = 0xA, /* 4 */ OSD_ATTR_RI_TOTAL_CAPACITY = 0x80, /* 8 */ OSD_ATTR_RI_USED_CAPACITY = 0x81, /* 8 */ OSD_ATTR_RI_NUMBER_OF_PARTITIONS = 0xC0, /* 8 */ OSD_ATTR_RI_CLOCK = 0x100, /* 6 */ OARI_DEFAULT_ISOLATION_METHOD = 0X110, /* 1 */ OARI_SUPPORTED_ISOLATION_METHODS = 0X111, /* 32 */ OARI_DATA_ATOMICITY_GUARANTEE = 0X120, /* 8 */ OARI_DATA_ATOMICITY_ALIGNMENT = 0X121, /* 8 */ OARI_ATTRIBUTES_ATOMICITY_GUARANTEE = 0X122, /* 8 */ OARI_DATA_ATTRIBUTES_ATOMICITY_MULTIPLIER = 0X123, /* 1 */ OARI_MAXIMUM_SNAPSHOTS_COUNT = 0X1C1, /* 0 or 4 */ OARI_MAXIMUM_CLONES_COUNT = 0X1C2, /* 0 or 4 */ OARI_MAXIMUM_BRANCH_DEPTH = 0X1CC, /* 0 or 4 */ OARI_SUPPORTED_OBJECT_DUPLICATION_METHOD_FIRST = 0X200, /* 0 or 4 */ OARI_SUPPORTED_OBJECT_DUPLICATION_METHOD_LAST = 0X2ff, /* 0 or 4 */ OARI_SUPPORTED_TIME_OF_DUPLICATION_METHOD_FIRST = 0X300, /* 0 or 4 */ OARI_SUPPORTED_TIME_OF_DUPLICATION_METHOD_LAST = 0X30F, /* 0 or 4 */ OARI_SUPPORT_FOR_DUPLICATED_OBJECT_FREEZING = 0X310, /* 0 or 4 */ OARI_SUPPORT_FOR_SNAPSHOT_REFRESHING = 0X311, /* 0 or 1 */ OARI_SUPPORTED_CDB_CONTINUATION_DESC_TYPE_FIRST = 0X7000001,/* 0 or 4 */ OARI_SUPPORTED_CDB_CONTINUATION_DESC_TYPE_LAST = 0X700FFFF,/* 0 or 4 */ }; /* Root_Information_attributes_page does not have a get_page structure */ /* 7.1.2.9 Partition Information attributes page * (OSD_APAGE_PARTITION_INFORMATION) */ enum { OSD_ATTR_PI_PARTITION_ID = 0x1, /* 8 */ OSD_ATTR_PI_USERNAME = 0x9, /* variable */ OSD_ATTR_PI_USED_CAPACITY = 0x81, /* 8 */ OSD_ATTR_PI_USED_CAPACITY_INCREMENT = 0x84, /* 0 or 8 */ OSD_ATTR_PI_NUMBER_OF_OBJECTS = 0xC1, /* 8 */ OSD_ATTR_PI_ACTUAL_DATA_SPACE = 0xD1, /* 0 or 8 */ OSD_ATTR_PI_RESERVED_DATA_SPACE = 0xD2, /* 0 or 8 */ OSD_ATTR_PI_DEFAULT_SNAPSHOT_DUPLICATION_METHOD = 0x200,/* 0 or 4 */ OSD_ATTR_PI_DEFAULT_CLONE_DUPLICATION_METHOD = 0x201,/* 0 or 4 */ OSD_ATTR_PI_DEFAULT_SP_TIME_OF_DUPLICATION = 0x300,/* 0 or 4 */ OSD_ATTR_PI_DEFAULT_CLONE_TIME_OF_DUPLICATION = 0x301,/* 0 or 4 */ }; /* Partition Information attributes page does not have a get_page structure */ /* 7.1.2.10 Collection Information attributes page * (OSD_APAGE_COLLECTION_INFORMATION) */ enum { OSD_ATTR_CI_PARTITION_ID = 0x1, /* 8 */ OSD_ATTR_CI_COLLECTION_OBJECT_ID = 0x2, /* 8 */ OSD_ATTR_CI_USERNAME = 0x9, /* variable */ OSD_ATTR_CI_COLLECTION_TYPE = 0xA, /* 1 */ OSD_ATTR_CI_USED_CAPACITY = 0x81, /* 8 */ }; /* Collection Information attributes page does not have a get_page structure */ /* 7.1.2.11 User Object Information attributes page * (OSD_APAGE_OBJECT_INFORMATION) */ enum { OSD_ATTR_OI_PARTITION_ID = 0x1, /* 8 */ OSD_ATTR_OI_OBJECT_ID = 0x2, /* 8 */ OSD_ATTR_OI_USERNAME = 0x9, /* variable */ OSD_ATTR_OI_USED_CAPACITY = 0x81, /* 8 */ OSD_ATTR_OI_LOGICAL_LENGTH = 0x82, /* 8 */ SD_ATTR_OI_ACTUAL_DATA_SPACE = 0XD1, /* 0 OR 8 */ SD_ATTR_OI_RESERVED_DATA_SPACE = 0XD2, /* 0 OR 8 */ }; /* Object Information attributes page does not have a get_page structure */ /* 7.1.2.12 Root Quotas attributes page (OSD_APAGE_ROOT_QUOTAS) */ enum { OSD_ATTR_RQ_DEFAULT_MAXIMUM_USER_OBJECT_LENGTH = 0x1, /* 8 */ OSD_ATTR_RQ_PARTITION_CAPACITY_QUOTA = 0x10001, /* 8 */ OSD_ATTR_RQ_PARTITION_OBJECT_COUNT = 0x10002, /* 8 */ OSD_ATTR_RQ_PARTITION_COLLECTIONS_PER_USER_OBJECT = 0x10081, /* 4 */ OSD_ATTR_RQ_PARTITION_COUNT = 0x20002, /* 8 */ }; struct Root_Quotas_attributes_page { struct osd_attr_page_header hdr; /* id=R+2, size=0x24 */ __be64 default_maximum_user_object_length; __be64 partition_capacity_quota; __be64 partition_object_count; __be64 partition_collections_per_user_object; __be64 partition_count; } __packed; /* 7.1.2.13 Partition Quotas attributes page (OSD_APAGE_PARTITION_QUOTAS)*/ enum { OSD_ATTR_PQ_DEFAULT_MAXIMUM_USER_OBJECT_LENGTH = 0x1, /* 8 */ OSD_ATTR_PQ_CAPACITY_QUOTA = 0x10001, /* 8 */ OSD_ATTR_PQ_OBJECT_COUNT = 0x10002, /* 8 */ OSD_ATTR_PQ_COLLECTIONS_PER_USER_OBJECT = 0x10081, /* 4 */ }; struct Partition_Quotas_attributes_page { struct osd_attr_page_header hdr; /* id=P+2, size=0x1C */ __be64 default_maximum_user_object_length; __be64 capacity_quota; __be64 object_count; __be64 collections_per_user_object; } __packed; /* 7.1.2.14 User Object Quotas attributes page (OSD_APAGE_OBJECT_QUOTAS) */ enum { OSD_ATTR_OQ_MAXIMUM_LENGTH = 0x1, /* 8 */ }; struct Object_Quotas_attributes_page { struct osd_attr_page_header hdr; /* id=U+2, size=0x8 */ __be64 maximum_length; } __packed; /* 7.1.2.15 Root Timestamps attributes page (OSD_APAGE_ROOT_TIMESTAMP) */ enum { OSD_ATTR_RT_ATTRIBUTES_ACCESSED_TIME = 0x2, /* 6 */ OSD_ATTR_RT_ATTRIBUTES_MODIFIED_TIME = 0x3, /* 6 */ OSD_ATTR_RT_TIMESTAMP_BYPASS = 0xFFFFFFFE, /* 1 */ }; struct root_timestamps_attributes_page { struct osd_attr_page_header hdr; /* id=R+3, size=0xD */ struct osd_timestamp attributes_accessed_time; struct osd_timestamp attributes_modified_time; u8 timestamp_bypass; } __packed; /* 7.1.2.16 Partition Timestamps attributes page * (OSD_APAGE_PARTITION_TIMESTAMP) */ enum { OSD_ATTR_PT_CREATED_TIME = 0x1, /* 6 */ OSD_ATTR_PT_ATTRIBUTES_ACCESSED_TIME = 0x2, /* 6 */ OSD_ATTR_PT_ATTRIBUTES_MODIFIED_TIME = 0x3, /* 6 */ OSD_ATTR_PT_DATA_ACCESSED_TIME = 0x4, /* 6 */ OSD_ATTR_PT_DATA_MODIFIED_TIME = 0x5, /* 6 */ OSD_ATTR_PT_TIMESTAMP_BYPASS = 0xFFFFFFFE, /* 1 */ }; struct partition_timestamps_attributes_page { struct osd_attr_page_header hdr; /* id=P+3, size=0x1F */ struct osd_timestamp created_time; struct osd_timestamp attributes_accessed_time; struct osd_timestamp attributes_modified_time; struct osd_timestamp data_accessed_time; struct osd_timestamp data_modified_time; u8 timestamp_bypass; } __packed; /* 7.1.2.17/18 Collection/Object Timestamps attributes page * (OSD_APAGE_COLLECTION_TIMESTAMP/OSD_APAGE_OBJECT_TIMESTAMP) */ enum { OSD_ATTR_OT_CREATED_TIME = 0x1, /* 6 */ OSD_ATTR_OT_ATTRIBUTES_ACCESSED_TIME = 0x2, /* 6 */ OSD_ATTR_OT_ATTRIBUTES_MODIFIED_TIME = 0x3, /* 6 */ OSD_ATTR_OT_DATA_ACCESSED_TIME = 0x4, /* 6 */ OSD_ATTR_OT_DATA_MODIFIED_TIME = 0x5, /* 6 */ }; /* same for collection */ struct object_timestamps_attributes_page { struct osd_attr_page_header hdr; /* id=C+3/3, size=0x1E */ struct osd_timestamp created_time; struct osd_timestamp attributes_accessed_time; struct osd_timestamp attributes_modified_time; struct osd_timestamp data_accessed_time; struct osd_timestamp data_modified_time; } __packed; /* OSD2r05: 7.1.3.19 Attributes Access attributes page * (OSD_APAGE_PARTITION_ATTR_ACCESS) * * each attribute is of the form below. Total array length is deduced * from the attribute's length * (See allowed_attributes_access of the struct osd_cap_object_descriptor) */ struct attributes_access_attr { struct osd_attributes_list_attrid attr_list[0]; } __packed; /* OSD2r05: 7.1.2.21 Collections attributes page */ /* TBD */ /* 7.1.2.20 Root Policy/Security attributes page (OSD_APAGE_ROOT_SECURITY) */ enum { OSD_ATTR_RS_DEFAULT_SECURITY_METHOD = 0x1, /* 1 */ OSD_ATTR_RS_OLDEST_VALID_NONCE_LIMIT = 0x2, /* 6 */ OSD_ATTR_RS_NEWEST_VALID_NONCE_LIMIT = 0x3, /* 6 */ OSD_ATTR_RS_PARTITION_DEFAULT_SECURITY_METHOD = 0x6, /* 1 */ OSD_ATTR_RS_SUPPORTED_SECURITY_METHODS = 0x7, /* 2 */ OSD_ATTR_RS_ADJUSTABLE_CLOCK = 0x9, /* 6 */ OSD_ATTR_RS_MASTER_KEY_IDENTIFIER = 0x7FFD, /* 0 or 7 */ OSD_ATTR_RS_ROOT_KEY_IDENTIFIER = 0x7FFE, /* 0 or 7 */ OSD_ATTR_RS_SUPPORTED_INTEGRITY_ALGORITHM_0 = 0x80000000,/* 1,(x16)*/ OSD_ATTR_RS_SUPPORTED_DH_GROUP_0 = 0x80000010,/* 1,(x16)*/ }; struct root_security_attributes_page { struct osd_attr_page_header hdr; /* id=R+5, size=0x3F */ u8 default_security_method; u8 partition_default_security_method; __be16 supported_security_methods; u8 mki_valid_rki_valid; struct osd_timestamp oldest_valid_nonce_limit; struct osd_timestamp newest_valid_nonce_limit; struct osd_timestamp adjustable_clock; u8 master_key_identifier[32-25]; u8 root_key_identifier[39-32]; u8 supported_integrity_algorithm[16]; u8 supported_dh_group[16]; } __packed; /* 7.1.2.21 Partition Policy/Security attributes page * (OSD_APAGE_PARTITION_SECURITY) */ enum { OSD_ATTR_PS_DEFAULT_SECURITY_METHOD = 0x1, /* 1 */ OSD_ATTR_PS_OLDEST_VALID_NONCE = 0x2, /* 6 */ OSD_ATTR_PS_NEWEST_VALID_NONCE = 0x3, /* 6 */ OSD_ATTR_PS_REQUEST_NONCE_LIST_DEPTH = 0x4, /* 2 */ OSD_ATTR_PS_FROZEN_WORKING_KEY_BIT_MASK = 0x5, /* 2 */ OSD_ATTR_PS_PARTITION_KEY_IDENTIFIER = 0x7FFF, /* 0 or 7 */ OSD_ATTR_PS_WORKING_KEY_IDENTIFIER_FIRST = 0x8000, /* 0 or 7 */ OSD_ATTR_PS_WORKING_KEY_IDENTIFIER_LAST = 0x800F, /* 0 or 7 */ OSD_ATTR_PS_POLICY_ACCESS_TAG = 0x40000001, /* 4 */ OSD_ATTR_PS_USER_OBJECT_POLICY_ACCESS_TAG = 0x40000002, /* 4 */ }; struct partition_security_attributes_page { struct osd_attr_page_header hdr; /* id=p+5, size=0x8f */ u8 reserved[3]; u8 default_security_method; struct osd_timestamp oldest_valid_nonce; struct osd_timestamp newest_valid_nonce; __be16 request_nonce_list_depth; __be16 frozen_working_key_bit_mask; __be32 policy_access_tag; __be32 user_object_policy_access_tag; u8 pki_valid; __be16 wki_00_0f_vld; struct osd_key_identifier partition_key_identifier; struct osd_key_identifier working_key_identifiers[16]; } __packed; /* 7.1.2.22/23 Collection/Object Policy-Security attributes page * (OSD_APAGE_COLLECTION_SECURITY/OSD_APAGE_OBJECT_SECURITY) */ enum { OSD_ATTR_OS_POLICY_ACCESS_TAG = 0x40000001, /* 4 */ }; struct object_security_attributes_page { struct osd_attr_page_header hdr; /* id=C+5/5, size=4 */ __be32 policy_access_tag; } __packed; /* OSD2r05: 7.1.3.31 Current Command attributes page * (OSD_APAGE_CURRENT_COMMAND) */ enum { OSD_ATTR_CC_RESPONSE_INTEGRITY_CHECK_VALUE = 0x1, /* 32 */ OSD_ATTR_CC_OBJECT_TYPE = 0x2, /* 1 */ OSD_ATTR_CC_PARTITION_ID = 0x3, /* 8 */ OSD_ATTR_CC_OBJECT_ID = 0x4, /* 8 */ OSD_ATTR_CC_STARTING_BYTE_ADDRESS_OF_APPEND = 0x5, /* 8 */ OSD_ATTR_CC_CHANGE_IN_USED_CAPACITY = 0x6, /* 8 */ }; /*TBD: osdv1_current_command_attributes_page */ struct osdv2_current_command_attributes_page { struct osd_attr_page_header hdr; /* id=0xFFFFFFFE, size=0x44 */ u8 response_integrity_check_value[OSD_CRYPTO_KEYID_SIZE]; u8 object_type; u8 reserved[3]; __be64 partition_id; __be64 object_id; __be64 starting_byte_address_of_append; __be64 change_in_used_capacity; }; #endif /*ndef __OSD_ATTRIBUTES_H__*/
/** * @brief Handles the PRESS sensor data getting/sending. * @param Msg - PRESS part of the stream * @retval None */ static void Pressure_Sensor_Handler(TMsg *Msg) { uint8_t status = 0; float PRESSURE_Value; if(Sensors_Enabled & PRESSURE_SENSOR) { if(BSP_PRESSURE_IsInitialized(PRESSURE_handle, &status) == COMPONENT_OK && status == 1) { BSP_PRESSURE_Get_Press(PRESSURE_handle, &PRESSURE_Value); memcpy(&Msg->Data[7], (void *)&PRESSURE_Value, sizeof(float)); } } }
/** * The request distributor calls this function if it picked the PCIXCC/CEX2C * device to handle a modexpo request. * @zdev: pointer to zcrypt_device structure that identifies the * PCIXCC/CEX2C device to the request distributor * @mex: pointer to the modexpo request buffer */ static long zcrypt_msgtype6_modexpo(struct zcrypt_device *zdev, struct ica_rsa_modexpo *mex) { struct ap_message ap_msg; struct response_type resp_type = { .type = PCIXCC_RESPONSE_TYPE_ICA, }; int rc; ap_init_message(&ap_msg); ap_msg.message = (void *) get_zeroed_page(GFP_KERNEL); if (!ap_msg.message) return -ENOMEM; ap_msg.receive = zcrypt_msgtype6_receive; ap_msg.psmid = (((unsigned long long) current->pid) << 32) + atomic_inc_return(&zcrypt_step); ap_msg.private = &resp_type; rc = ICAMEX_msg_to_type6MEX_msgX(zdev, &ap_msg, mex); if (rc) goto out_free; init_completion(&resp_type.work); ap_queue_message(zdev->ap_dev, &ap_msg); rc = wait_for_completion_interruptible(&resp_type.work); if (rc == 0) rc = convert_response_ica(zdev, &ap_msg, mex->outputdata, mex->outputdatalength); else ap_cancel_message(zdev->ap_dev, &ap_msg); out_free: free_page((unsigned long) ap_msg.message); return rc; }
/** * This file is part of DSO. * * Copyright 2016 Technical University of Munich and Intel. * Developed by Jakob Engel <engelj at in dot tum dot de>, * for more information see <http://vision.in.tum.de/dso>. * If you use this code, please cite the respective publications as * listed on the above website. * * DSO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DSO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSO. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "util/NumType.h" namespace dso { const float minUseGrad_pixsel = 10; template<int pot> inline int gridMaxSelection(Eigen::Vector3f* grads, bool* map_out, int w, int h, float THFac) { memset(map_out, 0, sizeof(bool)*w*h); int numGood = 0; for(int y=1;y<h-pot;y+=pot) { for(int x=1;x<w-pot;x+=pot) { int bestXXID = -1; int bestYYID = -1; int bestXYID = -1; int bestYXID = -1; float bestXX=0, bestYY=0, bestXY=0, bestYX=0; Eigen::Vector3f* grads0 = grads+x+y*w; for(int dx=0;dx<pot;dx++) for(int dy=0;dy<pot;dy++) { int idx = dx+dy*w; Eigen::Vector3f g=grads0[idx]; float sqgd = g.tail<2>().squaredNorm(); float TH = THFac*minUseGrad_pixsel * (0.75f); if(sqgd > TH*TH) { float agx = fabs((float)g[1]); if(agx > bestXX) {bestXX=agx; bestXXID=idx;} float agy = fabs((float)g[2]); if(agy > bestYY) {bestYY=agy; bestYYID=idx;} float gxpy = fabs((float)(g[1]-g[2])); if(gxpy > bestXY) {bestXY=gxpy; bestXYID=idx;} float gxmy = fabs((float)(g[1]+g[2])); if(gxmy > bestYX) {bestYX=gxmy; bestYXID=idx;} } } bool* map0 = map_out+x+y*w; if(bestXXID>=0) { if(!map0[bestXXID]) numGood++; map0[bestXXID] = true; } if(bestYYID>=0) { if(!map0[bestYYID]) numGood++; map0[bestYYID] = true; } if(bestXYID>=0) { if(!map0[bestXYID]) numGood++; map0[bestXYID] = true; } if(bestYXID>=0) { if(!map0[bestYXID]) numGood++; map0[bestYXID] = true; } } } return numGood; } //根据像素自身的梯度来选点 inline int gridMaxSelection(Eigen::Vector3f* grads, bool* map_out, int w, int h, int pot, float THFac) { memset(map_out, 0, sizeof(bool)*w*h); int numGood = 0; for(int y=1;y<h-pot;y+=pot) { for(int x=1;x<w-pot;x+=pot) { int bestXXID = -1; int bestYYID = -1; int bestXYID = -1; int bestYXID = -1; float bestXX=0, bestYY=0, bestXY=0, bestYX=0; Eigen::Vector3f* grads0 = grads+x+y*w; for(int dx=0;dx<pot;dx++) for(int dy=0;dy<pot;dy++) { int idx = dx+dy*w; Eigen::Vector3f g=grads0[idx]; float sqgd = g.tail<2>().squaredNorm(); float TH = THFac*minUseGrad_pixsel * (0.75f); if(sqgd > TH*TH) { float agx = fabs((float)g[1]); if(agx > bestXX) {bestXX=agx; bestXXID=idx;} float agy = fabs((float)g[2]); if(agy > bestYY) {bestYY=agy; bestYYID=idx;} float gxpy = fabs((float)(g[1]-g[2])); if(gxpy > bestXY) {bestXY=gxpy; bestXYID=idx;} float gxmy = fabs((float)(g[1]+g[2])); if(gxmy > bestYX) {bestYX=gxmy; bestYXID=idx;} } } bool* map0 = map_out+x+y*w; if(bestXXID>=0) { if(!map0[bestXXID]) numGood++; map0[bestXXID] = true; } if(bestYYID>=0) { if(!map0[bestYYID]) numGood++; map0[bestYYID] = true; } if(bestXYID>=0) { if(!map0[bestXYID]) numGood++; map0[bestXYID] = true; } if(bestYXID>=0) { if(!map0[bestYXID]) numGood++; map0[bestYXID] = true; } } } return numGood; } inline int makePixelStatus(Eigen::Vector3f* grads, bool* map, int w, int h, float desiredDensity, int recsLeft=5, float THFac = 1) { if(sparsityFactor < 1) sparsityFactor = 1; int numGoodPoints; if(sparsityFactor==1) numGoodPoints = gridMaxSelection<1>(grads, map, w, h, THFac); else if(sparsityFactor==2) numGoodPoints = gridMaxSelection<2>(grads, map, w, h, THFac); else if(sparsityFactor==3) numGoodPoints = gridMaxSelection<3>(grads, map, w, h, THFac); else if(sparsityFactor==4) numGoodPoints = gridMaxSelection<4>(grads, map, w, h, THFac); else if(sparsityFactor==5) numGoodPoints = gridMaxSelection<5>(grads, map, w, h, THFac); else if(sparsityFactor==6) numGoodPoints = gridMaxSelection<6>(grads, map, w, h, THFac); else if(sparsityFactor==7) numGoodPoints = gridMaxSelection<7>(grads, map, w, h, THFac); else if(sparsityFactor==8) numGoodPoints = gridMaxSelection<8>(grads, map, w, h, THFac); else if(sparsityFactor==9) numGoodPoints = gridMaxSelection<9>(grads, map, w, h, THFac); else if(sparsityFactor==10) numGoodPoints = gridMaxSelection<10>(grads, map, w, h, THFac); else if(sparsityFactor==11) numGoodPoints = gridMaxSelection<11>(grads, map, w, h, THFac); else numGoodPoints = gridMaxSelection(grads, map, w, h, sparsityFactor, THFac); /* * #points is approximately proportional to sparsityFactor^2. */ float quotia = numGoodPoints / (float)(desiredDensity); int newSparsity = (sparsityFactor * sqrtf(quotia))+0.7f; if(newSparsity < 1) newSparsity=1; float oldTHFac = THFac; if(newSparsity==1 && sparsityFactor==1) THFac = 0.5; if((abs(newSparsity-sparsityFactor) < 1 && THFac==oldTHFac) || ( quotia > 0.8 && 1.0f / quotia > 0.8) || recsLeft == 0) { // printf(" \n"); //all good sparsityFactor = newSparsity; return numGoodPoints; } else { // printf(" -> re-evaluate! \n"); // re-evaluate. sparsityFactor = newSparsity; return makePixelStatus(grads, map, w,h, desiredDensity, recsLeft-1, THFac); } } }
#pragma once #include <vector> #include <Eigen/Dense> namespace drake { /// Returns true if and only if the two matrices are equal to within a certain /// absolute elementwise @p tolerance. Special values (infinities, NaN, etc.) /// do not compare as equal elements. template <typename DerivedA, typename DerivedB> bool is_approx_equal_abstol(const Eigen::MatrixBase<DerivedA>& m1, const Eigen::MatrixBase<DerivedB>& m2, double tolerance) { return ( (m1.rows() == m2.rows()) && (m1.cols() == m2.cols()) && ((m1 - m2).template lpNorm<Eigen::Infinity>() <= tolerance)); } /// Returns true if and only if a simple greedy search reveals a permutation /// of the columns of m2 to make the matrix equal to m1 to within a certain /// absolute elementwise @p tolerance. E.g., there exists a P such that /// <pre> /// forall i,j, |m1 - m2*P|_{i,j} <= tolerance /// where P is a permutation matrix: /// P(i,j)={0,1}, sum_i P(i,j)=1, sum_j P(i,j)=1. /// </pre> /// Note: Returns false for matrices of different sizes. /// Note: The current implementation is O(n^2) in the number of columns. /// Note: In marginal cases (with similar but not identical columns) this /// algorithm can fail to find a permutation P even if it exists because it /// accepts the first column match (m1(i),m2(j)) and removes m2(j) from the /// pool. It is possible that other columns of m2 would also match m1(i) but /// that m2(j) is the only match possible for a later column of m1. template <typename DerivedA, typename DerivedB> bool IsApproxEqualAbsTolWithPermutedColumns( const Eigen::MatrixBase<DerivedA>& m1, const Eigen::MatrixBase<DerivedB>& m2, double tolerance) { if ((m1.cols() != m2.cols()) || (m1.rows() != m2.rows())) return false; std::vector<bool> available(m2.cols()); for (int i = 0; i < m2.cols(); i++) available[i] = true; for (int i = 0; i < m1.cols(); i++) { bool found_match = false; for (int j = 0; j < m2.cols(); j++) { if (available[j] && is_approx_equal_abstol(m1.col(i), m2.col(j), tolerance)) { found_match = true; available[j] = false; break; } } if (!found_match) return false; } return true; } } // namespace drake
/* Put ITEM onto QUEUE, allocating it in QUEUE's pool... * If a checksum is provided, it can be the MD5 and/or the SHA1. */ static svn_error_t * post_process_commit_item(svn_wc_committed_queue_t *queue, const svn_client_commit_item3_t *item, svn_wc_context_t *wc_ctx, svn_boolean_t keep_changelists, svn_boolean_t keep_locks, svn_boolean_t commit_as_operations, const svn_checksum_t *sha1_checksum, apr_pool_t *scratch_pool) { svn_boolean_t loop_recurse = FALSE; svn_boolean_t remove_lock; if (! commit_as_operations && (item->state_flags & SVN_CLIENT_COMMIT_ITEM_ADD) && (item->kind == svn_node_dir) && (item->copyfrom_url)) loop_recurse = TRUE; remove_lock = (! keep_locks && (item->state_flags & SVN_CLIENT_COMMIT_ITEM_LOCK_TOKEN)); return svn_wc_queue_committed3(queue, wc_ctx, item->path, loop_recurse, item->incoming_prop_changes, remove_lock, !keep_changelists, sha1_checksum, scratch_pool); }
/*! \brief Sends a character with the USART. * * \param usart Base address of the USART instance. * \param c Character to write. * * \return Status code */ static inline enum status_code usart_serial_putchar(struct usart_module *const module, uint8_t c) { return usart_write_wait(module, c); }
/* * Request the nsp IOMUX pinmux controller to mux individual pins to GPIO */ static int nsp_gpio_request(struct gpio_chip *gc, unsigned offset) { unsigned gpio = gc->base + offset; return pinctrl_request_gpio(gpio); }
/* { dg-do run } */ /* { dg-options "-O2 -mavx512f" } */ /* { dg-require-effective-target avx512f } */ #include "avx512f-check.h" static __m512i __attribute__ ((noinline)) foo (long long x1, long long x2, long long x3, long long x4, long long x5, long long x6, long long x7, long long x8) { return _mm512_set_epi64 (x1, x2, x3, x4, x5, x6, x7, x8); } static __m512i __attribute__ ((noinline)) foo_r (long long x1, long long x2, long long x3, long long x4, long long x5, long long x6, long long x7, long long x8) { return _mm512_setr_epi64 (x8, x7, x6, x5, x4, x3, x2, x1); } static void avx512f_test (void) { long long v[8] = { 0x12e9e94645ad8LL, 0x851c0b39446LL, 2134, 6678, 0x786784645245LL, 0x9487731234LL, 41124, 86530 }; union512i_q res; res.x = foo (v[7], v[6], v[5], v[4], v[3], v[2], v[1], v[0]); if (check_union512i_q (res, v)) abort (); res.x = _mm512_setzero_si512 (); res.x = foo_r (v[7], v[6], v[5], v[4], v[3], v[2], v[1], v[0]); if (check_union512i_q (res, v)) abort (); }
/* * Create a new replace struct, clear it and return it. */ static struct replace * new_replace(void) { struct replace *replace; replaces = reallocate(replaces, (nreplaces + 1) * sizeof(struct replace)); replace = replaces + nreplaces; nreplaces++; memset(replace, '\0', sizeof(struct replace)); return(replace); }
/* Output and update for function-call system: '<S1>/rsnToOpenCC' */ void BSC_rsnToOpenCC(SimStruct * const S) { B_BSC_T *_rtB; PrevZCX_BSC_T *_rtZCE; _rtZCE = ((PrevZCX_BSC_T *) _ssGetPrevZCSigState(S)); _rtB = ((B_BSC_T *) ssGetLocalBlockIO(S)); _rtB->Add = (uint8_T)((uint32_T)_rtB->MinMax + _rtB->MinMax1); if (((_rtB->key_cycle.key_cycle > 0) != (_rtZCE->TriggeredSubsystem_Trig_ZCE == POS_ZCSIG)) && (_rtZCE->TriggeredSubsystem_Trig_ZCE != UNINITIALIZED_ZCSIG)) { if (_rtB->Add > 0) { _rtB->Merge = _rtB->check_type.type_of_fault; } else { _rtB->Merge = 0U; } } _rtZCE->TriggeredSubsystem_Trig_ZCE = (uint8_T)(_rtB->key_cycle.key_cycle > 0); ((uint8_T *)ssGetOutputPortSignal(S, 4))[0] = _rtB->Merge; ((uint8_T *)ssGetOutputPortSignal(S, 5))[0] = _rtB->Add; }
/* Create a list of numbers of PME nodes to test */ static void make_npme_list( const char *npmevalues_opt, int *nentries, int *nPMEnodes[], int nnodes, int minPMEnodes, int maxPMEnodes) { int i, npme, npp; int min_factor = 1; int nlistmax; int nlist; int eNPME = 0; if (0 == strcmp(npmevalues_opt, "all") ) { eNPME = eNpmeAll; } else if (0 == strcmp(npmevalues_opt, "subset") ) { eNPME = eNpmeSubset; } else { if (nnodes <= 64) { eNPME = eNpmeAll; } else if (nnodes < 128) { eNPME = eNpmeReduced; } else { eNPME = eNpmeSubset; } } if (nnodes > 2) { nlistmax = maxPMEnodes - minPMEnodes + 3; if (0 == minPMEnodes) { nlistmax--; } } else { nlistmax = 1; } snew(*nPMEnodes, nlistmax); nlist = 0; for (i = 0; i < nlistmax - 2; i++) { npme = maxPMEnodes - i; npp = nnodes-npme; switch (eNPME) { case eNpmeAll: min_factor = 1; break; case eNpmeReduced: min_factor = 2; break; case eNpmeSubset: min_factor = (int) pow(npp, 1.0/3.0); break; default: gmx_fatal(FARGS, "Unknown option for eNPME in make_npme_list"); break; } if (largest_common_factor(npp, npme) >= min_factor) { (*nPMEnodes)[nlist] = npme; nlist++; } } *nentries = nlist + 2; (*nPMEnodes)[nlist ] = 0; (*nPMEnodes)[nlist+1] = -1; fprintf(stderr, "Will try the following %d different values for -npme:\n", *nentries); for (i = 0; i < *nentries-1; i++) { fprintf(stderr, "%d, ", (*nPMEnodes)[i]); } fprintf(stderr, "and %d (auto).\n", (*nPMEnodes)[*nentries-1]); }
/** * nlmsvc_invalidate_all - remove all locks held for clients * * Release all locks held by NFS clients. * */ void nlmsvc_invalidate_all(void) { nlm_traverse_files(NULL, nlmsvc_is_client, NULL); }
/* * sqliteIterateForeignScan: Iterate and get the rows one by one from * Sqlite and placed in tuple slot */ static TupleTableSlot * sqliteIterateForeignScan(ForeignScanState *node) { SqliteFdwExecState *festate = (SqliteFdwExecState *) node->fdw_state; TupleTableSlot *tupleSlot = node->ss.ss_ScanTupleSlot; EState *estate = node->ss.ps.state; TupleDesc tupleDescriptor = tupleSlot->tts_tupleDescriptor; int rc = 0; elog(DEBUG1, "duckdb_fdw : %s", __func__); if (!festate->cursor_exists) create_cursor(node); ExecClearTuple(tupleSlot); if (festate->for_update && festate->rowidx == 0) { int size = 0; MemoryContext oldcontext = MemoryContextSwitchTo(estate->es_query_cxt); festate->row_nums = 0; festate->rowidx = 0; while (1) { rc = sqlite3_step(festate->stmt); if (rc == SQLITE_ROW) { if (size == 0) { size = 1; festate->rows = palloc(sizeof(Datum *) * size); festate->rows_isnull = palloc(sizeof(bool *) * size); } else if (festate->row_nums >= size) { size = size * 2; festate->rows = repalloc(festate->rows, sizeof(Datum *) * size); festate->rows_isnull = repalloc(festate->rows_isnull, sizeof(bool *) * size); } festate->rows[festate->row_nums] = palloc(sizeof(Datum) * tupleDescriptor->natts); festate->rows_isnull[festate->row_nums] = palloc(sizeof(bool) * tupleDescriptor->natts); make_tuple_from_result_row(festate->stmt, tupleDescriptor, festate->retrieved_attrs, festate->rows[festate->row_nums], festate->rows_isnull[festate->row_nums]); festate->row_nums++; } else if (SQLITE_DONE == rc) { break; } else { sqlitefdw_report_error(ERROR, festate->stmt, festate->conn, NULL, rc); } } MemoryContextSwitchTo(oldcontext); } if (festate->for_update) { if (festate->rowidx < festate->row_nums) { memcpy(tupleSlot->tts_values, festate->rows[festate->rowidx], sizeof(Datum) * tupleDescriptor->natts); memcpy(tupleSlot->tts_isnull, festate->rows_isnull[festate->rowidx], sizeof(bool) * tupleDescriptor->natts); ExecStoreVirtualTuple(tupleSlot); festate->rowidx++; } } else { rc = sqlite3_step(festate->stmt); if (SQLITE_ROW == rc) { make_tuple_from_result_row(festate->stmt, tupleDescriptor, festate->retrieved_attrs, tupleSlot->tts_values, tupleSlot->tts_isnull); ExecStoreVirtualTuple(tupleSlot); } else if (SQLITE_DONE == rc) { } else { sqlitefdw_report_error(ERROR, festate->stmt, festate->conn, NULL, rc); } } return tupleSlot; }
/* ** BOOL FPatchUs(int fh, LONG lib, USHORT us) ** ** Patch the USHORT at lib offset of fh with the us value, but leave ** the fh unchanged. Return TRUE if okay, FALSE in failure. */ BOOL FPatchUs(int fh, LONG lib, USHORT us) { LONG libSav; if (fh == -1 || (libSav = tell(fh)) == -1 || lseek(fh, lib, SEEK_SET) == -1) return(FALSE); if (!FWriteUs(fh, us)) { lseek(fh, libSav, SEEK_SET); return(FALSE); } if (lseek(fh, libSav, SEEK_SET) == -1) return(FALSE); return((BOOL)TRUE); }
//recalculates text properties and applies them to sprites void update_text_properties(text_t *t) { sprite_t *s; float scale = t->scale * SPRITE_SIZE * 2; float spacing = scale * LETTER_SPACING_SCALE; float x0 = 0; vec2_t position; Vec2Zero(position); switch (t->anchor) { case ANCHOR_RIGHT: x0 = -(t->length * spacing); break; case ANCHOR_CENTER: x0 = -(t->length * spacing / 2) + (spacing / 2); break; case ANCHOR_LEFT: default: break; } for (int i = 0; i < t->length; i++) { s = *(t->sprites + i); s->scale_x = scale; s->scale_y = scale; Color3Copy(t->color, s->color); position[VEC_X] = x0 + (spacing * i) + t->position[VEC_X]; position[VEC_Y] = t->position[VEC_Y]; Vec2Copy(position, s->position); s->render_layer = t->render_layer; s->collision_mask = t->collision_mask; if (t->action) { s->action = t->action; } if (t->object_data && t->data_size) { if (t->data_size) { s->object_data = malloc(t->data_size); memcpy(s->object_data, t->object_data, t->data_size); } else { free(s->object_data); } } } }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #define MAX 1000000 typedef struct i{ char n; struct i *prox; }link; typedef struct{ link *top; int size; }stack; link * createLink(char value, link *prox){ link *a; a = (link *) malloc(sizeof(link)); a->n = value; a->prox = prox; return a; } link * createLink2(link * prox){ link *a; a = (link *) malloc(sizeof(link)); a->prox = prox; return a; } stack createStack(){ stack s; s.top = NULL; s.size = 0; return s; } void push(stack *s, char value){ s->top = createLink(value, s->top); s->size++; } char pop(stack *s){ char ret; ret = s->top->n; s->top = s->top->prox; s->size--; return ret; } char topValue(stack *s){ char ret; ret = s->top->n; return ret; } int main(){ stack open = createStack(); char string[MAX]; scanf(" %s", string); int tamString = strlen(string), i; int changes = 0, tam, error = 0; int a = 0, c = 0; for(i = 0; i < tamString; i++){ if(string[i] == '<' || string[i] == '{' || string[i] == '[' || string[i] == '('){ a++; push(&open, string[i]); }else if(string[i] == '>' || string[i] == '}' || string[i] == ']' || string[i] == ')'){ c++; if(open.size == 0) { error = 1; break; }else{ char atual = topValue(&open); if(string[i] == '>' && atual != '<') changes++; else if(string[i] == '}' && atual != '{') changes++; else if(string[i] == ']' && atual != '[') changes++; else if(string[i] == ')' && atual != '(') changes++; pop(&open); } } } if(error == 0 && a == c) printf("%d\n", changes); else printf("Impossible"); return 0; }
/* aci_gatt_read_multi_permit_req_event */ /* Event len: 2 + 1 + rp0->Number_of_Handles * (sizeof(Handle_Item_t)) */ /** * @brief This event is given to the application when a read multiple request or * read by type request is received by the server from the client. This * event will be given to the application only if the event bit for this * event generation is set when the characteristic was added. On * receiving this event, the application can update the values of the * handles if it desires and when done, it has to send the @ref * aci_gatt_allow_read command to indicate to the stack that it can send * the response to the client. * @param Connection_Handle Handle of the connection which requested to read the * attribute * @param Number_of_Handles * @param Handle_Item See @ref Handle_Item_t * @retval None */ tBleStatus aci_gatt_read_multi_permit_req_event_process(uint8_t *buffer_in) { tBleStatus status = BLE_STATUS_SUCCESS; aci_gatt_read_multi_permit_req_event_rp0 *rp0 = (aci_gatt_read_multi_permit_req_event_rp0 *)buffer_in; uint8_t size = 3; int i; Handle_Item_t Handle_Item[HCI_MAX_PAYLOAD_SIZE/sizeof(Handle_Item_t)]; for (i = 0; i < rp0->Number_of_Handles; i++) { Handle_Item[i].Handle = rp0->Handle_Item[i].Handle; size += 2; } aci_gatt_read_multi_permit_req_event(rp0->Connection_Handle, rp0->Number_of_Handles, Handle_Item); return status; }
/* funtion name: key_unify_write * keyname : key name is ascii string * keydata : key data buf * datalen : key buf len * return 0: ok, -0x1fe: no space, other fail * * Step 1: Get burn target from dtb * Step 2: check whether can burned, OTP can't burned twice * 2.1)check is programmed yet, burn directly if not programmed yet. * 2.2)if programmed yet, check if OTP * Step 3: burn the key to the target * */ int key_unify_write(const char *keyname, const void* keydata, const unsigned datalen) { int err=0; const KmDevKeyOps* theDevOps = NULL; theDevOps = _get_km_ops_by_name(keyname); if (!theDevOps) { KM_ERR("key[%s] no cfg in dts\n", keyname); return __LINE__; } if (!theDevOps->can_overwrite) { KM_DBG("can't overwrite\n"); int ret = theDevOps->pKeyExist(keyname); if (ret) { KM_ERR("OTP key[%s] already existed, can't program twice!\n", keyname); return __LINE__; } } err = theDevOps->pWriteFunc(keyname, keydata, datalen); return err; }
/* * ***************************************************************************** * * Function: _addNewPrinterObject() * * Description: For the given printerName add a printer object into the * LDAP directory NS domain. The object is created with the * supplied attribute values. Note: if the printer's uri is * given that is used as the RDN otherwise the printer's * name is used as the RDN * * Parameters: * Input: LDAP *ld - existing ldap connection descriptor * uchar_t *printerName - Name of printer to be added * uchar_t *domainDN - DN of the domain to add the printer * char **attrList - user specified attribute values list * Output: None * * Returns: NSL_RESULT - NSL_OK = request actioned okay * !NSL_OK = error * * ***************************************************************************** */ static NSL_RESULT _addNewPrinterObject(LDAP *ld, uchar_t *printerName, uchar_t *domainDN, char **attrList) { NSL_RESULT result = NSL_ERR_ADD_FAILED; int lresult = 0; uchar_t *printerDN = NULL; LDAPMod **attrs = NULL; if ((ld != NULL) && (printerName != NULL) && (domainDN != NULL) && (attrList != NULL) && (attrList[0] != NULL)) { result = _checkAttributes(attrList); if (result == NSL_OK) { printerDN = _constructPrinterDN(printerName, domainDN, attrList); if (printerDN != NULL) { result = _constructAddLDAPMod(printerName, attrList, &attrs); if (result == NSL_OK) { lresult = ldap_add_s(ld, (char *)printerDN, attrs); if (lresult == LDAP_SUCCESS) { result = NSL_OK; } else { result = NSL_ERR_ADD_FAILED; #ifdef DEBUG (void) ldap_perror(ld, "ldap_add_s"); #endif } (void) ldap_mods_free(attrs, 1); } free(printerDN); } else { result = NSL_ERR_INTERNAL; } } } else { result = NSL_ERR_INTERNAL; } return (result); }
//----------------------------------------------------------------------------- // FUNCTION: D4DLCD_FlushBuffer_Flexbus_16b // SCOPE: Low Level Driver API function // DESCRIPTION: For buffered low level interfaces is used to inform // driver the complete object is drawed and pending pixels should be flushed // // PARAMETERS: none // // RETURNS: none //----------------------------------------------------------------------------- static void D4DLCD_FlushBuffer_Flexbus_16b(D4DLCD_FLUSH_MODE mode) { D4D_UNUSED(mode); }
/* As an extension of the normal return value (zero means good), -888 * instructs caller to bypass its write stage. */ static int rw_sparse_sparing(struct opts_t * op, struct cp_state_t * csp, int obs, int num, bool * sparse_skipp, bool * sparing_skipp, uint8_t * wPos) { int n, res; int od_type = op->odip->d_type; int ret = 0; if (op->oflagp->sparse) { n = (num * obs) + csp->partial_write_bytes; if (0 == memcmp(wPos, op->zeros_buff, n)) { *sparse_skipp = true; if (op->oflagp->wsame16 && (FT_PT & od_type)) { signals_process_delay(op, DELAY_WRITE); csp->low_bp = (uint8_t *)op->zeros_buff; csp->subseg_bp = csp->low_bp; csp->cur_countp = NULL; csp->buf_name = "zb"; res = cp_via_sgl_iter(op->odip, csp, num, cp_write_same_wrap, op); if (res) ++csp->stats.trim_errs; } else sgl_iter_add(&csp->out_iter, num, true ); } else if (op->obpch) { csp->cur_out_num = num; ret = cp_finer_comp_wr(op, csp, wPos, op->zeros_buff); if (ret) return ret; return -888; } } if (op->oflagp->sparing && (! *sparse_skipp)) { csp->reading = true; csp->cur_out_num = num; if (FT_PT & od_type) { csp->low_bp = op->wrkPos2; csp->subseg_bp = csp->low_bp; csp->cur_countp = NULL; csp->buf_name = "wPos2"; ret = cp_via_sgl_iter(op->odip, csp, num, cp_read_pt_wrap, op); if (ret) return ret; } else { csp->low_bp = op->wrkPos2; csp->subseg_bp = csp->low_bp; csp->cur_countp = NULL; csp->buf_name = "wPos2"; ret = cp_via_sgl_iter(op->odip, csp, num, cp_read_block_reg_wrap, op); if (ret) return ret; } n = (num * obs) + csp->partial_write_bytes; if (0 == memcmp(wPos, op->wrkPos2, n)) *sparing_skipp = true; else { if (op->iflagp->nowrite) ; else sgl_iter_sub(&csp->out_iter, num); if (op->obpch) { csp->reading = false; csp->low_bp = op->wrkPos2; csp->subseg_bp = csp->low_bp; csp->cur_countp = &csp->stats.out_full; csp->buf_name = "b1p=wPos; b2p=wPos2"; ret = cp_finer_comp_wr(op, csp, wPos, op->wrkPos2); if (ret) return ret; return -888; } } } return ret; }
/** * Sets a boolean floating-point ndarray data element. * * ## Notes * * - The function does **not** verify that the type of `v` matches the underlying input ndarray data type, and, thus, overwriting **unowned** memory is possible. The function **assumes** that you know what you are doing. * - The function returns `-1` if unable to set an element and `0` otherwise. * * @param arr input ndarray * @param sub ndarray subscripts * @param v value to set * @return status code */ int8_t stdlib_ndarray_set_bool( const struct ndarray *arr, const int64_t *sub, const bool v ) { uint8_t *idx = stdlib_ndarray_get_ptr( arr, sub ); if ( idx == NULL ) { return -1; } return stdlib_ndarray_set_ptr_bool( idx, v ); }
/* Set TX FIFO size and threshold */ static inline void pp2_port_tx_fifo_config(struct pp2_port *port, u32 fifo_size, uint32_t fifo_thr) { pp2_reg_write(port->cpu_slot, MVPP22_TX_FIFO_SIZE_REG(port->id), fifo_size & MVPP22_TX_FIFO_SIZE_MASK); pp2_reg_write(port->cpu_slot, MVPP22_TX_FIFO_THRESH_REG(port->id), fifo_thr & MVPP22_TX_FIFO_THRESH_MASK); }
// Read or Write from/to EEP I2C slave. static void HandleEEP(int argc, char **argv) { uint8_t testPatternWrite[4] = {0xAA, 0xBB, 0xAB, 0xBA}; uint8_t testPatternRead[4] = {}; uint8_t patternIdx = 0; uint16_t addr = 0x3000; if ((argc == ONE_ARGUMENT) && (strcmp(argv[FIRST_ARG_IDX], "e") == 0)) { HW_TERM_Print("Erasing all EEPROM..."); HW_EEP_EraseAll(); HW_TERM_Print("EEPROM Erased"); } else if ((argc == ONE_ARGUMENT) && (strcmp(argv[FIRST_ARG_IDX], "v") == 0)) { HW_TERM_Print("Validating NVM structures...\n"); APP_NVM_Validate(); } else if ((argc == ONE_ARGUMENT) && (strcmp(argv[FIRST_ARG_IDX], "d") == 0)) { HW_TERM_Print("Defaulting NVM structures...\n"); APP_NVM_DefaultAll(); } else if ((argc == TWO_ARGUMENTS) && (strcmp(argv[FIRST_ARG_IDX], "pattern") == 0)) { if (strcmp(argv[SECOND_ARG_IDX], "read") == 0) { for (patternIdx = 0; patternIdx < 4; patternIdx++) { testPatternRead[patternIdx] = HW_EEP_ReadByte(addr); addr++; } if ( memcmp(&testPatternRead, &testPatternWrite, 4) == 0 ) { HW_TERM_Print("\nPass\n"); } else { HW_TERM_PrintColor("\nFAIL\n", KRED); } } else if (strcmp(argv[SECOND_ARG_IDX], "write") == 0) { HW_EEP_WriteBlock(addr, (uint8_t*)&testPatternWrite, 4); HW_TERM_Print("\nWrite complete\n"); } else { HW_TERM_Print("Invalid parameter format."); } } else { HW_TERM_Print("Invalid parameter format."); } }
/******************************************************************* * output_srcdir_symlink * * Output rule to create a symlink back to the source directory, for source files * that are needed at run-time. */ static void output_srcdir_symlink( struct makefile *make, const char *obj ) { char *src_file, *dst_file, *src_name; if (!make->src_dir) return; src_file = src_dir_path( make, obj ); dst_file = obj_dir_path( make, obj ); output( "%s: %s\n", dst_file, src_file ); src_name = src_file; if (src_name[0] != '/' && make->obj_dir) src_name = concat_paths( get_relative_path( make->obj_dir, "" ), src_name ); output_symlink_rule( src_name, dst_file, 0 ); strarray_add( &make->all_targets, obj ); }
/* Simple Random Number Generators - getuniform - uniform deviate [0,1] - getnorm - gaussian (normal) deviate (mean=0, stddev=1) - getpoisson - poisson deviate for given expected mean lambda This code is adapted from SimpleRNG by John D Cook, which is provided in the public domain. The original C++ code is found here: http://www.johndcook.com/cpp_random_number_generation.html This code has been modified in the following ways compared to the original. 1. convert to C from C++ 2. keep only uniform, gaussian and poisson deviates 3. state variables are module static instead of class variables 4. provide an srand() equivalent to initialize the state */ extern void simplerng_setstate(unsigned int u, unsigned int v); extern void simplerng_getstate(unsigned int *u, unsigned int *v); extern void simplerng_srand(unsigned int seed); extern double simplerng_getuniform(void); extern double simplerng_getnorm(void); extern int simplerng_getpoisson(double lambda); extern double simplerng_logfactorial(int n);
#include<stdio.h> int main() { int m,n,p=2,q=1,count=0,z=0; scanf("%d %d",&m,&n); int i=1; while(m*n>=z) { count++; i++; z=z+2; } printf("%d",count-1); }
/* * Common ->done routine for commands executed synchronously. */ static void ub_probe_done(struct ub_dev *sc, struct ub_scsi_cmd *cmd) { struct completion *cop = cmd->back; complete(cop); }
#include<stdio.h> #define s 8 // マス目 #define F 1 #define NF -1 int A[s][s]; int row[s],col[s]; int pos[15],neg[15]; void print() { int i,j; for(i=0;i<s;i++) { for(j=0;j<s;j++) { if(A[i][j]) { if(row[i]!=j) return; } } } for(i=0;i<s;i++) { for(j=0;j<s;j++) { if(row[i]==j) printf("Q"); else printf("."); } printf("\n"); } } void putQueen(int i) { int j; if(i==s) { print(); return; } for(j=0;j<s;j++) { if(NF==col[j] || NF==pos[i+j] || NF==neg[i-j+s-1]) continue; row[i]=j; col[j] = pos[i+j] = neg[i-j+s-1] = NF; putQueen(i+1); row[i] = col[j] = pos[i+j] = neg[i-j+s-1] = F; } } int main() { int i,j; int r,c,k; for(i=0;i<s;i++) { for(j=0;j<s;j++) A[i][j]=0; } scanf("%d",&k); for(i=0;i<k;i++) { scanf("%d%d",&r,&c); A[r][c] = 1; } for(i=0 ; i<s ; i++) row[i] = col[i] = F; for(i=0 ; i<15 ; i++) pos[i] = neg[i] = F; putQueen(0); return 0; }
// srckey is the 64-bit master key (2x32 bits) XORed with the subkey // dstkey will contain the 96-bit key for the 2nd FN (4x24 bits) static void expand_2nd_key(UINT32 *dstkey, const UINT32 *srckey) { static const int bits[96] = { 34, 9, 32, 24, 44, 54, 38, 61, 47, 13, 28, 7, 29, 58, 18, 1, 20, 60, 15, 6, 11, 43, 39, 19, 63, 23, 16, 62, 54, 40, 31, 3, 56, 61, 17, 25, 47, 38, 55, 57, 5, 4, 15, 42, 22, 7, 2, 19, 46, 37, 29, 39, 12, 30, 49, 57, 31, 41, 26, 27, 24, 36, 11, 63, 33, 16, 56, 62, 48, 60, 59, 32, 12, 30, 53, 48, 10, 0, 50, 35, 3, 59, 14, 49, 51, 45, 44, 2, 21, 33, 55, 52, 23, 28, 8, 26, }; int i; dstkey[0] = 0; dstkey[1] = 0; dstkey[2] = 0; dstkey[3] = 0; for (i = 0; i < 96; ++i) dstkey[i / 24] |= BIT(srckey[bits[i] / 32], bits[i] % 32) << (i % 24); }
/* Returns the inode encapsulated by DIR. */ struct inode * dir_get_inode (struct dir *dir) { return dir->inode; }
#pragma once #include "drake/common/drake_copyable.h" #include "drake/common/drake_deprecated.h" #include "drake/lcmt_object_status.hpp" #include "drake/traj_gen/ilqr_kkt/object/object_constants.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace traj_gen { namespace kuka_iiwa_arm { /// Creates and outputs lcmt_object_status messages. /// /// Note that this system does not actually send the message an LCM channel. To /// send the message, the output of this system should be connected to a /// systems::lcm::LcmPublisherSystem::Make<lcmt_object_status>(). /// /// This system has many vector-valued input ports, each of which has exactly /// num_joints elements. /// /// - `position_commanded`: the most recently received position command. /// - `position_measured`: the plant's current position. /// - `velocity_estimated` (optional): the plant's current velocity (this /// should be a low-pass filter of the position's derivative; see detailed /// comments in `lcmt_object_status.lcm`); when absent, the output message /// will use zeros. /// - `torque_commanded`: the most recently received joint torque command. /// - `torque_measured` (optional): the plant's measured joint torque; when /// absent, the output message will duplicate torque_commanded. /// - `torque_external` (optional): the plant's external joint torque; when /// absent, the output message will use zeros. /// /// This system has one abstract-valued output port of type lcmt_object_status. /// /// This system is presently only used in simulation. The robot hardware drivers /// publish directly to LCM and do not make use of this system. /// /// @system{ObjectStatusSender, /// @input_port{position_commanded} /// @input_port{position_measured} /// @input_port{velocity_estimated (optional)} /// @input_port{torque_commanded} /// @input_port{torque_measured (optional)} /// @input_port{torque_external (optional)}, /// @output_port{lcmt_object_status} /// } /// @see `lcmt_object_status.lcm` for additional documentation. class ObjectStatusSender : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ObjectStatusSender) explicit ObjectStatusSender(int num_joints = kObjectNumJoints); /// @name Named accessors for this System's input and output ports. //@{ const systems::InputPort<double>& get_position_commanded_input_port() const; const systems::InputPort<double>& get_position_measured_input_port() const; const systems::InputPort<double>& get_velocity_estimated_input_port() const; const systems::InputPort<double>& get_torque_commanded_input_port() const; const systems::InputPort<double>& get_torque_measured_input_port() const; const systems::InputPort<double>& get_torque_external_input_port() const; const systems::OutputPort<double>& get_output_port() const; //@} private: void CalcOutput(const systems::Context<double>&, lcmt_object_status*) const; const int num_joints_; const Eigen::VectorXd zero_vector_; }; } // namespace kuka_iiwa_arm } // namespace traj_gen } // namespace drake
/** As tor_snprintf, but write the results into a buf_t */ void buf_add_printf(buf_t *buf, const char *format, ...) { va_list ap; va_start(ap,format); buf_add_vprintf(buf, format, ap); va_end(ap); }
/** * Construct a Function object for specified built-in accessor getter * * @return pointer to constructed accessor getter Function object */ static ecma_object_t * ecma_builtin_make_function_object_for_getter_accessor (ecma_object_t *builtin_object_p, uint8_t routine_id, uint32_t routine_index) { return ecma_builtin_make_function_object_for_routine (builtin_object_p, routine_id, routine_index, ECMA_BUILTIN_ROUTINE_GETTER); }
#define _CRT_SECURE_NO_WARNINGS #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include "private_config.h" #ifdef _WIN32 #define PATH_MAX 255 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <process.h> #include <direct.h> #include <io.h> #include <sys/types.h> #include <sys/stat.h> struct timezone; struct timeval { long tv_sec; long tv_usec; } timeval; static int gettimeofday(struct timeval *tp, struct timezone *tzp) { /* * Note: some broken versions only have 8 trailing zero's, the * correct epoch has 9 trailing zero's This magic number is the * number of 100 nanosecond intervals since January 1, 1601 (UTC) * until 00:00:00 January 1, 1970 */ static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL); SYSTEMTIME system_time; FILETIME file_time; uint64_t time; GetSystemTime(&system_time); SystemTimeToFileTime(&system_time, &file_time); time = ((uint64_t)file_time.dwLowDateTime); time += ((uint64_t)file_time.dwHighDateTime) << 32; tp->tv_sec = (long)((time - EPOCH) / 10000000L); tp->tv_usec = (long)(system_time.wMilliseconds * 1000); return 0; } #define open _open #define unlink _unlink #define mkdir(p, f) _mkdir(p) #define close _close #define strdup _strdup #define lstat _stat64 #define fstat _fstat64 #define stat __stat64 #else #define PATH_MAX 1024 #include <unistd.h> #include <sys/time.h> #include <sys/stat.h> #define O_BINARY 0 #define _setmode(a, b) #endif #include "cache.h" #include "util/skein.h" #define HEXP_LEN (128 + 2) typedef struct _disk_cache { cache c; cache * mem; kwrite_fn kwrite; vwrite_fn vwrite; kread_fn kread; vread_fn vread; const char *dirp; } disk_cache; /* Convert unsigned long long from network to host order */ static unsigned long long ntohull(const char *_in) { const unsigned char *in = (const unsigned char *)_in; return ((unsigned long long)in[0] << 56 | (unsigned long long)in[1] << 48 | (unsigned long long)in[2] << 40 | (unsigned long long)in[3] << 32 | (unsigned long long)in[4] << 24 | (unsigned long long)in[5] << 16 | (unsigned long long)in[6] << 8 | (unsigned long long)in[7]); } /* Convert unsigned long long from host to network order */ static void htonull(unsigned long long in, char *out) { out[0] = (unsigned char)(in >> 56); out[1] = (unsigned char)(in >> 48); out[2] = (unsigned char)(in >> 40); out[3] = (unsigned char)(in >> 32); out[4] = (unsigned char)(in >> 24); out[5] = (unsigned char)(in >> 16); out[6] = (unsigned char)(in >> 8); out[7] = (unsigned char)(in); } /* Concatenate prefix and suffix into a single path string while checking for overflow */ static int catp(char *path, const char *dirp, const char *rpath) { if (strlcpy(path, dirp, PATH_MAX) >= PATH_MAX) { errno = ENAMETOOLONG; return -1; } if (strlcat(path, rpath, PATH_MAX) >= PATH_MAX) { errno = ENAMETOOLONG; return -1; } return 0; } /* open() for a path specifed by the concatenation of dirp and rpath */ static int openp(const char *dirp, const char *rpath, int flags, int mode) { char path[PATH_MAX]; if (catp(path, dirp, rpath)) return -1; return open(path, flags, mode); } static int mkstempp(const char *dirp, char *template) { char path[PATH_MAX]; int res; if (catp(path, dirp, template)) return -1; res = mkstemp(path); /* We need to copy the result path back and set binary mode (for windows) */ if (res != -1) { _setmode(res, O_BINARY); memcpy(template, &path[strlen(dirp)], strlen(template)); } return res; } static int unlinkp(const char *dirp, const char *rpath) { char path[PATH_MAX]; if (catp(path, dirp, rpath)) return -1; return unlink(path); } static int renamep(const char *dirp, const char *ropath, const char *rnpath) { char opath[PATH_MAX]; char npath[PATH_MAX]; if (catp(opath, dirp, ropath)) return -1; if (catp(npath, dirp, rnpath)) return -1; return rename(opath, npath); } /* Ensure that a path exists by creating all intermediate directories */ int ensurep(const char *dirp, const char *rpath) { char path[PATH_MAX]; char *pp; char sep; if (dirp == NULL) { if (strlcpy(path, rpath, PATH_MAX) >= PATH_MAX) { errno = ENAMETOOLONG; return -1; } #ifdef _WIN32 /* Skip root dir (windows) */ pp = strchr(path, '\\'); if (pp) while (*pp == '\\') pp++; else pp = path; #else pp = path; /* Skip root dir (unix) */ while (*pp == '/') pp++; #endif } else { if (catp(path, dirp, rpath)) return -1; pp = path + strlen(dirp); } while ((pp = strpbrk(pp + 1, "\\/")) != NULL) { sep = *pp; *pp = '\0'; if (mkdir(path, 0777)) { if (errno != EEXIST) return -1; /* For now we suppose that EEXIST means that the directory is * already there. */ } *pp = sep; } return 0; } static int key_path(disk_cache *c, const cache_key_t key, char *out) { strb kb = STRB_STATIC_INIT; unsigned char hash[64]; int i; if (c->kwrite(&kb, key)) { strb_clear(&kb); return -1; } if (Skein_512((unsigned char *)kb.s, kb.l, hash)) { strb_clear(&kb); return -1; } strb_clear(&kb); if (snprintf(out, 10, "%02x%02x/%02x%02x", hash[0], hash[1], hash[2], hash[3]) != 9) return -1; for (i = 4; i < 64; i += 4) { if (snprintf(out+(i * 2 + 1), 9, "%02x%02x%02x%02x", hash[i], hash[i+1], hash[i+2], hash[i+3]) != 8) return -1; } return 0; } static int write_entry(disk_cache *c, const cache_key_t k, const cache_value_t v) { char hexp[HEXP_LEN]; char tmp_path[] = "tmp.XXXXXXXX"; strb b = STRB_STATIC_INIT; size_t kl, vl; int fd, err; if (key_path(c, k, hexp)) return -1; if (ensurep(c->dirp, hexp)) return -1; if (strb_ensure(&b, 16)) return -1; b.l = 16; c->kwrite(&b, k); kl = b.l - 16; c->vwrite(&b, v); vl = b.l - kl - 16; htonull(kl, b.s); htonull(vl, b.s + 8); if (strb_error(&b)) { strb_clear(&b); return -1; } fd = mkstempp(c->dirp, tmp_path); if (fd == -1) { strb_clear(&b); return -1; } err = strb_write(fd, &b); strb_clear(&b); close(fd); if (err) { unlinkp(c->dirp, tmp_path); return -1; } if (renamep(c->dirp, tmp_path, hexp)) { unlinkp(c->dirp, tmp_path); #ifdef _WIN32 /* On windows we can't rename over an existing file */ return (errno != EACCES) ? -1 : 0; #else return -1; #endif } return 0; } static int find_entry(disk_cache *c, const cache_key_t key, cache_key_t *_k, cache_value_t *_v) { struct stat st; strb b = STRB_STATIC_INIT; char *ts; size_t kl, vl; cache_key_t k; char hexp[HEXP_LEN]; int fd; if (key_path(c, key, hexp)) return 0; fd = openp(c->dirp, hexp, O_RDONLY|O_BINARY, 0); if (fd == -1) return 0; if (fstat(fd, &st)) { close(fd); return 0; } if (!(st.st_mode & S_IFREG)) { close(fd); return 0; } strb_read(&b, fd, st.st_size); close(fd); if (strb_error(&b) || b.l < 16) { strb_clear(&b); return 0; } kl = ntohull(b.s); vl = ntohull(b.s + 8); if (b.l < 16 + kl + vl) { strb_clear(&b); return 0; } ts = b.s; b.s += 16; b.l = kl; k = c->kread(&b); if (k && c->c.keq(key, k)) { if (_v) { b.s += kl; b.l = vl; *_v = c->vread(&b); if (*_v == NULL) goto error_find_entry; } if (_k) *_k = k; else c->c.kfree(k); b.s = ts; strb_clear(&b); return 1; } error_find_entry: if (k) c->c.kfree(k); b.s = ts; strb_clear(&b); return 0; } static int disk_add(cache *_c, cache_key_t k, cache_value_t v) { disk_cache *c = (disk_cache *)_c; /* Ignore write errors */ write_entry(c, k, v); return cache_add(c->mem, k, v); } static int disk_del(cache *_c, const cache_key_t key) { disk_cache *c = (disk_cache *)_c; char hexp[HEXP_LEN] = {0}; cache_del(c->mem, key); key_path(c, key, hexp); return (unlinkp(c->dirp, hexp) == 0); } static cache_value_t disk_get(cache *_c, const cache_key_t key) { disk_cache *c = (disk_cache *)_c; cache_key_t k; cache_value_t v; v = cache_get(c->mem, key); if (v != NULL) return v; if (find_entry(c, key, &k, &v)) { if (cache_add(c->mem, k, v)) return NULL; return v; } return NULL; } static void disk_destroy(cache *_c) { disk_cache *c = (disk_cache *)_c; cache_destroy(c->mem); free((void *)c->dirp); } cache *cache_disk(const char *dirpath, cache *mem, kwrite_fn kwrite, vwrite_fn vwrite, kread_fn kread, vread_fn vread, error *e) { struct stat st; disk_cache *res; char *dirp; size_t dirl = strlen(dirpath); char sep = '/'; /* This trickery is to make sure the path ends with a separator */ #ifdef _WIN32 if (dirpath[dirl - 1] == '\\') sep = '\\'; #endif if (dirpath[dirl - 1] != sep) dirl++; dirp = malloc(dirl + 1); /* With the NUL */ if (dirp == NULL) { error_sys(e, "malloc"); return NULL; } strlcpy(dirp, dirpath, dirl + 1); if (dirp[dirl - 1] != sep) { dirp[dirl - 1] = sep; dirp[dirl] = '\0'; } if (ensurep(NULL, dirp) != 0) { free(dirp); error_sys(e, "ensurep"); return NULL; } /* For Windows mkdir and lstat which can't handle trailing separator */ dirp[dirl - 1] = '\0'; mkdir(dirp, 0777); /* This may fail, but it's ok */ if (lstat(dirp, &st) != 0) { error_sys(e, "lstat"); return NULL; } /* Restore the good path at the end */ dirp[dirl - 1] = sep; if (!(st.st_mode & S_IFDIR)) { error_set(e, GA_SYS_ERROR, "Cache path exists but is not a directory"); return NULL; } res = calloc(sizeof(*res), 1); if (res == NULL) { error_sys(e, "calloc"); return NULL; } res->dirp = dirp; res->mem = mem; res->kwrite = kwrite; res->vwrite = vwrite; res->kread = kread; res->vread = vread; res->c.add = disk_add; res->c.del = disk_del; res->c.get = disk_get; res->c.destroy = disk_destroy; res->c.keq = mem->keq; res->c.khash = mem->khash; res->c.kfree = mem->kfree; res->c.vfree = mem->vfree; return (cache *)res; }
/* * This is a runaway item. Each time it is requested, it changes. * pokes just make it change again. */ HDDEDATA TestCountXfer( PXFERINFO pXferInfo, WORD iFmt) { CHAR szT[16]; LPSTR pszData; HDDEDATA hData; WORD i; switch (pXferInfo->wType) { case XTYP_POKE: pszComment = "Count poke received"; InvalidateRect(hwndServer, &rcComment, TRUE); InvalidateRect(hwndServer, &rcCount, TRUE); if (DdeGetData(pXferInfo->hData, szT, 10, 0)) { szT[9] = '\0'; sscanf(szT, "%ld", &count); for (i = 0; i < CFORMATS; i++) { if (hDataCount[i]) DdeFreeDataHandle(hDataCount[i]); hDataCount[i] = 0; } DdePostAdvise(idInst, pXferInfo->hszTopic, pXferInfo->hszItem); return(1); } break; case XTYP_REQUEST: pszComment = "Count data requested."; InvalidateRect(hwndServer, &rcComment, TRUE); case XTYP_ADVREQ: Delay(RenderDelay, FALSE); if (!hDataCount[iFmt]) { hDataCount[iFmt] = DdeCreateDataHandle(idInst, NULL, 0, 10, pXferInfo->hszItem, pXferInfo->wFmt, fAppowned ? HDATA_APPOWNED : 0); if (pszData = DdeAccessData(hDataCount[iFmt], NULL)) { wsprintf(pszData, "%ld", count); DdeUnaccessData(hDataCount[iFmt]); } } hData = hDataCount[iFmt]; if (!fAppowned) hDataCount[iFmt] = 0; return(hData); break; case XTYP_ADVSTART: return(1); } return(0); }
/******************************************************************************* ** ** Function BTM_SetInquiryScanType ** ** Description This function is called to set the iquiry scan-type to ** standard or interlaced. ** ** Returns BTM_SUCCESS if successful ** BTM_MODE_UNSUPPORTED if not a 1.2 device ** BTM_WRONG_MODE if the device is not up. ** *******************************************************************************/ tBTM_STATUS BTM_SetInquiryScanType (UINT16 scan_type) { BTM_TRACE_API ("BTM_SetInquiryScanType\n"); if (scan_type != BTM_SCAN_TYPE_STANDARD && scan_type != BTM_SCAN_TYPE_INTERLACED) { return (BTM_ILLEGAL_VALUE); } if (!controller_get_interface()->supports_interlaced_inquiry_scan()) { return (BTM_MODE_UNSUPPORTED); } if (scan_type != btm_cb.btm_inq_vars.inq_scan_type) { if (BTM_IsDeviceUp()) { if (btsnd_hcic_write_inqscan_type ((UINT8)scan_type)) { btm_cb.btm_inq_vars.inq_scan_type = scan_type; } else { return (BTM_NO_RESOURCES); } } else { return (BTM_WRONG_MODE); } } return (BTM_SUCCESS); }
/** * @brief Replaces the patterns in the given text with their correspondence * replacement in the A.C. Trie * * @param thiz * @param instr * @param mode * @param callback * @param param * @return *****************************************************************************/ int multifast_replace (AC_TRIE_t *thiz, AC_TEXT_t *instr, MF_REPLACE_MODE_t mode, MF_REPLACE_CALBACK_f callback, void *param) { ACT_NODE_t *current; ACT_NODE_t *next; struct mf_replacement_nominee nom; MF_REPLACEMENT_DATA_t *rd = &thiz->repdata; size_t position_r = 0; size_t backlog_pos = 0; if (thiz->trie_open) return -1; if (!rd->has_replacement) return -2; rd->cbf = callback; rd->user = param; rd->replace_mode = mode; thiz->text = instr; current = thiz->last_node; while (position_r < instr->length) { if (!(next = node_find_next_bs(current, instr->astring[position_r]))) { if(current->failure_node) current = current->failure_node; else position_r++; } else { current = next; position_r++; } if (current->final && next) { nom.pattern = current->to_be_replaced; nom.position = thiz->base_position + position_r; mf_repdata_booknominee (rd, &nom); } } backlog_pos = thiz->base_position + instr->length - current->depth; mf_repdata_do_replace (rd, backlog_pos); mf_repdata_savetobacklog (rd, backlog_pos); thiz->last_node = current; thiz->base_position += position_r; return 0; }
/* * Function: * bcm_tomahawk3_l2_tunnel_delete_all * Purpose: * Remove all tunnel processing indicating L2 addresses * Parameters: * unit - StrataXGS unit number */ int bcm_tomahawk3_l2_tunnel_delete_all(int unit) { TH3_L2_INIT(unit); #if defined(BCM_MPLS_SUPPORT) && defined(INCLUDE_L3) return bcm_td_metro_myStation_delete_all(unit); #else return BCM_E_UNAVAIL; #endif }
/** * clear_nlink - directly zero an inode's link count * @inode: inode * * This is a low-level filesystem helper to replace any * direct filesystem manipulation of i_nlink. See * drop_nlink() for why we care about i_nlink hitting zero. */ void clear_nlink(struct inode *inode) { if (inode->i_nlink) { inode->__i_nlink = 0; atomic_long_inc(&inode->i_sb->s_remove_count); } }
//=== RegistryParser.h - Linker-supported plugin registries -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines a command-line parser for a registry. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_REGISTRYPARSER_H #define LLVM_SUPPORT_REGISTRYPARSER_H #include "llvm/Support/CommandLine.h" #include "llvm/Support/Registry.h" namespace llvm { /// A command-line parser for a registry. Use like such: /// /// static cl::opt<Registry<Collector>::entry, false, /// RegistryParser<Collector> > /// GCOpt("gc", cl::desc("Garbage collector to use."), /// cl::value_desc()); /// /// To make use of the value: /// /// Collector *TheCollector = GCOpt->instantiate(); /// template <typename T, typename U = RegistryTraits<T> > class RegistryParser : public cl::parser<const typename U::entry*>, public Registry<T, U>::listener { typedef U traits; typedef typename U::entry entry; typedef typename Registry<T, U>::listener listener; protected: void registered(const entry &E) { addLiteralOption(traits::nameof(E), &E, traits::descof(E)); } public: void initialize(cl::Option &O) { listener::init(); cl::parser<const typename U::entry*>::initialize(O); } }; } #endif // LLVM_SUPPORT_REGISTRYPARSER_H
/* ========================================================================== Calculates number of elements in ring buffer until the end of buffer memory. If elements don't overlap memory, function acts like rb_count ========================================================================== */ static size_t rb_count_end ( const struct rb *rb ) { size_t end; size_t n; end = rb->count - rb->tail; n = (rb->head + end) & (rb->count - 1); return n < end ? n : end; }
/** * @brief This function send the tdls teardown request event. * * @param priv A pointer to mlan_private * * @return N/A */ void wlan_send_tdls_tear_down_request(pmlan_private priv) { t_u8 event_buf[100]; mlan_event *ptdls_event = (mlan_event *) event_buf; tdls_tear_down_event *tdls_evt = (tdls_tear_down_event *) ptdls_event->event_buf; sta_node *sta_ptr = MNULL; ENTER(); sta_ptr = (sta_node *) util_peek_list(priv->adapter->pmoal_handle, &priv->sta_list, priv->adapter->callbacks. moal_spin_lock, priv->adapter->callbacks. moal_spin_unlock); if (!sta_ptr) { LEAVE(); return; } while (sta_ptr != (sta_node *) & priv->sta_list) { if (sta_ptr->external_tdls) { ptdls_event->bss_index = priv->bss_index; ptdls_event->event_id = MLAN_EVENT_ID_DRV_TDLS_TEARDOWN_REQ; ptdls_event->event_len = sizeof(tdls_tear_down_event); memcpy(priv->adapter, (t_u8 *) tdls_evt->peer_mac_addr, sta_ptr->mac_addr, MLAN_MAC_ADDR_LENGTH); tdls_evt->reason_code = WLAN_REASON_TDLS_TEARDOWN_UNSPECIFIED; wlan_recv_event(priv, MLAN_EVENT_ID_DRV_TDLS_TEARDOWN_REQ, ptdls_event); } sta_ptr = sta_ptr->pnext; } LEAVE(); return; }
/* APPLE LOCAL begin ObjC GC */ /* Return 1 if EXPR is marked with the __strong attribute, -1 if it is marked with the __weak attribute, and 0 if it is marked with neither (regardless if it is otherwise GC-able). */ static int objc_is_strong_p (tree expr) { if (TYPE_P (expr) || DECL_P (expr)) { tree attr = lookup_attribute ("objc_gc", (TYPE_P (expr) ? TYPE_ATTRIBUTES (expr) : DECL_ATTRIBUTES (expr))); if (attr && TREE_VALUE (attr)) { if (TREE_VALUE (TREE_VALUE (attr)) == get_identifier ("strong")) return 1; if (TREE_VALUE (TREE_VALUE (attr)) == get_identifier ("weak")) return -1; } } return 0; }
/** * pci_vpd_size - determine actual size of Vital Product Data * @dev: pci device struct * @old_size: current assumed size, also maximum allowed size */ static size_t pci_vpd_size(struct pci_dev *dev, size_t old_size) { size_t off = 0; unsigned char header[1+2]; while (off < old_size && pci_read_vpd(dev, off, 1, header) == 1) { unsigned char tag; if (header[0] & PCI_VPD_LRDT) { tag = pci_vpd_lrdt_tag(header); if ((tag == PCI_VPD_LTIN_ID_STRING) || (tag == PCI_VPD_LTIN_RO_DATA) || (tag == PCI_VPD_LTIN_RW_DATA)) { if (pci_read_vpd(dev, off+1, 2, &header[1]) != 2) { dev_warn(&dev->dev, "invalid large VPD tag %02x size at offset %zu", tag, off + 1); return 0; } off += PCI_VPD_LRDT_TAG_SIZE + pci_vpd_lrdt_size(header); } } else { off += PCI_VPD_SRDT_TAG_SIZE + pci_vpd_srdt_size(header); tag = pci_vpd_srdt_tag(header); } if (tag == PCI_VPD_STIN_END) return off; if ((tag != PCI_VPD_LTIN_ID_STRING) && (tag != PCI_VPD_LTIN_RO_DATA) && (tag != PCI_VPD_LTIN_RW_DATA)) { dev_warn(&dev->dev, "invalid %s VPD tag %02x at offset %zu", (header[0] & PCI_VPD_LRDT) ? "large" : "short", tag, off); return 0; } } return 0; }